[User]
**Suffixation**:   a letter or a group of letters added to the end of a word to change its meaning.

:   :   :   :   :   :   :   ─────   or, as used herein   ─────

**Suffixation**:   the addition of a metric or "binary" metric suffix to a number, with/without rounding.

Task

Write a function(s) to append (if possible)   a metric   or   a "binary" metric   suffix to a
number   (displayed in decimal).

The number may be rounded   (as per user specification)   (via shortening of the number when the number of
digits past the decimal point are to be used).

Task requirements
:   :   * write a function (or functions) to add   (if possible)   a suffix to a number
        * the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified
        * the sign should be preserved   (if present)
        * the number may have commas within the number   (the commas need not be preserved)
        * the number may have a decimal point and/or an exponent as in:   -123.7e-01
        * the suffix that might be appended should be in uppercase;   however, the   **i**   should be in lowercase
        * support:

        :   :   * the            metric suffixes:   **K  M  G  T  P  E  Z  Y  X  W  V  U**
                * the binary metric suffixes:   **Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui**
                * the (full name) suffix:   **googol**   (lowercase)   (equal to **1e100**)     (optional)
                * a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits

        * validation of the (supplied/specified) arguments is optional but recommended
        * display   (with identifying text):

        :   :   * the original number   (with identifying text)
                * the number of digits past the decimal point being used   (or none, if not specified)
                * the type of suffix being used   (metric or "binary" metric)
                * the (new) number with the appropriate   (if any)   suffix
                * all output here on this page

Metric suffixes to be supported   (whether or not they're officially sanctioned)

```
     K     multiply the number by  10^3              kilo      (1,000)
     M     multiply the number by  10^6              mega      (1,000,000)
     G     multiply the number by  10^9              giga      (1,000,000,000)
     T     multiply the number by  10^12             tera      (1,000,000,000,000)
     P     multiply the number by  10^15             peta      (1,000,000,000,000,000)
     E     multiply the number by  10^18             exa       (1,000,000,000,000,000,000)
     Z     multiply the number by  10^21             zetta     (1,000,000,000,000,000,000,000)
     Y     multiply the number by  10^24             yotta     (1,000,000,000,000,000,000,000,000)
     X     multiply the number by  10^27             xenta     (1,000,000,000,000,000,000,000,000,000)
     W     multiply the number by  10^30             wekta     (1,000,000,000,000,000,000,000,000,000,000)
     V     multiply the number by  10^33             vendeka   (1,000,000,000,000,000,000,000,000,000,000,000)
     U     multiply the number by  10^36             udekta    (1,000,000,000,000,000,000,000,000,000,000,000,000)

```

"Binary" suffixes to be supported   (whether or not they're officially sanctioned)

```
     Ki    multiply the number by  2^10              kibi      (1,024)
     Mi    multiply the number by  2^20              mebi      (1,048,576)
     Gi    multiply the number by  2^30              gibi      (1,073,741,824)
     Ti    multiply the number by  2^40              tebi      (1,099,571,627,776)
     Pi    multiply the number by  2^50              pebi      (1,125,899,906,884,629)
     Ei    multiply the number by  2^60              exbi      (1,152,921,504,606,846,976)
     Zi    multiply the number by  2^70              zebi      (1,180,591,620,717,411,303,424)
     Yi    multiply the number by  2^80              yobi      (1,208,925,819,614,629,174,706,176)
     Xi    multiply the number by  2^90              xebi      (1,237,940,039,285,380,274,899,124,224)
     Wi    multiply the number by  2^100             webi      (1,267,650,600,228,229,401,496,703,205,376)
     Vi    multiply the number by  2^110             vebi      (1,298,074,214,633,706,907,132,624,082,305,024)
     Ui    multiply the number by  2^120             uebi      (1,329,227,995,784,915,872,903,807,060,280,344,576)

```

For instance, with this pseudo─code

```
                                 /* 1st arg: the number to be transformed.*/
                                 /* 2nd arg: # digits past the dec. point.*/
                                 /* 3rd arg: the type of suffix to use.   */
                                 /*         2   indicates "binary" suffix.*/
                                 /*        10   indicates  decimal suffix.*/
     a = '456,789,100,000,000'   /* "A"  has  eight  trailing zeros.      */
     say ' aa=' suffize(a)       /* Display a suffized number to terminal.*/
                                 /* The  "1"   below shows one decimal ···*/
                                 /*         digit past the decimal point. */
     n = suffize(a, 1)           /* SUFFIZE  is the function name.        */
     n = suffize(a, 1, 10)       /* (identical to the above statement.)   */
     say '  n=' n                /* Display value of  N  to terminal.     */
                                 /* Note the rounding that occurs.        */
     f = suffize(a, 1,  2)       /* SUFFIZE  with one fractional digit    */
     say '  f=' f                /* Display value of  F  to terminal.     */
                                 /* Display value in "binary" metric.     */
     bin = suffize(a, 5, 2)      /* SUFFIZE with binary metric suffix.    */
     say 'bin=' bin              /* Display value of  BIN  to terminal.   */
     win = suffize(a, 0, 2)      /* SUFFIZE with binary metric suffix.    */
     say 'win=' win              /* Display value of  WIN  to terminal.   */
     xvi = ' +16777216 '         /* this used to be a big computer ···    */
     big = suffize(xvi, , 2)     /* SUFFIZE with binary metric suffix.    */
     say 'big=' big              /* Display value of  BIG  to terminal.   */

```

would display:

```
      aa= 456.7891T
       n= 456.8T
       f= 415.4Ti
     bin= 415.44727Ti
     win= 415Ti
     big= 16Mi

```

Use these test cases

```
               87,654,321
              -998,877,665,544,332,211,000      3
              +112,233                          0
               16,777,216                       1
               456,789,100,000,000              2
               456,789,100,000,000              2      10
               456,789,100,000,000              5       2
               456,789,100,000.000e+00          0      10
              +16777216                         ,       2
               1.2e101
               (your primary disk free space)   1                  ◄■■■■■■■ optional

```

Use whatever parameterizing your computer language supports,   and it's permitted to create as many
separate functions as are needed   (if needed)   if   function arguments aren't allowed to
be omitted or varied.

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)

**Works with**: Rakudo version 2018.09

Pass in a number string, optionally a type, and optionally the number of digits to round to.

The types supported are B, M & G for binary, metric or gigantic. (At this point, the only gigantic unit is googol, so maybe it stands for googol. ¯\\_(ツ)\_/¯ )

If no type is specified, M (metric) is assumed.

If you desire the number to be rounded, pass in a number representing the placed past the decimal to round to. If you pass in a negative number for rounding, it will round to a negative number of places past the decimal.

```
sub sufficate ($val is copy, $type is copy = 'M', $round is copy = Any) {
   if +$type ~~ Int { $round = $type; $type = 'M' }
   my $s = '';
   if $val.substr(0,1) eq '-' { $s = '-'; $val.=substr(1) }
   $val.=subst(',', '', :g);
   if $val ~~ m:i/'e'/ {
       my ($m,$e) = $val.split(/<[eE]>/);
       $val = ($e < 0)
           ?? $m * FatRat.new(1,10**-$e)
           !! $m * 10**$e;
   }
   my %s = do given $type {
       when 'M' { <K M G T P E Z Y X W V U> Z=> (1000, * * 1000 … *) }
       when 'B' { <Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui> Z=> (1024, * * 1024 … *) }
       when 'G' { googol => 10**100 }
       default { return 'What we have here is a failure to communicate...' }
   }
   my $k = do given $val {
       when .abs < (my $m = min %s.values) { %s.first( *.value == $m ).key };
       when .abs > (my $x = max %s.values) { %s.first( *.value == $x ).key };
       default { %s.sort(*.value).first({$val.abs/%s{$_.key} < min %s.values}).key}
   }
   $round.defined
       ?? $s ~ comma(($val.abs/%s{$k}).round(10**-$round)) ~ $k
       !! $s ~ comma($val.abs/%s{$k}) ~ $k
}

sub comma ($i is copy) {
    my $s = $i < 0 ?? '-' !! '';
    my ($whole, $frac) = $i.split('.');
    $frac = $frac.defined ?? ".$frac" !! '';
    $s ~ $whole.abs.flip.comb(3).join(',').flip ~ $frac
}

## TESTING

my @tests =
   '87,654,321',
   '-998,877,665,544,332,211,000 3',
   '+112,233 0',
   '16,777,216 1',
   '456,789,100,000,000',
   '456,789,100,000,000 M 2',
   '456,789,100,000,000 B 5',
   '456,789,100,000.000e+00 M 0',
   '+16777216 B',
   '1.2e101 G',
   "{run('df', '/', :out).out.slurp.words[10] * 1024} B 2", # Linux df returns Kilobytes by default
   '347,344 M -2', # round to -2 past the decimal
   '1122334455 Q', # bad unit type example
;

printf "%33s : %s\n", $_, sufficate(|.words) for @tests;

```

Output:

```
                       87,654,321 : 87.654321M
   -998,877,665,544,332,211,000 3 : -998.878E
                       +112,233 0 : 112K
                     16,777,216 1 : 16.8M
              456,789,100,000,000 : 456.7891T
          456,789,100,000,000 M 2 : 456.79T
          456,789,100,000,000 B 5 : 415.44727Ti
      456,789,100,000.000e+00 M 0 : 457G
                      +16777216 B : 16Mi
                        1.2e101 G : 12googol
                 703674818560 B 2 : 655.35Gi
                     347,344 M -2 : 300K
                     1122334455 Q : What we have here is a failure to communicate...
```


[User]
Task

Compute the sum and product of an array of integers.

[Assistant]
(formerly Perl 6)

```
my @ary = 1, 5, 10, 100;
say 'Sum: ',     [+] @ary;
say 'Product: ', [*] @ary;
```


[User]
Task

Solve the "*Impossible Puzzle*":

X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X\*Y. Both S and P know all the information in this paragraph.

The following conversation occurs:

* S says "P does not know X and Y."
* P says "Now I know X and Y."
* S says "Now I also know X and Y!"

What are X and Y?

Guidance

It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y.
So for your convenience, here's a break-down:

|  | Quote | Implied fact |
| --- | --- | --- |
| 1) | S says "P does not know X and Y." | For every possible sum decomposition of the number X+Y, the product has in turn *more than one* product decomposition. |
| 2) | P says "Now I know X and Y." | The number X\*Y has *only one* product decomposition for which fact 1 is true. |
| 3) | S says "Now I also know X and Y." | The number X+Y has *only one* sum decomposition for which fact 2 is true. |

