[User]
The linear congruential generator is a very simple example of a random number generator.

All linear congruential generators use this formula:

* r

  n
  +
  1
  =
  a
  ×

  r

  n
  +
  c

  (
  mod

  m
  )
  {\displaystyle {\displaystyle r\_{n+1}=a\times r\_{n}+c{\pmod {m}}}}

Where:

* r

  0
  {\displaystyle {\displaystyle r\_{0}}}
   is a seed.
* r

  1
  {\displaystyle {\displaystyle r\_{1}}}
  ,

  r

  2
  {\displaystyle {\displaystyle r\_{2}}}
  ,

  r

  3
  {\displaystyle {\displaystyle r\_{3}}}
  , ..., are the random numbers.
* a
  {\displaystyle {\displaystyle a}}
  ,

  c
  {\displaystyle {\displaystyle c}}
  ,

  m
  {\displaystyle {\displaystyle m}}
   are constants.

If one chooses the values of

a
{\displaystyle {\displaystyle a}}
,

c
{\displaystyle {\displaystyle c}}
 and

m
{\displaystyle {\displaystyle m}}
 with care, then the generator produces a uniform distribution of integers from

0
{\displaystyle {\displaystyle 0}}
 to

m
−
1
{\displaystyle {\displaystyle m-1}}
.

LCG numbers have poor quality.

r

n
{\displaystyle {\displaystyle r\_{n}}}
 and

r

n
+
1
{\displaystyle {\displaystyle r\_{n+1}}}
 are not independent, as true random numbers would be. Anyone who knows

r

n
{\displaystyle {\displaystyle r\_{n}}}
 can predict

r

n
+
1
{\displaystyle {\displaystyle r\_{n+1}}}
, therefore LCG is not cryptographically secure. The LCG is still good enough for simple tasks like Miller-Rabin primality test, or FreeCell deals. Among the benefits of the LCG, one can easily reproduce a sequence of numbers, from the same

r

0
{\displaystyle {\displaystyle r\_{0}}}
. One can also reproduce such sequence with a different programming language, because the formula is so simple.

The task is to replicate two historic random number generators. One is the `rand()` function from BSD libc, and the other is the `rand()` function from the Microsoft C Runtime (MSCVRT.DLL). Each replica must yield the same sequence of integers as the original generator, when starting from the same seed.

In these formulas, the seed becomes

s
t
a
t

e

0
{\displaystyle {\displaystyle state\_{0}}}
. The random sequence is

r
a
n

d

1
{\displaystyle {\displaystyle rand\_{1}}}
,

r
a
n

d

2
{\displaystyle {\displaystyle rand\_{2}}}
 and so on.

BSD formula

* s
  t
  a
  t

  e

  n
  +
  1
  =
  1103515245
  ×
  s
  t
  a
  t

  e

  n
  +
  12345

  (
  mod

  2

  31
  )
  {\displaystyle {\displaystyle state\_{n+1}=1103515245\times state\_{n}+12345{\pmod {2^{31}}}}}
* r
  a
  n

  d

  n
  =
  s
  t
  a
  t

  e

  n
  {\displaystyle {\displaystyle rand\_{n}=state\_{n}}}
* r
  a
  n

  d

  n
  {\displaystyle {\displaystyle rand\_{n}}}
   is in range 0 to 2147483647.

Microsoft formula

* s
  t
  a
  t

  e

  n
  +
  1
  =
  214013
  ×
  s
  t
  a
  t

  e

  n
  +
  2531011

  (
  mod

  2

  31
  )
  {\displaystyle {\displaystyle state\_{n+1}=214013\times state\_{n}+2531011{\pmod {2^{31}}}}}
* r
  a
  n

  d

  n
  =
  s
  t
  a
  t

  e

  n
  ÷

  2

  16
  {\displaystyle {\displaystyle rand\_{n}=state\_{n}\div 2^{16}}}
* r
  a
  n

  d

  n
  {\displaystyle {\displaystyle rand\_{n}}}
   is in range 0 to 32767.

The BSD formula was so awful that FreeBSD switched to a different formula.

More info is at Random number generator (included)#C.

[Assistant]
(formerly Perl 6)

We'll define subroutines implementing the LCG algorithm for each version. We'll make them return a lazy list.

```
constant modulus = 2**31;
sub bsd  {
    $^seed, ( 1103515245 * * + 12345 ) % modulus ... *
}
sub ms   {
    map * +> 16, (
	$^seed, ( 214013 * * + 2531011 ) % modulus ... *
    )
}

say 'BSD LCG first 10 values (first one is the seed):';
.say for bsd(0)[^10];

say "\nMS LCG first 10 values (first one is the seed):";
.say for ms(0)[^10];

```

```
BSD LCG first 10 values (first one is the seed):
0
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793

MS LCG first 10 values (first one is the seed):
0
38
7719
21238
2437
8855
11797
8365
32285
10450
```


[User]
Task

Display the current CPU utilization, as a percentage, calculated from  `/proc/stat`.

Background

Most Linux kernels provide a virtual   `/proc`   filesystem, providing an interface to various internal data structures.

One of these internal structures (`/proc/stat`) includes information on the amount of time (in `USER_HZ`) spent in various states.   From this information, we can, with a little effort, determine the current level of CPU utilization, as a percent of time spent in any states other than *idle*.

To do this:

:   :   :   1. read the first line of   `/proc/stat`
            2. discard the first word of that first line   (it's always `cpu`)
            3. sum all of the times found on that first line to get the total time
            4. divide the fourth column ("idle") by the total time, to get the fraction of time spent being idle
            5. subtract the previous fraction from 1.0 to get the time spent being   *not*   idle
            6. multiple by   **100**   to get a percentage

The times in `/proc/stat` are monotonically increasing, and begin at some point during the kernel's initialization (ie during boot up).   So the steps above will give the total CPU utilization since boot, which may or may not be useful to some.   To get a more real-time utilization, we simply repeat the steps above with some small sleep interval in between, and instead of using the absolute total and idle times, we use use the total time delta and the idle time delta to compute the utilization.

This project is based on   this blog post   by Paul Colby,   and the   Bash   version comes from there.

[Assistant]
(formerly Perl 6)

```
my $last-total = 0;
my $last-idle  = 0;

loop {
    my $Δ-total = (my $this-total = [+] my @cpu = "/proc/stat".IO.lines[0].words[1..*]) - $last-total;
    my $Δ-idle  = (my $this-idle  = @cpu[3]) - $last-idle;
    $last-total = $this-total;
    $last-idle  = $this-idle;
    print "\b" x 40, (100 * (1 - $Δ-idle / $Δ-total)).fmt("Utilization: %0.1f%% ");
    sleep(1);
}

```


[User]
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a *set comprehension*, hence the name.

Some attributes of a list comprehension are:

1. They should be distinct from (nested) for loops and the use of map and filter functions within the syntax of the language.
2. They should return either a list or an iterator (something that returns successive members of a collection, in order).
3. The syntax has parts corresponding to that of set-builder notation.

Task

Write a list comprehension that builds the list of all Pythagorean triples with elements between   **1**   and   **n**.

If the language has multiple ways for expressing such a construct (for example, direct list comprehensions and generators), write one example for each.

[Assistant]
(formerly Perl 6)
Raku has single-dimensional list comprehensions that fall out naturally from nested modifiers; multidimensional comprehensions are also supported via the cross operator; however, Raku does not (yet) support multi-dimensional list comprehensions with dependencies between the lists, so the most straightforward way is currently:

```
my $n = 20;
say gather for 1..$n -> $x {
         for $x..$n -> $y {
           for $y..$n -> $z {
             take $x,$y,$z if $x*$x + $y*$y == $z*$z;
           }
         }
       }

```

Output:

```
((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))
```

Note that gather/take is the primitive in Raku corresponding to generators or coroutines in other languages. It is not, however, tied to function call syntax in Raku. We can get away with that because lists are lazy, and the demand for more of the list is implicit; it does not need to be driven by function calls.


[User]
You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.

If we use a matching pair of parentheses to represent a bag, the ways are:

For 1 bag, there's one way:

```
 ()	<- a bag

```

for 2 bags, there's one way:

```
 (())	<- one bag in another

```

for 3 bags, there are two:

```
 ((())) <- 3 bags nested Russian doll style
 (()()) <- 2 bags side by side, inside the third

```

for 4 bags, four:

```
 (()()())
 ((())())
 ((()()))
 (((())))

```

Note that because all bags are identical, the two 4-bag strings `((())())` and `(()(()))` represent the same configuration.

It's easy to see that each configuration for *n* bags represents a *n*-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given *n* is given by OEIS A81.

Task

Write a program that, when given *n*, enumerates all ways of nesting *n* bags.   You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.

This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.

As an example output, run 5 bags.   There should be 9 ways.

[Assistant]
(formerly Perl 6)
Bags are represented by Raku type Bag.

```
use v6;

multi expand-tree ( Bag $tree ) {
    bag(bag(bag()) (+) $tree) (+)
    [(+)] (
        $tree.keys ==> map {
            $^a.&expand-tree.map: * (+) ( $tree (-) bag($^a) )
        }
    );
}

multi expand-trees ( Bag $trees ) {
    [(+)] $trees.keys.map:  { $_.&expand-tree } ;
}

my $n = 5;
for ( bag(), bag(bag()), *.&expand-trees ... * )[$n] {
    print ++$,".\t";
    .say
};

```

Output:

```
1.	bag(bag(), bag(bag()(2))) => 2
2.	bag(bag(bag()(3))) => 1
3.	bag(bag(bag(bag()), bag())) => 2
4.	bag(bag(bag(bag(bag())))) => 1
5.	bag(bag(bag())(2)) => 1
6.	bag(bag(bag(bag()(2)))) => 1
7.	bag(bag(), bag(bag(bag()))) => 2
8.	bag(bag(bag()), bag()(2)) => 2
9.	bag(bag()(4)) => 1

```

The bag `bag(bag(bag()), bag()(2))` coresponds with `((())()())`. There are two independent ways how we can get it by nesting 4 bags.


[User]
Programming languages have different ways of expressing floating-point literals.

Task

Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features.

You may want to include a regular expression or BNF/ABNF/EBNF defining allowable formats for your language.

Related tasks

* Literals/Integer
* Extreme floating point values

[Assistant]
(formerly Perl 6)
Floating point numbers (the Num type) are written in the standard 'e' scientific notation:

```
2e2      # same as 200e0, 2e2, 200.0e0  and 2.0e2
6.02e23
-2e48
1e-9
1e0

```

A number like 3.1416 is specifically not floating point, but rational (the Rat type), equivalent to 3927/1250. On the other hand, Num(3.1416) would be considered a floating literal though by virtue of mandatory constant folding.


[User]
Some programming languages have ways of expressing integer literals in bases other than the normal base ten.

Task

Show how integer literals can be expressed in as many bases as your language allows.

Note:   this should **not** involve the calling of any functions/methods, but should be interpreted by the compiler or interpreter as an integer written to a given base.

Also show any other ways of expressing literals, e.g. for different types of integers.

Related task

* Literals/Floating point

[Assistant]
(formerly Perl 6)
These all print 255.

```
say 255;
say 0d255;
say 0xff;
say 0o377;
say 0b1111_1111;

say :10<255>;
say :16<ff>;
say :8<377>;
say :2<1111_1111>;
say :3<100110>;
say :4<3333>;
say :12<193>;
say :36<73>;
```

There is a specced form for bases above 36, but rakudo does not yet implement it.


[User]
Task

Show literal specification of characters and strings.

If supported, show how the following work:

:   * *verbatim strings*   (quotes where escape sequences are quoted literally)
    * *here-strings*

Also, discuss which quotes expand variables.

Related tasks

* Special characters
* Here document

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)
Unlike most languages that hardwire their quoting mechanisms, the quote mechanism in Raku is extensible, and all normal-looking quotes actually derive from a parent quoting language called Q via grammatical mixins, applied via standard Raku adverbial syntax.
The available quote mixins, straight from current spec S02, are:

```
Short       Long            Meaning
=====       ====            =======
:x          :exec           Execute as command and return results
:w          :words          Split result on words (no quote protection)
:ww         :quotewords     Split result on words (with quote protection)
:v          :val            Evaluate word or words for value literals
:q          :single         Interpolate \\, \q and \' (or whatever)
:qq         :double         Interpolate with :s, :a, :h, :f, :c, :b
:s          :scalar         Interpolate $ vars
:a          :array          Interpolate @ vars
:h          :hash           Interpolate % vars
:f          :function       Interpolate & calls
:c          :closure        Interpolate {...} expressions
:b          :backslash      Interpolate \n, \t, etc. (implies :q at least)
:to         :heredoc        Parse result as heredoc terminator
            :regex          Parse as regex
            :subst          Parse as substitution
            :trans          Parse as transliteration
            :code           Quasiquoting
:p          :path           Return a Path object (see S16 for more options
```

In any case, an initial Q, q, or qq may omit the initial colon to form traditional Perl quotes such as qw//.
And Q can be used by itself to introduce a quote that has no escapes at all except for the closing delimiter:

```
my $raw = Q'$@\@#)&!#';
```

Note that the single quotes there imply no single quoting semantics as they would in Perl 5. They're just the quotes the programmer happened to choose, since they were most like the raw quoting. Single quotes imply :q only when used as normal single quotes are, as discussed below.
As in Perl 5, you can use any non-alphanumeric, non-whitespace characters for delimiters with the general forms of quoting, including matching bracket characters, including any Unicode brackets.

Using the definitions above, we can derive the various standard "sugar" quotes from Q, including:

```
Normal  Means
======  =====
q/.../  Q :q /.../
qq/.../ Q :qq /.../
'...'   Q :q /.../
"..."   Q :qq /.../
<...>   Q :q :w :v /.../
«...»   Q :qq :ww :v /.../
/.../   Q :regex /.../
quasi {...} Q :code {...}
```

The :qq-derived languages all give normal Perlish interpolation, but individual interpolations may be chosen or suppressed with extra adverbs.

Unlike in Perl 5, we don't use backticks as shorthand for what is now expressed as qqx// in Raku.
(Backticks are now reserved for user-defined syntax.)
Heredocs now have no special << syntax,
but fall out of the :to adverb:

```
say qq:to/END/;
    Your ad here.
    END
```

Indentation equivalent to the ending tag is automatically removed.

Backslash sequences recognized by :b (and hence :qq) include:

```
"\a"        # BELL
"\b"        # BACKSPACE
"\t"        # TAB
"\n"        # LINE FEED
"\f"        # FORM FEED
"\r"        # CARRIAGE RETURN
"\e"        # ESCAPE
"\x263a"    # ☺
"\o40"      # SPACE
"\0"        # NULL

"\cC"       # CTRL-C
"\c8"       # BACKSPACE
"\c[13,10]" # CRLF
"\c[LATIN CAPITAL LETTER A, COMBINING RING ABOVE]"
```

Leading 0 specifically does not mean octal in Perl 6;
you must use \o instead.


[User]
Task

Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments.

If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.

If the language supports additional logical operations on booleans such as XOR, list them as well.

[Assistant]
(formerly Perl 6)

Raku has an abundance of logical operators for various purposes.