Terminology:

* *"sum decomposition" of a number* = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.
* *"product decomposition" of a number* = Any pair of positive integers (A, B) so that A\*B equals the number. Here, with the additional constraint 2 ≤ A < B.

Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains!
See the Python example for an implementation that uses this approach with a few optimizations.

See also

* Wikipedia:   Sum and Product Puzzle

---

[Assistant]
(formerly Perl 6)

**Translation of**: Python

**Works with**: Rakudo version 2016.07

```
sub grep-unique (&by, @list) { @list.classify(&by).values.grep(* == 1).map(*[0]) }
sub sums        ($n)         { ($_, $n - $_ for 2 .. $n div 2) }
sub product     ([$x, $y])   { $x * $y }
sub sum         ([$x, $y])   { $x + $y }

my @all-pairs = (|($_ X $_+1 .. 98) for 2..97);

# Fact 1:
my %p-unique := Set.new: map ~*, grep-unique &product, @all-pairs;
my @s-pairs = @all-pairs.grep: { none (%p-unique{~$_} for sums sum $_) };

# Fact 2:
my @p-pairs = grep-unique &product, @s-pairs;

# Fact 3:
my @final-pairs = grep-unique &sum, @p-pairs;

printf "X = %d, Y = %d\n", |$_ for @final-pairs;

```

Output:

```
X = 4, Y = 13
```


[User]
Task

Create a sum data type:

A sum data type is a data structure used to hold a value that could take on several different, but fixed, types.
Only one of the types can be in use at any one time.

Sum data types are considered an algebraic data type and are also known as tagged union, variant, variant record, choice type, discriminated union, disjoint union or coproduct.

Related task

* Compound data type

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 doesn't really have Sum Types as a formal data structure but they can be emulated with enums and switches or multi-dispatch. Note that in this case, feeding the dispatcher an incorrect value results in a hard fault; it doesn't just dispatch to the default. Of course those rules can be relaxed or made more restrictive depending on your particular use case.

```
enum Traffic-Signal < Red Yellow Green Blue >;

sub message (Traffic-Signal $light) {
    with $light {
        when Red    { 'Stop!'                                       }
        when Yellow { 'Speed Up!'                                   }
        when Green  { 'Go! Go! Go!'                                 }
        when Blue   { 'Wait a minute, How did we end up in Japan?!' }
        default     { 'Whut?'                                       }
    }
}

my \Pink = 'A Happy Balloon';

for Red, Green, Blue, Pink -> $signal {
    say message $signal;
}

```

Output:

```
Stop!
Go! Go! Go!
Wait a minute, How did we end up in Japan?!
Type check failed in binding to parameter '$light'; expected Traffic-Signal but got Str ("A Happy Balloon")
```


[User]
Task

Take a   Natural Number   in a given base and return the sum of its digits:

:   * **1**10         sums to   **1**
    * **1234**10   sums to   **10**
    * **fe**16       sums to   **29**
    * **f0e**16     sums to   **29**

[Assistant]
(formerly Perl 6)
This will handle input numbers in any base from 2 to 36.
The results are in base 10.

```
say Σ $_ for <1 1234 1020304 fe f0e DEADBEEF>;

sub Σ { [+] $^n.comb.map: { :36($_) } }
```

Output:

```
1
10
10
29
29
104
```


[User]
Task

The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below *n*.

Show output for *n* = 1000.

This is is the same as Project Euler problem 1.

**Extra credit:** do this efficiently for *n* = 1e20 or higher.

[Assistant]
(formerly Perl 6)

```
sub sum35($n) { [+] grep * %% (3|5), ^$n; }

say sum35 1000;
```

Output:

```
233168
```

Here's an analytical approach that scales much better for large values.

```
sub sum-mults($first, $limit) {
    (my $last = $limit - 1) -= $last % $first;
    ($last div $first) * ($first + $last) div 2;
}

sub sum35(\n) {
    sum-mults(3,n) + sum-mults(5,n) - sum-mults(15,n);
}

say sum35($_) for 1,10,100...10**30;
```

Output:

```
0
23
2318
233168
23331668
2333316668
233333166668
23333331666668
2333333316666668
233333333166666668
23333333331666666668
2333333333316666666668
233333333333166666666668
23333333333331666666666668
2333333333333316666666666668
233333333333333166666666666668
23333333333333331666666666666668
2333333333333333316666666666666668
233333333333333333166666666666666668
23333333333333333331666666666666666668
2333333333333333333316666666666666666668
233333333333333333333166666666666666666668
23333333333333333333331666666666666666666668
2333333333333333333333316666666666666666666668
233333333333333333333333166666666666666666666668
23333333333333333333333331666666666666666666666668
2333333333333333333333333316666666666666666666666668
233333333333333333333333333166666666666666666666666668
23333333333333333333333333331666666666666666666666666668
2333333333333333333333333333316666666666666666666666666668
233333333333333333333333333333166666666666666666666666666668
```


[User]
Compute the   **n**th   term of a series,   i.e. the sum of the   **n**   first terms of the corresponding sequence.

Informally this value, or its limit when   **n**   tends to infinity, is also called the *sum of the series*, thus the title of this task.

For this task, use:

:   :   :   :   :   :   S

                        n
                        =

                        ∑

                        k
                        =
                        1

                        n

                        1

                        k

                        2
                        {\displaystyle {\displaystyle S\_{n}=\sum \_{k=1}^{n}{\frac {1}{k^{2}}}}}

:   :   and compute

        S

        1000
        {\displaystyle {\displaystyle S\_{1000}}}

This approximates the   zeta function   for   S=2,   whose exact value

:   :   :   :   :   :   ζ
                        (
                        2
                        )
                        =

                        π

                        2
                        6
                        {\displaystyle {\displaystyle \zeta (2)={\pi ^{2} \over 6}}}

is the solution of the Basel problem.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.04

In general, the `$n`th partial sum of a series whose terms are given by a unary function `&f` is

```
[+] map &f, 1 .. $n
```

So what's needed in this case is

```
say [+] map { 1 / $^n**2 }, 1 .. 1000;
```

Or, using the "hyper" metaoperator to vectorize, we can use a more "point free" style while keeping traditional precedence:

```
say [+] 1 «/« (1..1000) »**» 2;
```

Or we can use the X "cross" metaoperator, which is convenient even if one side or the other is a scalar. In this case, we demonstrate a scalar on either side:

```
say [+] 1 X/ (1..1000 X** 2);
```

Note that cross ops are parsed as list infix precedence rather than using the precedence of the base op as hypers do. Hence the difference in parenthesization.

With list comprehensions, you can write:

```
say [+] (1 / $_**2 for 1..1000);
```

That's fine for a single result, but if you're going to be evaluating the sequence multiple times, you don't want to be recalculating the sum each time, so it's more efficient to define the sequence as a constant to let the run-time automatically cache those values already calculated. In a lazy language like Raku, it's generally considered a stronger abstraction to write the correct infinite sequence, and then take the part of it you're interested in.
Here we define an infinite sequence of partial sums (by adding a backslash into the reduction to make it look "triangular"), then take the 1000th term of that:

```
constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *;
say @x[1000];  # prints 1.64393456668156
```

Note that infinite constant sequences can be lazily generated in Raku, or this wouldn't work so well...

A cleaner style is to combine these approaches with a more FP look:

```
constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*;
say ζish[1000];
```

Perhaps the cleanest way is to just define the zeta function and evaluate it for s=2, possibly using memoization:

```
use experimental :cached;
sub ζ($s) is cached { [\+] 1..* X** -$s }
say ζ(2)[1000];
```

Notice how the thus-defined zeta function returns a lazy list of approximated values, which is arguably the closest we can get from the mathematical definition.


[User]
Given a positive integer, sum its positive divisors.

Task

Show the result for the first 100 positive integers.

[Assistant]
Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.

```
use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;

say "\nTau function - first 100:\n",        # ID
(1..*).map({ +.&divisors })[^100]\          # the task
.batch(20)».fmt("%3d").join("\n");          # display formatting

say "\nTau numbers - first 100:\n",         # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\   # the task
.batch(10)».&comma».fmt("%5s").join("\n");  # display formatting

say "\nDivisor sums - first 100:\n",        # ID
(1..*).map({ [+] .&divisors })[^100]\       # the task
.batch(20)».fmt("%4d").join("\n");          # display formatting

say "\nDivisor products - first 100:\n",    # ID
(1..*).map({ [×] .&divisors })[^100]\       # the task
.batch(5)».&comma».fmt("%16s").join("\n");  # display formatting

```

Output:

```
Tau function - first 100:
  1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6
  4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8
  2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12
  2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10
  5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9

Tau numbers - first 100:
    1     2     8     9    12    18    24    36    40    56
   60    72    80    84    88    96   104   108   128   132
  136   152   156   180   184   204   225   228   232   240
  248   252   276   288   296   328   344   348   360   372
  376   384   396   424   441   444   448   450   468   472
  480   488   492   504   516   536   560   564   568   584
  600   612   625   632   636   640   664   672   684   708
  712   720   732   776   792   804   808   824   828   852
  856   864   872   876   880   882   896   904   936   948
  972   996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096

Divisor sums - first 100:
   1    3    4    7    6   12    8   15   13   18   12   28   14   24   24   31   18   39   20   42
  32   36   24   60   31   42   40   56   30   72   32   63   48   54   48   91   38   60   56   90
  42   96   44   84   78   72   48  124   57   93   72   98   54  120   72  120   80   90   60  168
  62   96  104  127   84  144   68  126   96  144   72  195   74  114  124  140   96  168   80  186
 121  126   84  224  108  132  120  180   90  234  112  168  128  144  120  252   98  171  156  217

Divisor products - first 100:
               1                2                3                8                5
              36                7               64               27              100
              11            1,728               13              196              225
           1,024               17            5,832               19            8,000
             441              484               23          331,776              125
             676              729           21,952               29          810,000
              31           32,768            1,089            1,156            1,225
      10,077,696               37            1,444            1,521        2,560,000
              41        3,111,696               43           85,184           91,125
           2,116               47      254,803,968              343          125,000
           2,601          140,608               53        8,503,056            3,025
       9,834,496            3,249            3,364               59   46,656,000,000
              61            3,844          250,047        2,097,152            4,225
      18,974,736               67          314,432            4,761       24,010,000
              71  139,314,069,504               73            5,476          421,875
         438,976            5,929       37,015,056               79    3,276,800,000
          59,049            6,724               83  351,298,031,616            7,225
           7,396            7,569       59,969,536               89  531,441,000,000
           8,281          778,688            8,649            8,836            9,025
 782,757,789,696               97          941,192          970,299    1,000,000,000
```


[User]
Task

Find and display the sum of elements that are below the main diagonal of a matrix.

The matrix should be a square matrix.

:   :   :   ───   Matrix to be used:   ───

```
     [[1,3,7,8,10],
      [2,4,16,14,4],
      [3,1,9,18,11],
      [12,14,17,18,20],
      [7,1,3,9,5]]

```

[Assistant]
```
sub lower-triangle-sum (@matrix) { sum flat (1..@matrix).map( { @matrix[^$_]»[^($_-1)] } )»[*-1] }

say lower-triangle-sum
[
    [  1,  3,  7,  8, 10 ],
    [  2,  4, 16, 14,  4 ],
    [  3,  1,  9, 18, 11 ],
    [ 12, 14, 17, 18, 20 ],
    [  7,  1,  3,  9,  5 ]
];

```

Output:

```
69
```


[User]
Task

Find and show sum of first   **n**   cubes,   where **n < 50** (ie show 50 entries for n=0..49)

[Assistant]
```
my @sums_of_all_cubes = [\+] ^Inf X** 3;

say .fmt('%7d') for @sums_of_all_cubes.head(50).batch(10);

```

Output:

```
     0       1       9      36     100     225     441     784    1296    2025
  3025    4356    6084    8281   11025   14400   18496   23409   29241   36100
 44100   53361   64009   76176   90000  105625  123201  142884  164836  189225
216225  246016  278784  314721  354025  396900  443556  494209  549081  608400
672400  741321  815409  894916  980100 1071225 1168561 1272384 1382976 1500625

```


[User]
Task

Let **p(i)** be a sequence of prime numbers. such that 2=p(1), 3=p(2), 5=p(3), ...

Consider the **p(1),p(3),p(5), ... ,p(i)**, for each **p(i) < 1,000** and **i** is odd.

Let **sum** be any prefix sum of these primesa.

If **sum** is prime then print **i**, **p(i)** and **sum**.

[Assistant]
```
my @odd  = grep { ++$ !%% 2 }, grep &is-prime, 2 ..^ 1000;
my @sums = [\+] @odd;

say .fmt('%5d') for grep { .[2].is-prime }, ( (1,3…*) Z @odd Z @sums );

```

Output:

```
    1     2     2
    3     5     7
   11    31    89
   27   103   659
   35   149  1181
   67   331  5021
   91   467  9923
   95   499 10909
   99   523 11941
  119   653 17959
  143   823 26879
```


[User]
Task

Find and show here all positive integers **n** less than **100** where:

* the sum of the digits of the square of **n** is prime; and
* the sum of the digits of the cube of **n** is also prime.

Example

**16** satisfies the task descrption because 16 x 16 = 256 has a digit sum of 13 which is prime and
16 x 16 x 16 = 4096 has a digit sum of 19 which is also prime.

[Assistant]
```
say ^100 .grep: { .².comb.sum.is-prime && .³.comb.sum.is-prime }

```

Output:

```
(16 17 25 28 34 37 47 52 64)
```


[User]
Task

Write a program to find the sum of squares of a numeric vector.

The program should work on a zero-length vector (with an answer of   **0**).

Related task

* Mean

[Assistant]
(formerly Perl 6)

```
say [+] map * ** 2, (3, 1, 4, 1, 5, 9);
```

If this expression seems puzzling, note that `* ** 2` is equivalent to `{$^x ** 2}`— the leftmost asterisk is not the multiplication operator but the `Whatever` star, which specifies currying behavior.
Another convenient way to distribute the exponentiation is via the cross metaoperator, which
as a list infix is looser than comma in precedence but tighter than the reduction list operator:

```
say [+] <3 1 4 1 5 9> X** 2
```


[User]
Task

Find and show numbers   **n**   with property that the sum of the decimal digits of   **n**   is substring of   **n**,   where   **n   <   1,000**

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]
```
say "{+$_} matching numbers\n{.batch(10)».fmt('%3d').join: "\n"}" given (^1000).grep: { .contains: .comb.sum }

```

Output:

```
48 matching numbers
  0   1   2   3   4   5   6   7   8   9
 10  20  30  40  50  60  70  80  90 100
109 119 129 139 149 159 169 179 189 199
200 300 400 500 600 700 800 900 910 911
912 913 914 915 916 917 918 919
```


[User]
Task

Show on this page the first 20 prime sums of two consecutive integers.

Extra credit

Show the ten millionth such prime sum.

[Assistant]
```
my @n-n1-triangular = map { $_, $_ + 1, $_ + ($_ + 1) }, ^Inf;

my @wanted = @n-n1-triangular.grep: *.[2].is-prime;

printf "%2d + %2d = %2d\n", |.list for @wanted.head(20);

```

Output:

```
 1 +  2 =  3
 2 +  3 =  5
 3 +  4 =  7
 5 +  6 = 11
 6 +  7 = 13
 8 +  9 = 17
 9 + 10 = 19
11 + 12 = 23
14 + 15 = 29
15 + 16 = 31
18 + 19 = 37
20 + 21 = 41
21 + 22 = 43
23 + 24 = 47
26 + 27 = 53
29 + 30 = 59
30 + 31 = 61
33 + 34 = 67
35 + 36 = 71
36 + 37 = 73

```


[User]
Task

Find solutions to the    *sum to one hundred*    puzzle.

Add (insert) the mathematical
operators      **+**    or    **-**      (plus
or minus)   before any of the digits in the

decimal numeric string    **123456789**    such that the
resulting mathematical expression adds up to a

particular sum   (in this iconic case,   **100**).

Example:

```
             123 + 4 - 5 + 67 - 89   =   100

```

Show all output here.

:   * Show all solutions that sum to    **100**
    * Show the sum that has the maximum   *number*   of solutions   (from zero to infinity‡)
    * Show the lowest positive sum that   *can't*   be expressed   (has no solutions),   using the rules for this task
    * Show the ten highest numbers that can be expressed using the rules for this task   (extra credit)

‡   (where   *infinity*   would be a relatively small   123,456,789)

An example of a sum that can't be expressed   (within the rules of this task)   is:   **5074**

(which,   of course,   isn't the lowest positive sum that can't be expressed).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.03

```
my $sum = 100;
my $N   = 10;
my @ops = ['-', ''], |( [' + ', ' - ', ''] xx 8 );
my @str = [X~] map { .Slip }, ( @ops Z 1..9 );
my %sol = @str.classify: *.subst( ' - ', ' -', :g )\
                          .subst( ' + ',  ' ', :g ).words.sum;

my %count.push: %sol.map({ .value.elems => .key });

my $max-solutions    = %count.max( + *.key );
my $first-unsolvable = first { %sol{$_} :!exists }, 1..*;
sub n-largest-sums (Int $n) { %sol.sort(-*.key)[^$n].fmt: "%8s => %s\n" }

given %sol{$sum}:p {
    say "{.value.elems} solutions for sum {.key}:";
    say "    $_" for .value.list;
}

.say for :$max-solutions, :$first-unsolvable, "$N largest sums:", n-largest-sums($N);

```

Output:

```
12 solutions for sum 100:
    -1 + 2 - 3 + 4 + 5 + 6 + 78 + 9
    1 + 2 + 3 - 4 + 5 + 6 + 78 + 9
    1 + 2 + 34 - 5 + 67 - 8 + 9
    1 + 23 - 4 + 5 + 6 + 78 - 9
    1 + 23 - 4 + 56 + 7 + 8 + 9
    12 + 3 + 4 + 5 - 6 - 7 + 89
    12 + 3 - 4 + 5 + 67 + 8 + 9
    12 - 3 - 4 + 5 - 6 + 7 + 89
    123 + 4 - 5 + 67 - 89
    123 + 45 - 67 + 8 - 9
    123 - 4 - 5 - 6 - 7 + 8 - 9
    123 - 45 - 67 + 89
max-solutions => 46 => [-9 9]
first-unsolvable => 211
10 largest sums:
123456789 => 123456789
 23456790 => 1 + 23456789
 23456788 => -1 + 23456789
 12345687 => 12345678 + 9
 12345669 => 12345678 - 9
  3456801 => 12 + 3456789
  3456792 => 1 + 2 + 3456789
  3456790 => -1 + 2 + 3456789
  3456788 => 1 - 2 + 3456789
  3456786 => -1 - 2 + 3456789
```


[User]
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:

```
       0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...

```

The terms generated grow in length geometrically and never converge.

Another way to generate a self-referential sequence is to summarize the previous term.

Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.

```
       0, 10, 1110, 3110, 132110, 13123110, 23124110 ...

```

Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.

Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)

Task

Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.

```
Seed Value(s): 9009 9090 9900

Iterations: 21

Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110

```

Related tasks

* Fours is the number of letters in the ...
* Look-and-say sequence
* Number names
* Self-describing numbers
* Spelling of ordinal numbers

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

Also see

* The On-Line Encyclopedia of Integer Sequences.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
my @list;
my $longest = 0;
my %seen;

for 1 .. 1000000 -> $m {
    next unless $m ~~ /0/;         # seed must have a zero
    my $j = join '', $m.comb.sort;
    next if %seen{$j}:exists;      # already tested a permutation
    %seen{$j} = '';
    my @seq = converging($m);
    my %elems;
    my $count;
    for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };
    if $longest == $count {
        @list.push($m);
    }
    elsif $longest < $count {
        $longest = $count;
        @list = $m;
        print "\b" x 20, "$count, $m"; # monitor progress
    }
};

for @list -> $m {
    say "\nSeed Value(s): ", my $seeds = ~permutations($m).unique.grep( { .substr(0,1) != 0 } );
    my @seq = converging($m);
    my %elems;
    my $count;
    for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };
    say "\nIterations: ", $count;
    say "\nSequence: (Only one shown per permutation group.)";
   .say for |@seq[^$count], "\n";
}

sub converging ($seed) { return $seed, -> $l { join '', map { $_.value.elems~$_.key }, $l.comb.classify({$^b}).sort: {-$^c.key} } ... * }

sub permutations ($string, $sofar? = '' ) {
    return $sofar unless $string.chars;
    my @perms;
    for ^$string.chars -> $idx {
        my $this = $string.substr(0,$idx)~$string.substr($idx+1);
        my $char = substr($string, $idx,1);
        @perms.push( |permutations( $this, join '', $sofar, $char ) );
    }
    return @perms;
}

```

Output:

```
Seed Value(s): 9009 9090 9900

Iterations: 21

Sequence: (Only one shown per permutation group.)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110

```


[User]
Task

Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.

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

my @primes    = grep *.is-prime, ^Inf;
my @primesums = [\+] @primes;
say "{.elems} cumulative prime sums:\n",
    .map( -> $p {
        sprintf "The sum of the first %3d (up to {@primes[$p]}) is prime: %s",
        1 + $p, comma @primesums[$p]
      }
    ).join("\n")
    given grep { @primesums[$_].is-prime }, ^1000;

```

Output:

```
76 cumulative prime sums:
The sum of the first   1 (up to 2) is prime: 2
The sum of the first   2 (up to 3) is prime: 5
The sum of the first   4 (up to 7) is prime: 17
The sum of the first   6 (up to 13) is prime: 41
The sum of the first  12 (up to 37) is prime: 197
The sum of the first  14 (up to 43) is prime: 281
The sum of the first  60 (up to 281) is prime: 7,699
The sum of the first  64 (up to 311) is prime: 8,893
The sum of the first  96 (up to 503) is prime: 22,039
The sum of the first 100 (up to 541) is prime: 24,133
The sum of the first 102 (up to 557) is prime: 25,237
The sum of the first 108 (up to 593) is prime: 28,697
The sum of the first 114 (up to 619) is prime: 32,353
The sum of the first 122 (up to 673) is prime: 37,561
The sum of the first 124 (up to 683) is prime: 38,921
The sum of the first 130 (up to 733) is prime: 43,201
The sum of the first 132 (up to 743) is prime: 44,683
The sum of the first 146 (up to 839) is prime: 55,837
The sum of the first 152 (up to 881) is prime: 61,027
The sum of the first 158 (up to 929) is prime: 66,463
The sum of the first 162 (up to 953) is prime: 70,241
The sum of the first 178 (up to 1061) is prime: 86,453
The sum of the first 192 (up to 1163) is prime: 102,001
The sum of the first 198 (up to 1213) is prime: 109,147
The sum of the first 204 (up to 1249) is prime: 116,533
The sum of the first 206 (up to 1277) is prime: 119,069
The sum of the first 208 (up to 1283) is prime: 121,631
The sum of the first 214 (up to 1307) is prime: 129,419
The sum of the first 216 (up to 1321) is prime: 132,059
The sum of the first 296 (up to 1949) is prime: 263,171
The sum of the first 308 (up to 2029) is prime: 287,137
The sum of the first 326 (up to 2161) is prime: 325,019
The sum of the first 328 (up to 2203) is prime: 329,401
The sum of the first 330 (up to 2213) is prime: 333,821
The sum of the first 332 (up to 2237) is prime: 338,279
The sum of the first 334 (up to 2243) is prime: 342,761
The sum of the first 342 (up to 2297) is prime: 360,979
The sum of the first 350 (up to 2357) is prime: 379,667
The sum of the first 356 (up to 2393) is prime: 393,961
The sum of the first 358 (up to 2411) is prime: 398,771
The sum of the first 426 (up to 2957) is prime: 581,921
The sum of the first 446 (up to 3137) is prime: 642,869
The sum of the first 458 (up to 3251) is prime: 681,257
The sum of the first 460 (up to 3257) is prime: 687,767
The sum of the first 464 (up to 3301) is prime: 700,897
The sum of the first 480 (up to 3413) is prime: 754,573
The sum of the first 484 (up to 3461) is prime: 768,373
The sum of the first 488 (up to 3491) is prime: 782,263
The sum of the first 512 (up to 3671) is prime: 868,151
The sum of the first 530 (up to 3821) is prime: 935,507
The sum of the first 536 (up to 3863) is prime: 958,577
The sum of the first 548 (up to 3947) is prime: 1,005,551
The sum of the first 568 (up to 4129) is prime: 1,086,557
The sum of the first 620 (up to 4583) is prime: 1,313,041
The sum of the first 630 (up to 4657) is prime: 1,359,329
The sum of the first 676 (up to 5051) is prime: 1,583,293
The sum of the first 680 (up to 5087) is prime: 1,603,597
The sum of the first 696 (up to 5233) is prime: 1,686,239
The sum of the first 708 (up to 5351) is prime: 1,749,833
The sum of the first 734 (up to 5563) is prime: 1,891,889
The sum of the first 762 (up to 5807) is prime: 2,051,167
The sum of the first 768 (up to 5849) is prime: 2,086,159
The sum of the first 776 (up to 5897) is prime: 2,133,121
The sum of the first 780 (up to 5939) is prime: 2,156,813
The sum of the first 784 (up to 6007) is prime: 2,180,741
The sum of the first 808 (up to 6211) is prime: 2,327,399
The sum of the first 814 (up to 6263) is prime: 2,364,833
The sum of the first 820 (up to 6301) is prime: 2,402,537
The sum of the first 836 (up to 6427) is prime: 2,504,323
The sum of the first 844 (up to 6529) is prime: 2,556,187
The sum of the first 848 (up to 6563) is prime: 2,582,401
The sum of the first 852 (up to 6581) is prime: 2,608,699
The sum of the first 926 (up to 7243) is prime: 3,120,833
The sum of the first 942 (up to 7433) is prime: 3,238,237
The sum of the first 984 (up to 7757) is prime: 3,557,303
The sum of the first 992 (up to 7853) is prime: 3,619,807
```


[User]
Task