```
sub logic($a,$b) {
    say "$a && $b is ", $a && $b;     # short-circuiting
    say "$a || $b is ", $a || $b;     # short-circuiting
    say "$a ^^ $b is ", $a ^^ $b;
    say "!$a is ",     !$a;

    say "$a ?& $b is ", $a ?& $b;     # non-short-circuiting
    say "$a ?| $b is ", $a ?| $b;     # non-short-circuiting
    say "$a ?^ $b is ", $a ?^ $b;     # non-short-circuiting

    say "$a +& $b is ", $a +& $b;     # numeric bitwise
    say "$a +| $b is ", $a +| $b;     # numeric bitwise
    say "$a +^ $b is ", $a +^ $b;     # numeric bitwise

    say "$a ~& $b is ", $a ~& $b;     # buffer bitwise
    say "$a ~| $b is ", $a ~| $b;     # buffer bitwise
    say "$a ~^ $b is ", $a ~| $b;     # buffer bitwise

    say "$a & $b is ", $a & $b;       # junctional/autothreading
    say "$a | $b is ", $a | $b;       # junctional/autothreading
    say "$a ^ $b is ", $a ^ $b;       # junctional/autothreading

    say "$a and $b is ", ($a and $b); # loose short-circuiting
    say "$a or $b is ",  ($a or $b);  # loose short-circuiting
    say "$a xor $b is ", ($a xor $b);
    say "not $a is ",    (not $a);
}

logic(3,10);

```

Output:

```
3 && 10 is 10
3 || 10 is 3
3 ^^ 10 is Nil
!3 is False
3 ?& 10 is True
3 ?| 10 is True
3 ?^ 10 is False
3 +& 10 is 2
3 +| 10 is 11
3 +^ 10 is 9
3 ~& 10 is 1
3 ~| 10 is 30
3 ~^ 10 is 30
3 & 10 is all(3, 10)
3 | 10 is any(3, 10)
3 ^ 10 is one(3, 10)
3 and 10 is 10
3 or 10 is 3
3 xor 10 is Nil
not 3 is False
```


[User]
The least-squares method (see references below) in statistics is used to fit data
to the best of a family of similar curves by finding the parameters for a curve
which minimizes the total of the distances from each data point to the curve.

Often, the curve used is a straight line, in which case the method is also called
linear regression. If a curve which uses logarithmic growth is fit, the method can be
called logistic regression.

A commonly used family of functions used in statistical studies of populations,
including the growth of epidemics, are curves akin to the logistic curve:

```
        ƒ(x) = L / (1 + e-k(x-x0))

```

Though predictions based on fitting to such curves may error, especially if used to
extrapolate from incomplete data, curves similar to the logistic curve have had
good fits in population studies, including modeling the growth of past epidemics.

Given the following daily world totals since  December 31, 2019  for persons who have become infected with the novel coronavirus Covid-19:

```
Daily totals:
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,
4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,
31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,
69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,
80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,
95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,
133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,
271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652

```

Use the following variant of the logistic curve as a formula:

```
        ƒ(t) = n0 e(r t) / ((1 + n0 (e(r t) - 1) / K)

```

Where:

:   :   * **r**    is the rate of growth of the infection in the population.
        * **K**    is the world population, about 7.8 billion.
        * **n0**    is 27, the number of cases found in China at the start of the pandemic.

The    **R0**    of an infection (different from   **r**   above) is a measure of how many
new individuals will become infected for every individual currently infected.
It is an important measure of how quickly an infectious disease may spread.

**R0**   is related to the logistic curve's   **r**   parameter by the formula:

```
        r ≈ ln(R0) / G

```

where    **G**    the generation time, is roughly the sum of the incubation time, perhaps 5 days, and
the mean contagion period, perhaps 7 days, so, for covid-19, roughly we have:

```
        R0 ≈ e12r

```

Task

* Demonstrate code that finds a least-squares fits of the curve to the data.
* Show the calculated    **r**    for the logistic curve.
* Show the final    **R0**    parameter you calculate from the logistic curve    **r**    value parameter.

See also
:   * [Basic reproduction number] * [Logistic functions] * [Least squares] * [World covid-19 case tallies] * [Calculating r and R0]

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

**Translation of**: Perl

Original task numbers of cases per day as of April 05 plus updated, as of today, May 11 numbers.

```
my $K  = 7_800_000_000; #  population
my $n0 = 27;            #  cases @ day 0

my @Apr05 = <
         27      27      27      44      44      59      59      59      59      59
         59      59      59      60      60      61      61      66      83     219
        239     392     534     631     897    1350    2023    2820    4587    6067
       7823    9826   11946   14554   17372   20615   24522   28273   31491   34933
      37552   40540   43105   45177   60328   64543   67103   69265   71332   73327
      75191   75723   76719   77804   78812   79339   80132   80995   82101   83365
      85203   87024   89068   90664   93077   95316   98172  102133  105824  109695
     114232  118610  125497  133852  143227  151367  167418  180096  194836  213150
     242364  271106  305117  338133  377918  416845  468049  527767  591704  656866
     715353  777796  851308  928436 1000249 1082054 1174652
>;

my @May11 = <
         27      27      27      44      44      59      59      59      59      59
         59      59      59      60      60      61      61      66      83     219
        239     392     534     631     897    1350    2023    2820    4587    6067
       7823    9826   11946   14554   17372   20615   24522   28273   31491   34933
      37552   40540   43105   45177   60328   64543   67103   69265   71332   73327
      75191   75723   76719   77804   78812   79339   80132   80995   82101   83365
      85203   87026   89068   90865   93077   95316   98172  102133  105824  109695
     114235  118613  125497  133853  143259  154774  167418  180094  194843  213149
     242374  271116  305235  338235  377968  416881  468092  527839  591796  656834
     715377  777187  851587  928491 1006063 1087822 1174306 1245601 1316988 1391881
    1476792 1563819 1653160 1734868 1807256 1873639 1953786 2033745 2117297 2199460
    2278484 2350993 2427353 2513399 2579823 2657910 2731217 2832750 2915977 2981542
    3054404 3131487 3216467 3308341 3389459 3468047 3545486 3624789 3714816 3809262
    3899379 3986931 4063525
>;

sub logistic-func ($rate, @y) {
    my $sq = 0;
    for ^@y -> $time {
        my $ert = exp($rate * $time);
        my $δt = ($n0 * $ert) / (1 + $n0 * ($ert-1) / $K) - @y[$time];
        $sq += $δt²;
    }
    $sq
}

sub solve (&f, $guess, \ε, @y) {
    my $fₙ-minus;
    my $fₙ-plus;
    my $rate   = $guess;
    my $fₙ     = f $rate, @y;
    my $Δ      = $rate;
    my $factor = 2;
    while $Δ > ε {
        ($fₙ-minus = f $rate - $Δ, @y) < $fₙ ??
        do {
            $fₙ    = $fₙ-minus;
            $rate -= $Δ;
            $Δ    *= $factor;
        } !!
        ($fₙ-plus = f $rate + $Δ, @y) < $fₙ ??
        do {
            $fₙ    = $fₙ-plus;
            $rate += $Δ;
            $Δ    *= $factor;
        } !!
        $Δ /= $factor
    }
    $rate
}

for @Apr05, 'Dec 31 - Apr 5',
    @May11, 'Dec 31 - May 11' -> @y, $period {
    my $rate = solve(&logistic-func, 0.5, 0, @y);
    my $R0   = exp(12 * $rate);
    say "\nFor period: $period";
    say "Instantaneous rate of growth: r = " , $rate.fmt('%08f');
    say "Reproductive rate: R0 = ", $R0.fmt('%08f');
}

```

Output:

```
For period: Dec 31 - Apr 5
Instantaneous rate of growth: r = 0.112302
Reproductive rate: R0 = 3.848279

For period: Dec 31 - May 11
Instantaneous rate of growth: r = 0.093328
Reproductive rate: R0 = 3.064672
```