The task description is taken from Project Euler (https://projecteuler.net/problem=10)

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17

Find the sum of all the primes below **two million**

[Assistant]
Slow, but only using compiler built-ins (about 5 seconds)

```
say sum (^2e6).grep: {.&is-prime};

```

Output:

```
142913828922
```

Much faster using external libraries (well under half a second)

```
use Math::Primesieve;
my $sieve = Math::Primesieve.new;
say sum $sieve.primes(2e6.Int);

```

Same output


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

Draw a Sunflower fractal

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.06

This is not really a fractal. It is more accurately an example of a Fibonacci spiral or Phi-packing.

Or, to be completely accurate: It is a variation of a generative Fermat's spiral using the Vogel model to implement phi-packing. See: https://thatsmaths.com/2014/06/05/sunflowers-and-fibonacci-models-of-efficiency

```
use SVG;

my $seeds  = 3000;
my @center = 300, 300;
my $scale  = 5;

constant \φ = (3 - 5.sqrt) / 2;

my @c = map {
    my ($x, $y) = ($scale * .sqrt) «*« |cis($_ * φ * τ).reals »+« @center;
    [ $x.round(.01), $y.round(.01), (.sqrt * $scale / 100).round(.1) ]
}, 1 .. $seeds;

say SVG.serialize(
    svg => [
        :600width, :600height, :style<stroke:yellow>,
        :rect[:width<100%>, :height<100%>, :fill<black>],
        |@c.map( { :circle[:cx(.[0]), :cy(.[1]), :r(.[2])] } ),
    ],
);

```

See: Phi packing (SVG image)


[User]
A super-d number is a positive, decimal (base ten) integer   **n**   such that   **d × nd**   has at least   **d**   consecutive digits   **d**   where

```
   2 ≤ d ≤ 9

```

For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.

**Super-d**   numbers are also shown on   **MathWorld**™   as   **super-*d***    or   **super-*d***.

Task
:   * Write a function/procedure/routine to find super-d numbers.
    * For   **d=2**   through   **d=6**,   use the routine to show the first   **10**   super-d numbers.

Extra credit
:   * Show the first   **10**   super-7, super-8, and/or super-9 numbers   (optional).

See also
:   * Wolfram MathWorld - Super-d Number.
    * OEIS: A014569 - Super-3 Numbers.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

2 - 6 take a few seconds, 7 about 17 seconds, 8 about 90... 9, bleh... around 700 seconds.

```
sub super (\d) {
    my \run = d x d;
    ^∞ .hyper.grep: -> \n { (d * n ** d).Str.contains: run }
}

(2..9).race(:1batch).map: {
    my $now = now;
    put "\nFirst 10 super-$_ numbers:\n{.&super[^10]}\n{(now - $now).round(.1)} sec."
}

```

```
First 10 super-2 numbers:
19 31 69 81 105 106 107 119 127 131
0.1 sec.

First 10 super-3 numbers:
261 462 471 481 558 753 1036 1046 1471 1645
0.1 sec.

First 10 super-4 numbers:
1168 4972 7423 7752 8431 10267 11317 11487 11549 11680
0.3 sec.

First 10 super-5 numbers:
4602 5517 7539 12955 14555 20137 20379 26629 32767 35689
0.6 sec.

First 10 super-6 numbers:
27257 272570 302693 323576 364509 502785 513675 537771 676657 678146
5.2 sec.

First 10 super-7 numbers:
140997 490996 1184321 1259609 1409970 1783166 1886654 1977538 2457756 2714763
17.1 sec.

First 10 super-8 numbers:
185423 641519 1551728 1854230 6415190 12043464 12147605 15517280 16561735 18542300
92.1 sec.

First 10 super-9 numbers:
17546133 32613656 93568867 107225764 109255734 113315082 121251742 175461330 180917907 182557181
704.7 sec.
```


[User]
A super-Poulet number is a Poulet number (or Fermat pseudoprime to base 2) whose every divisor ***d*** evenly divides ***2d − 2***.

Task

* Find and display the first **20** super-Poulet numbers.

Stretch

* Find and display the index and value of the first super-Poulet number greater than one million.

See also

* Task: Fermat pseudoprimes * Wikipedia: super-Poulet number * OEIS:A050217 - super-Poulet numbers

[Assistant]
```
use Prime::Factor;
use Lingua::EN::Numbers;

my @poulet = lazy (2..*).hyper(:2000batch).grep: { !.is-prime && (1 == expmod 2, $_ - 1, $_) }
my @super-poulet = @poulet.grep: { all .&divisors.skip(1).map: { 2 == expmod 2, $_, $_ } }

say "First 20 super-Poulet numbers:\n" ~ @super-poulet[^20].gist;

for 1e6.Int, 1e7.Int -> $threshold {
    say "\nIndex and value of first super-Poulet greater than {$threshold.&cardinal}:";
    my $index = @super-poulet.first: * > $threshold, :k;
    say "{(1+$index).&ordinal-digit} super-Poulet number == " ~ @super-poulet[$index].,
}

```

Output:

```
First 20 super-Poulet numbers:
(341 1387 2047 2701 3277 4033 4369 4681 5461 7957 8321 10261 13747 14491 15709 18721 19951 23377 31417 31609)

Index and value of first super-Poulet greater than one million:
109th super-Poulet number == 1,016,801

Index and value of first super-Poulet greater than ten million:
317th super-Poulet number == 10,031,653

```


[User]
A superellipse is a geometric figure defined as the set of all points (x, y) with

:   :   :   |

            x
            a
            |

            n

            +

            |

            y
            b
            |

            n

            =
            1
            ,
            {\displaystyle {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}}

where *n*, *a*, and *b* are positive numbers.

Task

Draw a superellipse with n = 2.5, and a = b = 200

[Assistant]
(formerly Perl 6)

```
my (\a, \b, \n) = 200, 200, 2.5;

# y in terms of x
sub y ($x) { floor b × (1 - ($x/a).abs ** n ) ** (1/n) }

# find point pairs for one quadrant
my @q = flat map -> \x { x, y(x) }, ^(a+1);

my $out = open('superellipse.svg', :w);
$out.print: [~] qq|<svg height="{b×2}" width="{a×2}" xmlns="http://www.w3.org/2000/svg">\n|,
  pline( @q ),
  pline( @q «×» < 1 -1> ), # flip and mirror
  pline( @q «×» <-1 -1> ), # for the other
  pline( @q «×» <-1  1> ), # three quadrants
  '</svg>';

sub pline (@q) {
  qq|<polyline points="{@q}"
  style="fill:none;stroke:black;stroke-width:3"
  transform="translate({a}, {b})" />\n|
}

```

Superellipse (offsite image)


[User]
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.

For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.

A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.

A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.

The "too obvious" method of creation generates a string of length N!\*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.

Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.

The problem of generating the shortest superpermutation for each N *might* be NP complete, although the minimal strings for small values of N have been found by brute -force searches.

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

Reference

* The Minimal Superpermutation Problem. by Nathaniel Johnston.
* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
* Superpermutations - Numberphile. A video
* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
* New Superpermutations Discovered! Standupmaths & Numberphile.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

```
for 1..8 -> $len {
  my $pre = my $post = my $t = '';
  for  ('a'..'z')[^$len].permutations -> @p {
     $t = @p.join('');
     $post ~= $t        unless index($post, $t);
     $pre   = $t ~ $pre unless index($pre,  $t);
  }
  printf "%1d: %8d %8d\n", $len, $pre.chars, $post.chars;
}

```

Output:

```
1:        1        1
2:        4        4
3:       12       15
4:       48       64
5:      240      325
6:     1440     1956
7:    10080    13699
8:    80640   109600
```


[User]
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).

It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed.

Task

Take the closed polygon defined by the points:

:   [
    (
    50
    ,
    150
    )
    ,
    (
    200
    ,
    50
    )
    ,
    (
    350
    ,
    150
    )
    ,
    (
    350
    ,
    300
    )
    ,
    (
    250
    ,
    300
    )
    ,
    (
    200
    ,
    250
    )
    ,
    (
    150
    ,
    350
    )
    ,
    (
    100
    ,
    250
    )
    ,
    (
    100
    ,
    200
    )
    ]
    {\displaystyle {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}}

and clip it by the rectangle defined by the points:

:   [
    (
    100
    ,
    100
    )
    ,
    (
    300
    ,
    100
    )
    ,
    (
    300
    ,
    300
    )
    ,
    (
    100
    ,
    300
    )
    ]
    {\displaystyle {\displaystyle [(100,100),(300,100),(300,300),(100,300)]}}

Print the sequence of points that define the resulting clipped polygon.

Extra credit

Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.

(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

**Translation of**: Sidef

```
sub intersection ($L11, $L12, $L21, $L22) {
    my ($Δ1x, $Δ1y) = $L11 »-« $L12;
    my ($Δ2x, $Δ2y) = $L21 »-« $L22;
    my $n1 = $L11[0] * $L12[1] - $L11[1] * $L12[0];
    my $n2 = $L21[0] * $L22[1] - $L21[1] * $L22[0];
    my $n3 = 1 / ($Δ1x * $Δ2y - $Δ2x * $Δ1y);
    (($n1 * $Δ2x - $n2 * $Δ1x) * $n3, ($n1 * $Δ2y - $n2 * $Δ1y) * $n3)
}

sub is-inside ($p1, $p2, $p3) {
    ($p2[0] - $p1[0]) * ($p3[1] - $p1[1]) > ($p2[1] - $p1[1]) * ($p3[0] - $p1[0])
}

sub sutherland-hodgman (@polygon, @clip) {
    my @output = @polygon;
    my $clip-point1 = @clip.tail;
    for @clip -> $clip-point2 {
        my @input = @output;
        @output = ();
        my $start = @input.tail;
        for @input -> $end {
            if is-inside($clip-point1, $clip-point2, $end) {
                @output.push: intersection($clip-point1, $clip-point2, $start, $end)
                  unless is-inside($clip-point1, $clip-point2, $start);
                @output.push: $end;
            } elsif is-inside($clip-point1, $clip-point2, $start) {
                @output.push: intersection($clip-point1, $clip-point2, $start, $end);
            }
            $start = $end;
        }
        $clip-point1 = $clip-point2;
    }
    @output
}

my @polygon = (50,  150), (200, 50),  (350, 150), (350, 300), (250, 300),
              (200, 250), (150, 350), (100, 250), (100, 200);

my @clip    = (100, 100), (300, 100), (300, 300), (100, 300);

my @clipped = sutherland-hodgman(@polygon, @clip);

say "Clipped polygon: ", @clipped;

# Output an SVG as well as it is easier to visualize
use SVG;
my $outfile = 'Sutherland-Hodgman-polygon-clipping-perl6.svg'.IO.open(:w);
$outfile.say: SVG.serialize(
    svg => [
        :400width, :400height,
        :rect[ :400width, :400height, :fill<white> ],
        :text[ :10x, :20y, "Polygon (blue)" ],
        :text[ :10x, :35y, "Clip port (green)" ],
        :text[ :10x, :50y, "Clipped polygon (red)" ],
        :polyline[ :points(@polygon.join: ','), :style<stroke:blue>,  :fill<blue>,  :opacity<.3> ],
        :polyline[ :points(   @clip.join: ','), :style<stroke:green>, :fill<green>, :opacity<.3> ],
        :polyline[ :points(@clipped.join: ','), :style<stroke:red>,   :fill<red>,   :opacity<.5> ],
    ],
);

```

Output:

```
Clipped polygon: [(100 116.666667) (125 100) (275 100) (300 116.666667) (300 300) (250 300) (200 250) (175 300) (125 300) (100 250)]
```

Also see output image: offsite SVG image


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

In number theory, **Sylvester's sequence** is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.

Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to **1** more rapidly than any other series of unit fractions with the same number of terms.

Further, the sum of the first **k** terms of the infinite series of reciprocals provides the closest possible underestimate of **1** by any k-term Egyptian fraction.

Task

* Write a routine (function, procedure, generator, whatever) to calculate **Sylvester's sequence**.
* Use that routine to show the values of the first **10** elements in the sequence.
* Show the sum of the reciprocals of the first **10** elements on the sequence, ideally as an exact fraction.

Related tasks

* Egyptian fractions
* Harmonic series

See also

* OEIS A000058 - Sylvester's sequence

[Assistant]
```
my @S = {1 + [*] @S[^($++)]} … *;

put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];

say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ };

```

Output:

```
First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of first 10 elements: 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999635
```


[User]
Task

Given two sets *A* and *B*, compute

(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle {\displaystyle (A\setminus B)\cup (B\setminus A).}}

That is, enumerate the items that are in *A* or *B* but not both. This set is called the symmetric difference of *A* and *B*.

In other words:

(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle {\displaystyle (A\cup B)\setminus (A\cap B)}}
 (the set of items that are in at least one of *A* or *B* minus the set of items that are in both *A* and *B*).

Optionally, give the individual differences (

A
∖
B
{\displaystyle {\displaystyle A\setminus B}}
 and

B
∖
A
{\displaystyle {\displaystyle B\setminus A}}
) as well.

Test cases

```
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}

```

Notes

1. If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of `a = ["John", "Serena", "Bob", "Mary", "Serena"]` and `b = ["Jim", "Mary", "John", "Jim", "Bob"]` should produce the result of just two strings: `["Serena", "Jim"]`, in any order.
2. In the mathematical notation above `A \ B` gives the set of items in A that are not in B; `A ∪ B` gives the set of items in both A and B, (their *union*); and `A ∩ B` gives the set of items that are in both A and B (their *intersection*).

[Assistant]
(formerly Perl 6)

```
my \A = set <John Serena Bob Mary Serena>;
my \B = set <Jim Mary John Jim Bob>;

say  A ∖ B; # Set subtraction
say  B ∖ A; # Set subtraction
say (A ∪ B) ∖ (A ∩ B);  # Symmetric difference, via basic set operations
say  A ⊖ B;             # Symmetric difference, via dedicated operator

```

Output:

```
set(Serena)
set(Jim)
set(Jim, Serena)
set(Jim, Serena)
```


[User]
Sync subtitles

**Sync subtitles**

Sometimes, when you download a movie, the subtitles are out of sync with the audio in this movie. Video players like VLC solve the problem, but it must be done manually.

Make a program that takes the "movie.srt" file, and synchronizes the subtitles "n" seconds.

* Try to fast-forward the subtitles by 9 seconds.
* Try rolling back the subtitles by 9 seconds.

Take the excerpt from the following subtitles file as an example:

**movie.srt**

```
1
00:01:31,550 --> 00:01:36,347
Four billion years ago,
the first marine life forms.

2
00:01:36,555 --> 00:01:42,019
First came the fish...then slowly
other life forms evolved.

3
00:01:42,144 --> 00:01:43,979
Therefore, our ancestors...

4
00:01:43,979 --> 00:01:45,898
...came from fish.

5
00:01:46,232 --> 00:01:47,608
Everyone, come and see this.

6
00:01:47,733 --> 00:01:50,361
Cretaceous Tyrannosaurus.

7
00:01:50,736 --> 00:01:52,488
Ferocious!

8
00:01:58,035 --> 00:01:58,869
Red,

9
00:01:59,203 --> 00:02:00,079
Pong!

10
00:02:02,540 --> 00:02:03,999
Isn't this a gecko?

11
00:02:04,416 --> 00:02:07,419
How else can I get a 15 ton T-Rex in here?

12
00:02:07,503 --> 00:02:11,048
With our advanced technology, I shrank it down.

```

References

:   * Wikipedia: SubRip

[Assistant]
### Brutal

```
# 20240621 Raku programming solution

sub MAIN() {
   my @lines = $*IN.lines;
   for 9, -9 -> $seconds {
      say "Original subtitle adjusted by {$seconds.fmt('%+d')} seconds.";
      for @lines -> $line {
         if $line ~~ /(\d ** 2 ':' \d ** 2 ':' \d ** 2 ',' \d ** 3) ' --> ' (\d ** 2 ':' \d ** 2 ':' \d ** 2 ',' \d ** 3)/ {
            my $start = adjust-time($0.Str, $seconds);
            my $end   = adjust-time($1.Str, $seconds);
            my $adjusted = $line;
            $adjusted ~~ s/\d ** 2 ':' \d ** 2 ':' \d ** 2 ',' \d ** 3 ' --> ' \d ** 2 ':' \d ** 2 ':' \d ** 2 ',' \d ** 3/$start ~ ' --> ' ~ $end/.Str;
            say $adjusted
         } else {
            say $line;
         }
      }
      say()
   }
}

sub adjust-time($time, $seconds) {
   my ($time_str, $milliseconds_str) = $time.split(',');
   my (\hh, \mm, \ss) = $time_str.split(':')>>.Int;
   my $milliseconds = $milliseconds_str.Int;
   my $datetime = DateTime.new(:year,     :month,      :day,
                               :hour(hh), :minute(mm), :second(ss));
   given $datetime .= later(:seconds($seconds)) {
      return sprintf('%02d:%02d:%02d,%03d',.hour,.minute,.second,$milliseconds)
   }
}

```

You may Attempt This Online!

### Less brutal

```
# 20240622 Raku programming solution

grammar SRT { # loc.gov/preservation/digital/formats/fdd/fdd000569.shtml
   token TOP { ^ <subtitle>+ % \n $ }
   token subtitle { <index> \n <timecode> \n <text> \n? }
   token index { \d+ }
   token timecode { <timestamp> ' --> ' <timestamp> }
   token timestamp { \d ** 2 ':' \d ** 2 ':' \d ** 2 ',' \d ** 3 }
   token text { <line>+ % \n }
   token line { <-[\n]>+ }
}

class SRT::Actions { has @.subtitles;

   method TOP($/) {
      @.subtitles = $<subtitle>».made;
      make @.subtitles
   }

   method subtitle($/) {
      make {
         index => $<index>.Str,
         start => $<timecode><timestamp>[0].made,
         end   => $<timecode><timestamp>[1].made,
         text  => $<text>.made,
      }
   }

   method timestamp($/) { make $/.Str }

   method text($/) { make $<line>.join("\n") }
}

class SubtitleAdjuster {

    method adjust-time($time, $seconds) {
       my ($time-str, $milliseconds-str) = $time.split(',');
       my (\hh, \mm, \ss) = $time-str.split(':')>>.Int;
       my \mls            = $milliseconds-str.Int;
       my $datetime = DateTime.new( :year, :month, :day,
                                    :hour(hh), :minute(mm), :second(ss));
       given $datetime .= later(:seconds($seconds)) {
          return sprintf('%02d:%02d:%02d,%03d', .hour, .minute, .second, mls)
       }
   }

   method adjust-subtitles(@subtitles, Int $seconds) {
      @subtitles.map({
         $_<start> = self.adjust-time($_<start>, $seconds);
         $_<end>   = self.adjust-time($_<end>, $seconds);
         $_;
      });
   }

   method format-srt(@subtitles) {
      @subtitles.map({
         $_<index> ~ "\n"
         ~ $_<start> ~ " --> " ~ $_<end> ~ "\n"
         ~ $_<text> ~ "\n"
      }).join("\n");
   }
}

my $srt-content = $*IN.slurp;
my $parsed = SRT.parse($srt-content, :actions(SRT::Actions.new));
my @subtitles = $parsed.made;

my $adjuster = SubtitleAdjuster.new;

for 9, -9 -> \N {
   my @adjusted-subtitles = $adjuster.adjust-subtitles(@subtitles.deepmap(*.clone), N);
   say "Original subtitle adjusted by {N.fmt('%+d')} seconds.";
   say $adjuster.format-srt(@adjusted-subtitles);
}

```

You may Attempt This Online!


[User]
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.

One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.

This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2013-02-27

```
sub MAIN ($infile) {
    $infile.IO.lines ==> printer() ==> my $count;
    say "printed $count lines";
}

sub printer(*@lines) {
    my $lines;
    for @lines {
	.say;
	++$lines;
    }
    $lines;
}

```

Concurrent units are established by use of the feed operator, which works much like an in-process object pipe. Since the final feed goes to a variable declaration that belongs to the outer thread, it serves as a backchannel from the printer thread. In this case the outer thread signals the desire for a line count by terminating the pipe to the printing thread.
(Note: soon these will be implemented with real threads in Raku, but this is currently emulated with coroutine semantics, aka lazy lists.)


[User]
Task

Output the system **time**   (any units will do as long as they are noted) either by a system command or one built into the language.

The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.

Related task

* Date format

See also

* Retrieving system time (wiki)

[Assistant]
(formerly Perl 6)

```
say DateTime.now;
dd DateTime.now.Instant;
```

Output:

```
 2015-11-02T13:34:09+01:00
 Instant $var = Instant.new(<2159577143734/1493>)

```


[User]
*Szymański's algorithm* is a mutual exclusion algorithm devised by computer scientist Bolesław Szymański.

The algorithm allows mutiple processes or tasks to access a serial resource without conflict, using only linear waiting times.
It has application in multitasking and communications, especially if there is a need for massive parallelism with limited
waiting times for access to resources by the parallel program's components.

Task

* Implement Szymanski's algorithm utilizing parallel processes, threads, or similar coroutines.
* Your example should implement the steps shown in the Wikipedia's pseudocode at the Wikipedia reference below.

See also

* [Wikipedia entry for Szymański's algorithm] * [ACM digital entry for Szymański's paper]

"""
Szymański's algorithm reference:
Boleslaw K. Szymanski. A simple solution to Lamport's concurrent programming problem with linear wait.
Proceedings of the 2nd International Conference on Supercomputing, 1988, Figure 2, Page 624.
https://dl.acm.org/doi/pdf/10.1145/55364.55425
https://en.wikipedia.org/wiki/Szyma%C5%84ski%27s\_algorithm
"""

[Assistant]
```
# 20230822 Raku programming solution

use OO::Monitors;

my \N = 10;

monitor Szymański {

   has @.tasks;
   my $critical = 0;

   method runSzymański($id) {
      @.tasks[$id] = 1;
      ( my @others = @.tasks ).splice: $id,1;
      until @others.all ~~ 0|1|2 { $*THREAD.yield }
      @.tasks[$id] = 3;
      if @others.any ~~ 1 {
         @.tasks[$id] = 2;
         until @others.any ~~ 4 { $*THREAD.yield }
      }
      @.tasks[$id] = 4;
      until @.tasks[^$id].all ~~ 0|1 { $*THREAD.yield }
      $critical = ((my $previous = $critical) + $id * 3) div 2;
      say "Thread $id changed the critical value from $previous to $critical";
      until @.tasks[$id^..*-1].all ~~ 0|1|4 { $*THREAD.yield }
      @.tasks[$id] = 0
   }
}

my $flag = Szymański.new: tasks => 0 xx N;
await Promise.allof( ^N .pick(*).map: { start { $flag.runSzymański: $_ } } );

```

Output:

```
Thread 6 changed the critical value from 0 to 9
Thread 1 changed the critical value from 9 to 6
Thread 5 changed the critical value from 6 to 10
Thread 4 changed the critical value from 10 to 11
Thread 7 changed the critical value from 11 to 16
Thread 9 changed the critical value from 16 to 21
Thread 8 changed the critical value from 21 to 22
Thread 3 changed the critical value from 22 to 15
Thread 2 changed the critical value from 15 to 10
Thread 0 changed the critical value from 10 to 5
```


[User]
Task

Create a database table to exemplify most commonly used data types and options.

Related task

* Table Creation - Address

[Assistant]
(formerly Perl 6)
In Raku, there is no 'database' type built in, so it is somewhat ambiguous when specifying 'create a database table'. Raku offers bindings to most common databases through its DBIish module but mostly abstracts away the differences between the underlying databases, which hides many of the finer distinctions of what may be stored where. The actual data types and options available are properties of the database used.

If on the other hand, we are meant to show built in collective types that may be used to hold tabular data, this may be of some use.

In general, a container type can hold objects of any data type, even instances of their own type; allowing 'multi-dimensional' (tabular) containers.

Raku offers two broad categories of collective container types; those that do the Positional role and those that do Associative. Positional objects are collective objects that access the individual storage slots using an integer index. Associative objects use some sort of other pointer (typically string) to access their storage slots.

The various Associative types mostly differ in their value handling. Hash, Map and QuantHash may have any type of object as their value. All the others have some specific, usually numeric, type as their value.

```
Positional - Object that supports looking up values by integer index
    Array     Sequence of itemized objects
    List      Immutable sequence of objects

Associative - Object that supports looking up values by key (typically string)
    Bag        Immutable collection of distinct objects with integer weights
    BagHash    Mutable collection of distinct objects with integer weights
    Hash       Mapping from strings to itemized values
    Map        Immutable mapping from strings to values
    Mix        Immutable collection of distinct objects with Real weights
    MixHash    Mutable collection of distinct objects with Real weights
    QuantHash  Collection of objects represented as hash keys
    Set        Immutable collection of distinct objects, no value except 'present'
    SetHash    Mutable collection of distinct objects, no value except 'present'

```

If you want a persistent instance of any of these types, you need to declare the name with some scope constraint, but there are no prerequisites to creating instances. Simply assigning values to them will call them into existence.


[User]
Task

Create a table to store addresses.

You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode.   Choose appropriate types for each field.

For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.09

Like Perl DBI, Raku DBIish supports many different databases. An example using SQLite is shown here.

```
use DBIish;

my $dbh = DBIish.connect('SQLite', :database<addresses.sqlite3>);

my $sth = $dbh.do(q:to/STATEMENT/);
    DROP TABLE IF EXISTS Address;
    CREATE TABLE Address (
        addrID      INTEGER PRIMARY KEY AUTOINCREMENT,
        addrStreet  TEXT NOT NULL,
        addrCity    TEXT NOT NULL,
        addrState   TEXT NOT NULL,
        addrZIP     TEXT NOT NULL
    )
    STATEMENT

```


[User]
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.

[Assistant]
(formerly Perl 6)

```
my $file = 'notes.txt';

multi MAIN() {
    print slurp($file);
}

multi MAIN(*@note) {
    my $fh = open($file, :a);
    $fh.say: DateTime.now, "\n\t", @note;
    $fh.close;
}

```


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

Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.

It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.

Tarjan's Algorithm is named for its discoverer, Robert Tarjan.

References

* The article on Wikipedia.

See also: Kosaraju

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.09

```
sub tarjan (%k) {
    my %onstack;
    my %index;
    my %lowlink;
    my @stack;
    my @connected;

    sub strong-connect ($vertex) {
         state $index      = 0;
         %index{$vertex}   = $index;
         %lowlink{$vertex} = $index++;
         %onstack{$vertex} = True;
         @stack.push: $vertex;
         for |%k{$vertex} -> $connection {
             if not %index{$connection}.defined {
                 strong-connect($connection);
                 %lowlink{$vertex} min= %lowlink{$connection};
             }
             elsif %onstack{$connection} {
                 %lowlink{$vertex} min= %index{$connection};
             }
        }
        if %lowlink{$vertex} eq %index{$vertex} {
            my @node;
            repeat {
                @node.push: @stack.pop;
                %onstack{@node.tail} = False;
            } while @node.tail ne $vertex;
            @connected.push: @node;
        }
    }

    .&strong-connect unless %index{$_} for %k.keys;

    @connected
}

# TESTING

-> $test { say "\nStrongly connected components: ", |tarjan($test).sort».sort } for

# hash of vertex, edge list pairs
(((1),(2),(0),(1,2,4),(3,5),(2,6),(5),(4,6,7)).pairs.hash),

# Same layout test data with named vertices instead of numbered.
%(:Andy<Bart>,
  :Bart<Carl>,
  :Carl<Andy>,
  :Dave<Bart Carl Earl>,
  :Earl<Dave Fred>,
  :Fred<Carl Gary>,
  :Gary<Fred>,
  :Hank<Earl Gary Hank>
)

```

Output:

```
Strongly connected components: (0 1 2)(3 4)(5 6)(7)

Strongly connected components: (Andy Bart Carl)(Dave Earl)(Fred Gary)(Hank)
```


[User]
Given a positive integer, count the number of its positive divisors.

Task

Show the result for the first   **100**   positive integers.

Related task

* Tau number

[Assistant]
Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.

```
use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;

say "\nTau function - first 100:\n",        # ID
(1..*).map({ +.&divisors })[^100]\          # the task
.batch(20)».fmt("%3d").join("\n");          # display formatting

say "\nTau numbers - first 100:\n",         # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\   # the task
.batch(10)».&comma».fmt("%5s").join("\n");  # display formatting

say "\nDivisor sums - first 100:\n",        # ID
(1..*).map({ [+] .&divisors })[^100]\       # the task
.batch(20)».fmt("%4d").join("\n");          # display formatting

say "\nDivisor products - first 100:\n",    # ID
(1..*).map({ [×] .&divisors })[^100]\       # the task
.batch(5)».&comma».fmt("%16s").join("\n");  # display formatting

```

Output:

```
Tau function - first 100:
  1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6
  4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8
  2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12
  2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10
  5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9

Tau numbers - first 100:
    1     2     8     9    12    18    24    36    40    56
   60    72    80    84    88    96   104   108   128   132
  136   152   156   180   184   204   225   228   232   240
  248   252   276   288   296   328   344   348   360   372
  376   384   396   424   441   444   448   450   468   472
  480   488   492   504   516   536   560   564   568   584
  600   612   625   632   636   640   664   672   684   708
  712   720   732   776   792   804   808   824   828   852
  856   864   872   876   880   882   896   904   936   948
  972   996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096

Divisor sums - first 100:
   1    3    4    7    6   12    8   15   13   18   12   28   14   24   24   31   18   39   20   42
  32   36   24   60   31   42   40   56   30   72   32   63   48   54   48   91   38   60   56   90
  42   96   44   84   78   72   48  124   57   93   72   98   54  120   72  120   80   90   60  168
  62   96  104  127   84  144   68  126   96  144   72  195   74  114  124  140   96  168   80  186
 121  126   84  224  108  132  120  180   90  234  112  168  128  144  120  252   98  171  156  217

Divisor products - first 100:
               1                2                3                8                5
              36                7               64               27              100
              11            1,728               13              196              225
           1,024               17            5,832               19            8,000
             441              484               23          331,776              125
             676              729           21,952               29          810,000
              31           32,768            1,089            1,156            1,225
      10,077,696               37            1,444            1,521        2,560,000
              41        3,111,696               43           85,184           91,125
           2,116               47      254,803,968              343          125,000
           2,601          140,608               53        8,503,056            3,025
       9,834,496            3,249            3,364               59   46,656,000,000
              61            3,844          250,047        2,097,152            4,225
      18,974,736               67          314,432            4,761       24,010,000
              71  139,314,069,504               73            5,476          421,875
         438,976            5,929       37,015,056               79    3,276,800,000
          59,049            6,724               83  351,298,031,616            7,225
           7,396            7,569       59,969,536               89  531,441,000,000
           8,281          778,688            8,649            8,836            9,025
 782,757,789,696               97          941,192          970,299    1,000,000,000
```


[User]
A Tau number is a positive integer divisible by the count of its positive divisors.

Task

Show the first   **100**   Tau numbers.
The numbers shall be *generated* during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).