[User]
This task is about writing a computer program that has long literals   (character
literals that may require specifying the words/tokens on more than one (source)
line,   either with continuations or some other method, such as abutments or
concatenations   (or some other mechanisms).

The literal is to be in the form of a "list",   a literal that contains many
words (tokens) separated by a blank (space),   in this case   (so as to have a
common list),   the (English) names of the chemical elements of the periodic table.

The list is to be in (ascending) order of the (chemical) element's atomic number:

```
hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...

```

... up to the last known (named) chemical element   (at this time).

Do not include any of the   "unnamed"   chemical element names such as:

```
ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium

```

To make computer programming languages comparable,   the statement widths should be
restricted to less than   **81**   bytes (characters),   or less
if a computer programming language has more restrictive limitations or standards.

Also mention what column the programming statements can start in if   *not*
in column one.

The list   *may*   have leading/embedded/trailing blanks during the
declaration   (the actual program statements),   this allows the list to be
more readable.   The "final" list shouldn't have any leading/trailing or superfluous
blanks   (when stored in the program's "memory").

This list should be written with the idea in mind that the
program   *will*   be updated,   most likely by someone other than the
original author,   as there will be newer (discovered) elements of the periodic
table being added   (possibly in the near future).   These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list   (within the computer
program).

Attention should be paid so as to not exceed the   *clause length*   of
continued or specified statements,   if there is such a restriction.   If the
limit is greater than (say) 4,000 bytes or so,   it needn't be mentioned here.

Task
:   * Write a computer program (by whatever name) to contain a list of the known elements.
    * The program should eventually contain a long literal of words   (the elements).
    * The literal should show how one could create a long list of blank-delineated words.
    * The "final" (stored) list should only have a single blank between elements.
    * Try to use the most idiomatic approach(es) in creating the final list.
    * Use continuation if possible, and/or show alternatives   (possibly using concatenation).
    * Use a program comment to explain what the continuation character is if it isn't obvious.
    * The program should contain a variable that has the date of the last update/revision.
    * The program, when run, should display with verbiage:

    :   :   * The last update/revision date   (and should be unambiguous).
            * The number of chemical elements in the list.
            * The name of the highest (last) element name.

Show all output here, on this page.

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]
|  |
| --- |
| This example is **incorrect**. Please fix the code and remove this message.  ***Details:*** The task is to have a list of the names of the elements, not their atomic weight and chemical element symbol.   Also, the element names are not capitalized. |

Incorrectly marked incorrect. Enforcing rules that exists only in somebodies head.

**Works with**: Rakudo version 2020.02

Not really sure I understand the point of this task. Seems to be load some list into memory and manipulate it somehow. Exceptionally boring to just read it in and then read it back out again. Perform some more interesting manipulations. Use < > quoting construct for literal string; unlimited (memory limited) characters, spaces don't matter, new-lines don't matter, blank lines don't matter.

```
my %periodic;
%periodic<revision-date> = Date.new(2020,3,23);
%periodic<table> = |<

         Hydrogen  1.0079     H             Helium  4.0026    He
          Lithium  6.941     Li          Beryllium  9.0122    Be
            Boron  10.811     B             Carbon  12.0107    C
         Nitrogen  14.0067    N             Oxygen  15.9994    O
         Fluorine  18.9984    F               Neon  20.1797   Ne
           Sodium  22.9897   Na          Magnesium  24.305    Mg
         Aluminum  26.9815   Al            Silicon  28.0855   Si
       Phosphorus  30.9738    P             Sulfur  32.065     S
         Chlorine  35.453    Cl          Potassium  39.0983    K
            Argon  39.948    Ar            Calcium  40.078    Ca
         Scandium  44.9559   Sc           Titanium  47.867    Ti
         Vanadium  50.9415    V           Chromium  51.9961   Cr
        Manganese  54.938    Mn               Iron  55.845    Fe
           Nickel  58.6934   Ni             Cobalt  58.9332   Co
           Copper  63.546    Cu               Zinc  65.39     Zn
          Gallium  69.723    Ga          Germanium  72.64     Ge
          Arsenic  74.9216   As           Selenium  78.96     Se
          Bromine  79.904    Br            Krypton  83.8      Kr
         Rubidium  85.4678   Rb          Strontium  87.62     Sr
          Yttrium  88.9059    Y          Zirconium  91.224    Zr
          Niobium  92.9064   Nb         Molybdenum  95.94     Mo
       Technetium  98        Tc          Ruthenium  101.07    Ru
          Rhodium  102.9055  Rh          Palladium  106.42    Pd
           Silver  107.8682  Ag            Cadmium  112.411   Cd
           Indium  114.818   In                Tin  118.71    Sn
         Antimony  121.76    Sb             Iodine  126.9045   I
        Tellurium  127.6     Te              Xenon  131.293   Xe
           Cesium  132.9055  Cs             Barium  137.327   Ba
        Lanthanum  138.9055  La             Cerium  140.116   Ce
     Praseodymium  140.9077  Pr          Neodymium  144.24    Nd
       Promethium  145       Pm           Samarium  150.36    Sm
         Europium  151.964   Eu         Gadolinium  157.25    Gd
          Terbium  158.9253  Tb         Dysprosium  162.5     Dy
          Holmium  164.9303  Ho             Erbium  167.259   Er
          Thulium  168.9342  Tm          Ytterbium  173.04    Yb
         Lutetium  174.967   Lu            Hafnium  178.49    Hf
         Tantalum  180.9479  Ta           Tungsten  183.84     W
          Rhenium  186.207   Re             Osmium  190.23    Os
          Iridium  192.217   Ir           Platinum  195.078   Pt
             Gold  196.9665  Au            Mercury  200.59    Hg
         Thallium  204.3833  Tl               Lead  207.2     Pb
          Bismuth  208.9804  Bi           Polonium  209       Po
         Astatine  210       At              Radon  222       Rn
         Francium  223       Fr             Radium  226       Ra
         Actinium  227       Ac       Protactinium  231.0359  Pa
          Thorium  232.0381  Th          Neptunium  237       Np
          Uranium  238.0289   U          Americium  243       Am
        Plutonium  244       Pu             Curium  247       Cm
        Berkelium  247       Bk        Californium  251       Cf
      Einsteinium  252       Es            Fermium  257       Fm
      Mendelevium  258       Md           Nobelium  259       No
    Rutherfordium  261       Rf         Lawrencium  262       Lr
          Dubnium  262       Db            Bohrium  264       Bh
       Seaborgium  266       Sg         Meitnerium  268       Mt
      Roentgenium  272       Rg            Hassium  277       Hs
     Darmstadtium  ???       Ds        Copernicium  ???       Cn
         Nihonium  ???       Nh          Flerovium  ???       Fl
        Moscovium  ???       Mc        Livermorium  ???       Lv
       Tennessine  ???       Ts          Oganesson  ???       Og

>.words.map: { (:name($^a), :weight($^b), :symbol($^c)).hash };

put 'Revision date: ',                                   %periodic<revision-date>;
put 'Last element by position (nominally by weight): ',  %periodic<table>.tail.<name>;
put 'Total number of elements: ',                        %periodic<table>.elems;
put 'Last element sorted by full name: ',                %periodic<table>.sort( *.<name> ).tail.<name>;
put 'Longest element name: ',                            %periodic<table>.sort( *.<name>.chars ).tail.<name>;
put 'Shortest element name: ',                           %periodic<table>.sort( -*.<name>.chars ).tail.<name>;
put 'Symbols for elements whose name starts with "P": ', %periodic<table>.grep( *.<name>.starts-with('P') )».<symbol>;
put "Elements with molecular weight between 20 & 40:\n ",%periodic<table>.grep( {+.<weight> ~~ Numeric and 20 < .<weight> < 40} )».<name>;
put "SCRN: ",                                            %periodic<table>[87,17,92]».<symbol>.join.tclc;

```

Output:

```
Revision date: 2020-03-23
Last element by position (nominally by weight): Oganesson
Total number of elements: 118
Last element sorted by full name: Zirconium
Longest element name: Rutherfordium
Shortest element name: Tin
Symbols for elements whose name starts with "P": P K Pd Pr Pm Pt Po Pa Pu
Elements with molecular weight between 20 & 40:
 Neon Sodium Magnesium Aluminum Silicon Phosphorus Sulfur Chlorine Potassium Argon
SCRN: Raku
```


[User]
Task

Explicitly implement   long multiplication.

This is one possible approach to arbitrary-precision integer algebra.

For output, display the result of    264 \* 264.

Optionally, verify your result against builtin arbitrary precision support.

The decimal representation of    264    is:

```
18,446,744,073,709,551,616

```

The output of    264 \* 264    is    2128,    and is:

```
340,282,366,920,938,463,463,374,607,431,768,211,456

```

[Assistant]
(formerly Perl 6)

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

For efficiency (and novelty), this program explicitly implements long multiplication, but in base 10000. That base was chosen because multiplying two 5-digit numbers can overflow a 32-bit integer, but two 4-digit numbers cannot.

```
sub num_to_groups ( $num ) { $num.flip.comb(/.**1..4/)».flip     };
sub groups_to_num ( @g   ) { [~] flat @g.pop, @g.reverse».fmt('%04d') };

sub long_multiply ( Str $x, Str $y ) {
    my @group_sums;
    for flat num_to_groups($x).pairs X num_to_groups($y).pairs -> $xp, $yp {
        @group_sums[ $xp.key + $yp.key ] += $xp.value * $yp.value;
    }

    for @group_sums.keys -> $k {
        next if @group_sums[$k] < 10000;
        @group_sums[$k+1] += @group_sums[$k].Int div 10000;
        @group_sums[$k] %= 10000;
    }

    return groups_to_num @group_sums;
}

my $str = '18446744073709551616';
long_multiply( $str, $str ).say;

# cross-check with native implementation
say +$str * +$str;

```

Output:

```
340282366920938463463374607431768211456
340282366920938463463374607431768211456

```


[User]
A   **long prime**   (as defined here)   is a prime number whose reciprocal   (in decimal)   has
a   *period length*   of one less than the prime number.

**Long primes**   are also known as:

:   :   :   * base ten cyclic numbers
            * full reptend primes
            * golden primes
            * long period primes
            * maximal period primes
            * proper primes

Another definition:   primes   **p**   such that the decimal expansion of   **1/p**   has period   **p-1**,   which is the greatest period possible for any integer.

Example

**7**   is the first long prime,   the reciprocal of seven
is   **1****/****7**,   which
is equal to the repeating decimal fraction   **0.142857142857···**

The length of the   *repeating*   part of the decimal fraction
is six,   (the underlined part)   which is one less
than the (decimal) prime number   **7**.

Thus   **7**   is a long prime.

There are other (more) general definitions of a   **long prime**   which
include wording/verbiage for bases other than ten.

Task
:   * Show all long primes up to   **500**   (preferably on one line).
    * Show the   *number*   of long primes up to         **500**
    * Show the   *number*   of long primes up to      **1,000**
    * Show the   *number*   of long primes up to      **2,000**
    * Show the   *number*   of long primes up to      **4,000**
    * Show the   *number*   of long primes up to      **8,000**
    * Show the   *number*   of long primes up to   **16,000**
    * Show the   *number*   of long primes up to   **32,000**
    * Show the   *number*   of long primes up to   **64,000**   (optional)
    * Show all output here.

Also see

* Wikipedia: full reptend prime
* MathWorld: full reptend prime
* OEIS: A001913

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.06

Not very fast as the numbers get larger.

```
use Math::Primesieve;
my $sieve = Math::Primesieve.new;

sub is-long (Int $p) {
    my $r = 1;
    my $rr = $r = (10 * $r) % $p for ^$p;
    my $period;
    loop {
        $r = (10 * $r) % $p;
        ++$period;
        last if $period >= $p or $r == $rr;
    }
    $period == $p - 1 and $p > 2;
}

my @primes = $sieve.primes(500);
my @long-primes = @primes.grep: {.&is-long};

put "Long primes ≤ 500:\n", @long-primes;

@long-primes = ();

for 500, 1000, 2000, 4000, 8000, 16000, 32000, 64000 -> $upto {
    state $from = 0;
    my @extend = $sieve.primes($from, $upto);
    @long-primes.append: @extend.hyper(:8degree).grep: {.&is-long};
    say "\nNumber of long primes ≤ $upto: ", +@long-primes;
    $from = $upto;
}

```

Output:

```
Long primes ≤ 500:
7 17 19 23 29 47 59 61 97 109 113 131 149 167 179 181 193 223 229 233 257 263 269 313 337 367 379 383 389 419 433 461 487 491 499

Number of long primes ≤ 500: 35

Number of long primes ≤ 1000: 60

Number of long primes ≤ 2000: 116

Number of long primes ≤ 4000: 218

Number of long primes ≤ 8000: 390

Number of long primes ≤ 16000: 716

Number of long primes ≤ 32000: 1300

Number of long primes ≤ 64000: 2430
```


[User]
An evil wizard has trapped you in the stairwell of his castle. Your only hope of escape is to run up all 100 steps to reach the top, and you can run one step per second. Unfortunately the wizard uses magic to lengthen the staircase by five steps per second. The new steps are inserted randomly between existing steps, so if you're lucky some of them might be beneath you and not ahead of you.

Can you escape, or are you doomed to run up an ever-lengthening staircase forever?

Write a program to simulate your escape attempt. How are you doing after ten minutes? For every second between 600 and 609 seconds inclusive print the number of steps behind you and the number still ahead of you.

If you escaped, run 10,000 tests and print the average time taken and the average final length of the staircase.

[Assistant]
```
my ($trials, $t-total, $s-total) = 10000;

say 'Seconds  steps behind  steps ahead';

race for ^$trials {
    my $stairs   = 100;
    my $location = 0;
    my $seconds  = 0;

    loop {
        ++$seconds;
        ++$location;
        last if $location > $stairs;
        for (1..$stairs).roll(5) {
            ++$location if $_ <= $location;
            ++$stairs;
        }
        say "  $seconds        $location         {$stairs-$location}" if !$_ && (599 < $seconds < 610);
    }

    $t-total += $seconds;
    $s-total += $stairs;
}

say "Average seconds: {$t-total/$trials},  Average steps: {$s-total/$trials}";

```

Sample output:

```
Seconds  steps behind  steps ahead
  600        2143         957
  601        2149         956
  602        2153         957
  603        2158         957
  604        2164         956
  605        2170         955
  606        2175         955
  607        2178         957
  608        2183         957
  609        2187         958
Average seconds: 2716.0197,  Average steps: 13677.143
```


[User]
Most years have 52 weeks, some have 53, according to ISO8601.

Task

Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

December 28 is always in the last week of the year. (By ISO8601)

```
sub is-long ($year) { Date.new("$year-12-28").week[1] == 53 }

# Testing
say   "Long years in the 20th century:\n", (1900..^2000).grep: &is-long;
say "\nLong years in the 21st century:\n", (2000..^2100).grep: &is-long;
say "\nLong years in the 22nd century:\n", (2100..^2200).grep: &is-long;

```

Output:

```
Long years in the 20th century:
(1903 1908 1914 1920 1925 1931 1936 1942 1948 1953 1959 1964 1970 1976 1981 1987 1992 1998)

Long years in the 21st century:
(2004 2009 2015 2020 2026 2032 2037 2043 2048 2054 2060 2065 2071 2076 2082 2088 2093 2099)

Long years in the 22nd century:
(2105 2111 2116 2122 2128 2133 2139 2144 2150 2156 2161 2167 2172 2178 2184 2189 2195)
```


[User]
It is often useful to find the common prefix of a set of strings, that is, the longest initial portion of all strings that are identical.

Given a set of strings, *R*, for a prefix *S*, it should hold that:

:   ∀
    x

    ∈

    R
    :

    S
    ≤
    {\displaystyle {\displaystyle \forall x\ \in \ R:\ S\leq }}
    pref

    x
    {\displaystyle {\displaystyle \ x}}
     ~ "for all members *x* of set *R*, it holds true that string *S* is a prefix of *x*"
:   (help here: *does not express that* S *is the longest common prefix of* x)

An example use case for this: given a set of phone numbers, identify a common dialing code. This can be accomplished by first determining the common prefix (if any), and then matching it against know dialing codes (iteratively dropping characters from rhs until a match is found, as the *lcp* function may match more than the dialing code).

Test cases

For a function, *lcp*, accepting a list of strings, the following should hold true
(the empty string,

ε
{\displaystyle {\displaystyle \varepsilon }}
, is considered a prefix of all strings):

```
lcp("interspecies","interstellar","interstate") = "inters"
lcp("throne","throne") = "throne"
lcp("throne","dungeon") =

            ε

    {\displaystyle {\displaystyle \varepsilon }}

lcp("throne",

            ε

    {\displaystyle {\displaystyle \varepsilon }}

,"throne") =

            ε

    {\displaystyle {\displaystyle \varepsilon }}

lcp("cheese") = "cheese"
lcp(

            ε

    {\displaystyle {\displaystyle \varepsilon }}

) =

            ε

    {\displaystyle {\displaystyle \varepsilon }}

lcp(

            ∅

    {\displaystyle {\displaystyle \emptyset }}

) =

            ε

    {\displaystyle {\displaystyle \varepsilon }}

lcp("prefix","suffix") =

            ε

    {\displaystyle {\displaystyle \varepsilon }}

lcp("foo","foobar") = "foo"

```

*Task inspired by this stackoverflow question*: Find the longest common starting substring in a set of strings

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 2015-11-28

This should work on infinite strings (if and when we get them), since .ords is lazy. In any case, it does just about the minimal work by evaluating all strings lazily in parallel. A few explanations of the juicy bits: @s is the list of strings, and the hyper operator » applies the .ords to each of those strings, producing a list of lists. The | operator inserts each of those sublists as an argument into an argument list so that we can use a reduction operator across the list of lists, which makes sense if the operator in question knows how to deal with list arguments. In this case we use the Z ('zip') metaoperator with eqv as a base operator, which runs eqv across all the lists in parallel for each position, and will fail if not all the lists have the same ordinal value at that position, or if any of the strings run out of characters. Then we count up the leading matching positions and carve up one of the strings to that length.

```
multi lcp()    { '' }
multi lcp($s)  { ~$s }
multi lcp(*@s) { substr @s[0], 0, [+] [\and] [Zeqv] |@s».ords }

use Test;
plan 8;

is lcp("interspecies","interstellar","interstate"), "inters";
is lcp("throne","throne"), "throne";
is lcp("throne","dungeon"), '';
is lcp("cheese"), "cheese";
is lcp(''), '';
is lcp(), '';
is lcp("prefix","suffix"), '';
is lcp("foo","foobar"), 'foo';

```

Output:

```
1..8
ok 1 -
ok 2 -
ok 3 -
ok 4 -
ok 5 -
ok 6 -
ok 7 -
ok 8 -
```


[User]
**Introduction**

Define a *subsequence* to be any output string obtained by deleting zero or more symbols from an input string.

The Longest Common Subsequence (**LCS**) is a subsequence of maximum length common to two or more strings.

Let *A* ≡ *A*[0]… *A*[m - 1] and *B* ≡ *B*[0]… *B*[n - 1], m < n be strings drawn from an alphabet Σ of size s, containing every distinct symbol in A + B.

An ordered pair (i, j) will be referred to as a match if *A*[i] = *B*[j], where 0 ≤ i < m and 0 ≤ j < n.

The set of matches **M** defines a relation over matches: **M**[i, j] ⇔ (i, j) ∈ **M**.

Define a *non-strict* product-order (≤) over ordered pairs, such that (i1, j1) ≤ (i2, j2) ⇔ i1 ≤ i2 and j1 ≤ j2. We define (≥) similarly.

We say ordered pairs p1 and p2 are *comparable* if either p1 ≤ p2 or p1 ≥ p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 ≤ p2 nor p1 ≥ p2 are possible, and we say p1 and p2 are *incomparable*.

Define the *strict* product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) ⇔ i1 < i2 and j1 < j2. We define (>) similarly.

A chain **C** is a subset of **M** consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain **D** is any subset of **M** in which every pair of distinct elements m1 and m2 are incomparable.

A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m\*n coordinate space of **M**[i, j].

Every Common Sequence of length *q* corresponds to a chain of cardinality *q*, over the set of matches **M**. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality *p*.

According to [Dilworth 1950], this cardinality *p* equals the minimum number of disjoint antichains into which **M** can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.

**Background**

Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(*m\*n*) quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.

The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(*n*). However, this approach requires O(*m\*n*) time even in the best case.

This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.

In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(*n*) growth.

A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(*n log m*). Performance can degrade to O(*m\*n log m*) time in the worst case, as the number of matches grows to O(*m\*n*).

**Note**

[Rick 2000] describes a linear-space algorithm with a time bound of O(*n\*s + p\*min(m, n - p)*).

**Legend**

```
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of matches (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet Σ of distinct symbols in A + B

```

**References**

[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, *pp.* 161-166]

[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, *pp.* 45-66]

[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, *pp.* 341-343]

[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41

[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, *pp.* 350-353]

[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, *pp.* 275–281]

**Examples**

The sequences "1234" and "1224533324" have an LCS of "1234":

```
1234
1224533324

```

For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":

```
thisisatest
testing123testing

```

In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.

For more information on this problem please see Wikipedia.

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)

### Recursion

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

This solution is similar to the Haskell one. It is slow.

```
say lcs("thisisatest", "testing123testing");sub lcs(Str $xstr, Str $ystr) {
    return "" unless $xstr && $ystr;

    my ($x, $xs, $y, $ys) = $xstr.substr(0, 1), $xstr.substr(1), $ystr.substr(0, 1), $ystr.substr(1);
    return $x eq $y
        ?? $x ~ lcs($xs, $ys)
        !! max(:by{ $^a.chars }, lcs($xstr, $ys), lcs($xs, $ystr) );
}

say lcs("thisisatest", "testing123testing");

```

### Dynamic Programming

**Translation of**: Java

```
sub lcs(Str $xstr, Str $ystr) {
    my ($xlen, $ylen) = ($xstr, $ystr)>>.chars;
    my @lengths = map {[(0) xx ($ylen+1)]}, 0..$xlen;

    for $xstr.comb.kv -> $i, $x {
        for $ystr.comb.kv -> $j, $y {
            @lengths[$i+1][$j+1] = $x eq $y ?? @lengths[$i][$j]+1 !! (@lengths[$i+1][$j], @lengths[$i][$j+1]).max;
        }
    }

    my @x = $xstr.comb;
    my ($x, $y) = ($xlen, $ylen);
    my $result = "";
    while $x != 0 && $y != 0 {
        if @lengths[$x][$y] == @lengths[$x-1][$y] {
            $x--;
        }
        elsif @lengths[$x][$y] == @lengths[$x][$y-1] {
            $y--;
        }
        else {
            $result = @x[$x-1] ~ $result;
            $x--;
            $y--;
        }
    }

    return $result;
}

say lcs("thisisatest", "testing123testing");

```

### Bit Vector

Bit parallel dynamic programming with nearly linear complexity O(n). It is fast.

```
sub lcs(Str $xstr, Str $ystr) {
    my (@a, @b) := ($xstr, $ystr)».comb;
    my (%positions, @Vs, $lcs);

    for @a.kv -> $i, $x { %positions{$x} +|= 1 +< ($i % @a) }

    my $S = +^ 0;
    for (0 ..^ @b) -> $j {
        my $u = $S +& (%positions{@b[$j]} // 0);
        @Vs[$j] = $S = ($S + $u) +| ($S - $u)
    }

    my ($i, $j) = @a-1, @b-1;
    while ($i ≥ 0 and $j ≥ 0) {
        unless (@Vs[$j] +& (1 +< $i)) {
            $lcs [R~]= @a[$i] unless $j and ^@Vs[$j-1] +& (1 +< $i);
            $j--
        }
        $i--
    }
    $lcs
}

say lcs("thisisatest", "testing123testing");

```


[User]
Task

Write a function that returns the longest common substring of two strings.

Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".

Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.

Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub*string* is just "test".

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

References

* Generalize Suffix Tree
* Ukkonen’s Suffix Tree Construction

[Assistant]
(formerly Perl 6)

```
sub createSubstrings( Str $word --> Array ) {
   my $length = $word.chars ;
   my @substrings ;
   for (0..$length - 1) -> $start {
      for (1..$length - $start) -> $howmany {
	 @substrings.push( $word.substr( $start , $howmany ) ) ;
      }
   }
   return @substrings ;
}

sub findLongestCommon( Str $first , Str $second --> Str ) {
   my @substringsFirst  = createSubstrings( $first ) ;
   my @substringsSecond = createSubstrings( $second ) ;
   my $firstset  = set( @substringsFirst ) ;
   my $secondset = set( @substringsSecond ) ;
   my $common = $firstset (&) $secondset ;
   return $common.keys.sort({$^b.chars <=> $^a.chars})[0] ; # or: sort(-*.chars)[0]
}

sub MAIN( Str $first , Str $second ) {
   say "The longest common substring of $first and $second is " ~
   "{findLongestCommon( $first , $second ) } !" ;
}

```

Output:

```
The longest common substring of thisisatest and testing123testing is test !
```

### Functional

```
sub substrings ($s)       { (flat (0..$_ X 1..$_).grep:{$_ ≥ [+] @_}).map: { $s.substr($^a, $^b) } given $s.chars }
sub infix:<LCS>($s1, $s2) { ([∩] ($s1, $s2)».&substrings).keys.sort(*.chars).tail }

my $first  = 'thisisatest';
my $second = 'testing123testing';
say "The longest common substring between '$first' and '$second' is '{$first LCS $second}'.";

```

Output:

```
The longest common substring between 'thisisatest' and 'testing123testing' is 'test'.
```


[User]
Task

Write a function to find the longest common suffix string amongst an array of strings.

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]
**Works with**: Rakudo version 2020.07

```
sub longest-common-suffix ( *@words ) {
    return '' unless +@words;
    my $min = @words».chars.min;
    for 1 .. * {
        return @words[0].substr(* - $min) if $_ > $min;
        next if @words».substr(* - $_).Set == 1;
        return @words[0].substr(* - $_ + 1);
    }
}

say "{$_.raku} - LCS: >{longest-common-suffix $_}<" for
  <Sunday Monday Tuesday Wednesday Thursday Friday Saturday>,
  <Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag dag>,
  ( 2347, 9312347, 'acx5g2347', 12.02347 ),
  <longest common suffix>,
  ('one, Hey!', 'three, Hey!', 'ale, Hey!', 'me, Hey!'),
  'suffix',
  ''

```

Output:

```
("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") - LCS: >day<
("Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag", "dag") - LCS: >dag<
(2347, 9312347, "acx5g2347", 12.02347) - LCS: >2347<
("longest", "common", "suffix") - LCS: ><
("one, Hey!", "three, Hey!", "ale, Hey!", "me, Hey!") - LCS: >e, Hey!<
"suffix" - LCS: >suffix<
"" - LCS: ><
```


[User]
Calculate and show here a longest increasing subsequence of the list:

:   {
    3
    ,
    2
    ,
    6
    ,
    4
    ,
    5
    ,
    1
    }
    {\displaystyle {\displaystyle \{3,2,6,4,5,1\}}}

And of the list:

:   {
    0
    ,
    8
    ,
    4
    ,
    12
    ,
    2
    ,
    10
    ,
    6
    ,
    14
    ,
    1
    ,
    9
    ,
    5
    ,
    13
    ,
    3
    ,
    11
    ,
    7
    ,
    15
    }
    {\displaystyle {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}}}

Note that a list may have more than one subsequence that is of the maximum length.

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

Ref

1. Dynamic Programming #1: Longest Increasing Subsequence on YouTube
2. An efficient solution can be based on Patience sorting.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

### Dynamic programming

Straight-forward implementation of the algorithm described in the video.

```
sub lis(@d) {
    my @l = [].item xx @d;
    @l[0].push: @d[0];
    for 1 ..^ @d -> $i {
        for ^$i -> $j {
            if @d[$j] < @d[$i] && @l[$i] < @l[$j] + 1 {
                @l[$i] = [ @l[$j][] ]
            }
        }
        @l[$i].push: @d[$i];
    }
    return max :by(*.elems), @l;
}

say lis([3,2,6,4,5,1]);
say lis([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]);

```

Output:

```
[2 4 5]
[0 2 6 9 11 15]
```

### Patience sorting

```
sub lis(@deck is copy) {
    my @S = [@deck.shift() => Nil].item;
    for @deck -> $card {
        with first { @S[$_][*-1].key > $card }, ^@S -> $i {
            @S[$i].push: $card => @S[$i-1][*-1] // Nil
        } else {
            @S.push: [ $card => @S[*-1][*-1] // Nil ].item
        }
    }
    reverse map *.key, (
        @S[*-1][*-1], *.value ...^ !*.defined
    )
}

say lis <3 2 6 4 5 1>;
say lis <0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15>;

```

Output:

```
[2 4 5]
[0 2 6 9 11 15]
```


[User]
Let given a string s.
The goal is to find the longest palindromic substring in s.

Related tasks

* Palindrome\_detection

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]
**Works with**: Rakudo version 2020.09

This version regularizes (ignores) case and ignores non alphanumeric characters. It is only concerned with finding the *longest* palindromic substrings so does not exhaustively find *all possible* palindromes. If a palindromic substring is found to be part of a longer palindrome, it is not captured separately. Showing the longest 5 palindromic substring groups. Run it with no parameters to operate on the default; pass in a file name to run it against that instead.

```
my @chars = ( @*ARGS[0] ?? @*ARGS[0].IO.slurp !! q:to/BOB/ ) .lc.comb: /\w/;
    Lyrics to "Bob" copyright Weird Al Yankovic
    https://www.youtube.com/watch?v=JUQDzj6R3p4

    I, man, am regal - a German am I
    Never odd or even
    If I had a hi-fi
    Madam, I'm Adam
    Too hot to hoot
    No lemons, no melon
    Too bad I hid a boot
    Lisa Bonet ate no basil
    Warsaw was raw
    Was it a car or a cat I saw?

    Rise to vote, sir
    Do geese see God?
    "Do nine men interpret?" "Nine men," I nod
    Rats live on no evil star
    Won't lovers revolt now?
    Race fast, safe car
    Pa's a sap
    Ma is as selfless as I am
    May a moody baby doom a yam?

    Ah, Satan sees Natasha
    No devil lived on
    Lonely Tylenol
    Not a banana baton
    No "x" in "Nixon"
    O, stone, be not so
    O Geronimo, no minor ego
    "Naomi," I moan
    "A Toyota's a Toyota"
    A dog, a panic in a pagoda

    Oh no! Don Ho!
    Nurse, I spy gypsies - run!
    Senile felines
    Now I see bees I won
    UFO tofu
    We panic in a pew
    Oozy rat in a sanitary zoo
    God! A red nugget! A fat egg under a dog!
    Go hang a salami, I'm a lasagna hog!
    BOB
#"

my @cpfoa = flat
(1 ..^ @chars).race(:1000batch).map: -> \idx {
    my @s;
    for 1, 2 {
       my int ($rev, $fwd) = $_, 1;
       loop {
            quietly last if ($rev > idx) || (@chars[idx - $rev] ne @chars[idx + $fwd]);
            $rev = $rev + 1;
            $fwd = $fwd + 1;
        }
        @s.push: @chars[idx - $rev ^..^ idx + $fwd].join if $rev + $fwd > 2;
        last if @chars[idx - 1] ne @chars[idx];
    }
    next unless +@s;
    @s
}

"{.key} ({+.value})\t{.value.unique.sort}".put for @cpfoa.classify( *.chars ).sort( -*.key ).head(5);

```

Output:

Returns the length, (the count) and the list:

```
29 (2)	doninemeninterpretninemeninod godarednuggetafateggunderadog
26 (1)	gohangasalamiimalasagnahog
23 (1)	arwontloversrevoltnowra
21 (4)	imanamregalagermanami mayamoodybabydoomayam ootnolemonsnomelontoo oozyratinasanitaryzoo
20 (1)	ratsliveonnoevilstar

```

This isn't intensively optimised but isn't too shabby either. When run against the first million digits of pi: 1000000 digits of pi text file (Pass in the file path/name at the command line) we get:

```
13 (1)	9475082805749
12 (1)	450197791054
11 (8)	04778787740 09577577590 21348884312 28112721182 41428782414 49612121694 53850405835 84995859948
10 (9)	0045445400 0136776310 1112552111 3517997153 5783993875 6282662826 7046006407 7264994627 8890770988
9 (98)	019161910 020141020 023181320 036646630 037101730 037585730 065363560 068363860 087191780 091747190 100353001 104848401 111262111 131838131 132161231 156393651 160929061 166717661 182232281 193131391 193505391 207060702 211878112 222737222 223404322 242424242 250171052 258232852 267919762 272636272 302474203 313989313 314151413 314424413 318272813 323212323 330626033 332525233 336474633 355575553 357979753 365949563 398989893 407959704 408616804 448767844 450909054 463202364 469797964 479797974 480363084 489696984 490797094 532121235 546000645 549161945 557040755 559555955 563040365 563828365 598292895 621969126 623707326 636414636 636888636 641949146 650272056 662292266 667252766 681565186 684777486 712383217 720565027 726868627 762727267 769646967 777474777 807161708 819686918 833303338 834363438 858838858 866292668 886181688 895505598 896848698 909565909 918888819 926676629 927202729 929373929 944525449 944848449 953252359 972464279 975595579 979202979 992868299
```

in right around 7 seconds on my system.


[User]
Background

This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code.

Basic problem statement

Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output.
If there are ties for the longest line, the program writes out all the lines that tie.
If there is no input, the program should produce no output.

Task

Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below).

Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done.

This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches.

Given the input:

```
a
bb
ccc
ddd
ee
f
ggg

```

the output should be (possibly rearranged):

```
ccc
ddd
ggg

```

Original list of restrictions

1. No comparison operators may be used.
2. No arithmetic operations, such as addition and subtraction, may be used.
3. The only datatypes you may use are integer and string. In particular, you may not use lists.
4. Do not re-read the input file. Avoid using files as a replacement for lists (this restriction became apparent in the discussion).

Intent of restrictions

Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions.

The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it.

The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description.

Now having said that, the restrictions require some elaboration.

* In general, the restrictions are meant to avoid the explicit use of these features.
* "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable.
* "No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc.
* The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here.

To make this a bit more concrete, here are a couple of specific examples:
In C, a string is an array of chars, so using a couple of arrays as strings is in the spirit while using a second array in a non-string like fashion would violate the intent.
In APL or J, arrays are the core of the language so ruling them out is unfair. Meeting the spirit will come down to how they are used.

Please keep in mind these are just examples and you may hit new territory finding a solution. There will be other cases like these. Explain your reasoning. You may want to open a discussion on the talk page as well.

* The added "No rereading" restriction is for practical reasons, re-reading stdin should be broken. I haven't outright banned the use of other files but I've discouraged them as it is basically another form of a list. Somewhere there may be a language that just sings when doing file manipulation and where that makes sense; however, for most there should be a way to accomplish without resorting to an externality.

At the end of the day for the implementer this should be a bit of fun. As an implementer you represent the expertise in your language, the reader may have no knowledge of your language. For the reader it should give them insight into how people think outside the box in other languages. Comments, especially for non-obvious (to the reader) bits will be extremely helpful. While the implementations may be a bit artificial in the context of this task, the general techniques may be useful elsewhere.

[Assistant]
(formerly Perl 6)

```
my $l = '';  # Sample longest string seen.
my $a = '';  # Accumulator to save longest strings.

while get() -> $s {
   my $n = "$s\n";
   if $n.substr($l.chars) {     # Is new string longer?
       $a = $l = $n;            # Reset accumulator.
   }
   elsif !$l.substr($n.chars) { # Same length?
      $a ~= $n;                 # Accumulate it.
   }
}
print $a;

```

Given the example input, returns:

```
ccc
ddd
ggg
```


[User]
Task

Given a string,   find the   **longest substring**   without any repeating characters.

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]
Detects **any** character when checking for repeated characters, even multi-byte composite characters, control sequences and whitespace.

Note that there is no requirement that the substrings be unique, only that each has no repeated characters internally.

Not going to bother handling arrays since an array is not a string, and the task description **specifically** says 'Given a string'.

```
sub abbreviate ($_) { .chars > 80 ?? "(abbreviated)\n" ~ .substr(0,35) ~ ' ... ' ~ .substr(*-35) !! $_ }

sub longest ($string) {
   return 0 => [] unless $string.chars;
   my ($start, $end, @substr) = 0, 0;
   while ++$end < $string.chars {
       my $sub = $string.substr($start, $end - $start);
       if $sub.contains: my $next = $string.substr: $end, 1 {
           @substr[$end - $start].push($sub) if $end - $start >= @substr.end;
           $start += 1 + $sub.index($next);
       }
   }
   @substr[$end - $start].push: $string.substr($start);
   @substr.pairs.tail
}

# Testing
say "\nOriginal string: {abbreviate $_}\nLongest substring(s) chars: ", .&longest

# Standard tests
for flat qww< xyzyabcybdfd xyzyab zzzzz a '' >,

# multibyte Unicode
< 👒🎩🎓👩👩👦👦🧢🎓👨👧👧👒👩👩👦👦🎩🎓👒🧢 α⊆϶α϶ >,

# check a file
slurp 'unixdict.txt';

```

Output:

```
Original string: xyzyabcybdfd
Longest substring(s) chars: 5 => [zyabc cybdf]

Original string: xyzyab
Longest substring(s) chars: 4 => [zyab]

Original string: zzzzz
Longest substring(s) chars: 1 => [z z z z z]

Original string: a
Longest substring(s) chars: 1 => [a]

Original string:
Longest substring(s) chars: 0 => []

Original string: 👒🎩🎓👩👩👦👦🧢🎓👨👧👧👒👩👩👦👦🎩🎓👒🧢
Longest substring(s) chars: 6 => [🧢🎓👨👧👧👒👩👩👦👦🎩]

Original string: α⊆϶α϶
Longest substring(s) chars: 3 => [α⊆϶ ⊆϶α]

Original string: (abbreviated)
10th
1st
2nd
3rd
4th
5th
6th
7th
8t ... rian
zounds
zucchini
zurich
zygote

Longest substring(s) chars: 15 => [mbowel
disgrunt]
```