Related task

* Tau function

[Assistant]
Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.

```
use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;

say "\nTau function - first 100:\n",        # ID
(1..*).map({ +.&divisors })[^100]\          # the task
.batch(20)».fmt("%3d").join("\n");          # display formatting

say "\nTau numbers - first 100:\n",         # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\   # the task
.batch(10)».&comma».fmt("%5s").join("\n");  # display formatting

say "\nDivisor sums - first 100:\n",        # ID
(1..*).map({ [+] .&divisors })[^100]\       # the task
.batch(20)».fmt("%4d").join("\n");          # display formatting

say "\nDivisor products - first 100:\n",    # ID
(1..*).map({ [×] .&divisors })[^100]\       # the task
.batch(5)».&comma».fmt("%16s").join("\n");  # display formatting

```

Output:

```
Tau function - first 100:
  1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6
  4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8
  2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12
  2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10
  5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9

Tau numbers - first 100:
    1     2     8     9    12    18    24    36    40    56
   60    72    80    84    88    96   104   108   128   132
  136   152   156   180   184   204   225   228   232   240
  248   252   276   288   296   328   344   348   360   372
  376   384   396   424   441   444   448   450   468   472
  480   488   492   504   516   536   560   564   568   584
  600   612   625   632   636   640   664   672   684   708
  712   720   732   776   792   804   808   824   828   852
  856   864   872   876   880   882   896   904   936   948
  972   996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096

Divisor sums - first 100:
   1    3    4    7    6   12    8   15   13   18   12   28   14   24   24   31   18   39   20   42
  32   36   24   60   31   42   40   56   30   72   32   63   48   54   48   91   38   60   56   90
  42   96   44   84   78   72   48  124   57   93   72   98   54  120   72  120   80   90   60  168
  62   96  104  127   84  144   68  126   96  144   72  195   74  114  124  140   96  168   80  186
 121  126   84  224  108  132  120  180   90  234  112  168  128  144  120  252   98  171  156  217

Divisor products - first 100:
               1                2                3                8                5
              36                7               64               27              100
              11            1,728               13              196              225
           1,024               17            5,832               19            8,000
             441              484               23          331,776              125
             676              729           21,952               29          810,000
              31           32,768            1,089            1,156            1,225
      10,077,696               37            1,444            1,521        2,560,000
              41        3,111,696               43           85,184           91,125
           2,116               47      254,803,968              343          125,000
           2,601          140,608               53        8,503,056            3,025
       9,834,496            3,249            3,364               59   46,656,000,000
              61            3,844          250,047        2,097,152            4,225
      18,974,736               67          314,432            4,761       24,010,000
              71  139,314,069,504               73            5,476          421,875
         438,976            5,929       37,015,056               79    3,276,800,000
          59,049            6,724               83  351,298,031,616            7,225
           7,396            7,569       59,969,536               89  531,441,000,000
           8,281          778,688            8,649            8,836            9,025
 782,757,789,696               97          941,192          970,299    1,000,000,000
```


[User]
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way.

The first taxicab number is   **1729**,   which is:

:   :   :   13   +   123       and also
        :   93   +   103.

Taxicab numbers are also known as:

:   :   * taxi numbers
        * taxi-cab numbers
        * taxi cab numbers
        * Hardy-Ramanujan numbers

Task

* Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
* For each of the taxicab numbers, show the number as well as it's constituent cubes.

Extra credit

* Show the 2,000th taxicab number, and a half dozen more

See also

* A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
* Hardy-Ramanujan Number on MathWorld.
* taxicab number on MathWorld.
* taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).

[Assistant]
(formerly Perl 6)

This uses a pretty simple search algorithm that doesn't necessarily return the Taxicab numbers in order. Assuming we want all the Taxicab numbers within some range S to N, we'll search until we find N values. When we find the Nth value, we continue to search up to the cube root of the largest Taxicab number found up to that point. That ensures we will find all of them inside the desired range without needing to search arbitrarily or use magic numbers. Defaults to returning the Taxicab numbers from 1 to 25. Pass in a different start and end value if you want some other range.

```
constant @cu = (^Inf).map: { .³ }

sub MAIN ($start = 1, $end = 25) {
    my %taxi;
    my int $taxis = 0;
    my $terminate = 0;
    my int $max = 0;

    for 1 .. * -> $c1 {
        last if ?$terminate && ($terminate < $c1);
        for 1 .. $c1 -> $c2 {
            my $this = @cu[$c1] + @cu[$c2];
            %taxi{$this}.push: [$c2, $c1];
            if %taxi{$this}.elems == 2 {
                ++$taxis;
                $max max= $this;
            }
    	    $terminate = ceiling $max ** (1/3) if $taxis == $end and !$terminate;
        }
    }

    display( %taxi, $start, $end );

}

sub display (%this_stuff, $start, $end) {
    my $i = $start;
    printf "%4d %10d  =>\t%s\n", $i++, $_.key,
        (.value.map({ sprintf "%4d³ + %-s\³", |$_ })).join: ",\t"
        for %this_stuff.grep( { $_.value.elems > 1 } ).sort( +*.key )[$start-1..$end-1];
}

```

Output:

With no passed parameters (default)

```
   1       1729  =>	   9³ + 10³,	   1³ + 12³
   2       4104  =>	   9³ + 15³,	   2³ + 16³
   3      13832  =>	  18³ + 20³,	   2³ + 24³
   4      20683  =>	  19³ + 24³,	  10³ + 27³
   5      32832  =>	  18³ + 30³,	   4³ + 32³
   6      39312  =>	  15³ + 33³,	   2³ + 34³
   7      40033  =>	  16³ + 33³,	   9³ + 34³
   8      46683  =>	  27³ + 30³,	   3³ + 36³
   9      64232  =>	  26³ + 36³,	  17³ + 39³
  10      65728  =>	  31³ + 33³,	  12³ + 40³
  11     110656  =>	  36³ + 40³,	   4³ + 48³
  12     110808  =>	  27³ + 45³,	   6³ + 48³
  13     134379  =>	  38³ + 43³,	  12³ + 51³
  14     149389  =>	  29³ + 50³,	   8³ + 53³
  15     165464  =>	  38³ + 48³,	  20³ + 54³
  16     171288  =>	  24³ + 54³,	  17³ + 55³
  17     195841  =>	  22³ + 57³,	   9³ + 58³
  18     216027  =>	  22³ + 59³,	   3³ + 60³
  19     216125  =>	  45³ + 50³,	   5³ + 60³
  20     262656  =>	  36³ + 60³,	   8³ + 64³
  21     314496  =>	  30³ + 66³,	   4³ + 68³
  22     320264  =>	  32³ + 66³,	  18³ + 68³
  23     327763  =>	  51³ + 58³,	  30³ + 67³
  24     373464  =>	  54³ + 60³,	   6³ + 72³
  25     402597  =>	  56³ + 61³,	  42³ + 69³
```

With passed parameters 2000 2006:

```
2000 1671816384  =>	 940³ + 944³,	 428³ + 1168³
2001 1672470592  =>	 632³ + 1124³,	  29³ + 1187³
2002 1673170856  =>	 828³ + 1034³,	 458³ + 1164³
2003 1675045225  =>	 744³ + 1081³,	 522³ + 1153³
2004 1675958167  =>	 711³ + 1096³,	 492³ + 1159³
2005 1676926719  =>	 714³ + 1095³,	  63³ + 1188³
2006 1677646971  =>	 891³ + 990³,	  99³ + 1188³
```