[User]
Solve the Stable marriage problem using the Gale/Shapley algorithm.

**Problem description**
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.

A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman *also* prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.

Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.

**Task Specifics**
Given ten males:

```
   abe, bob, col, dan, ed, fred, gav, hal, ian, jon

```

And ten females:

```
   abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan

```

And a complete list of ranked preferences, where the most liked is to the left:

```
  abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
  bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
  col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
  dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
   ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
 fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
  gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
  hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
  ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
  jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope

  abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
  bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
 cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
  dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
  eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
  fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
  gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
 hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
  ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
  jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan

```

1. Use the Gale Shapley algorithm to find a stable set of engagements
2. Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.

**References**

1. The Stable Marriage Problem. (Eloquent description and background information).
2. Gale-Shapley Algorithm Demonstration.
3. Another Gale-Shapley Algorithm Demonstration.
4. Stable Marriage Problem - Numberphile (Video).
5. Stable Marriage Problem (the math bit) (Video).
6. The Stable Marriage Problem and School Choice. (Excellent exposition)

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.10

**Translation of**: Perl

```
my %he-likes =
    abe  => < abi eve cath ivy jan dee fay bea hope gay >,
    bob  => < cath hope abi dee eve fay bea jan ivy gay >,
    col  => < hope eve abi dee bea fay ivy gay cath jan >,
    dan  => < ivy fay dee gay hope eve jan bea cath abi >,
    ed   => < jan dee bea cath fay eve abi ivy hope gay >,
    fred => < bea abi dee gay eve ivy cath jan hope fay >,
    gav  => < gay eve ivy bea cath abi dee hope jan fay >,
    hal  => < abi eve hope fay ivy cath jan bea gay dee >,
    ian  => < hope cath dee gay bea abi fay ivy jan eve >,
    jon  => < abi fay jan gay eve bea dee cath ivy hope >,
;

my %she-likes =
    abi  => < bob fred jon gav ian abe dan ed col hal >,
    bea  => < bob abe col fred gav dan ian ed jon hal >,
    cath => < fred bob ed gav hal col ian abe dan jon >,
    dee  => < fred jon col abe ian hal gav dan bob ed >,
    eve  => < jon hal fred dan abe gav col ed ian bob >,
    fay  => < bob abe ed ian jon dan fred gav col hal >,
    gay  => < jon gav hal fred bob abe col ed dan ian >,
    hope => < gav jon bob abe ian dan hal ed col fred >,
    ivy  => < ian col hal gav fred bob abe ed jon dan >,
    jan  => < ed hal gav abe bob jon col ian fred dan >,
;

my %fiancé;
my %fiancée;
my %proposed;

sub she-prefers ($her, $hottie) { .index($hottie) < .index(%fiancé{$her}) given ~%she-likes{$her} }
sub he-prefers  ($him, $hottie) { .index($hottie) < .index(%fiancée{$him}) given ~%he-likes{$him} }

match'em;
check-stability;

perturb'em;
check-stability;

sub match'em {                                          #'
    say 'Matchmaking:';
    while unmatched-guy() -> $guy {
        my $gal = preferred-choice($guy);
        %proposed{"$guy $gal"} = '❤';
        if not %fiancé{$gal} {
            engage($guy, $gal);
            say "\t$gal and $guy";
        }
        elsif she-prefers($gal, $guy) {
	    my $engaged-guy = %fiancé{$gal};
	    engage($guy, $gal);
	    %fiancée{$engaged-guy} = '';
	    say "\t$gal dumped $engaged-guy for $guy";
	}
    }
}

sub check-stability {
    my @instabilities = gather for flat %he-likes.keys X %she-likes.keys -> $m, $w {
	if he-prefers($m, $w) and she-prefers($w, $m) {
	    take "\t$w prefers $m to %fiancé{$w} and $m prefers $w to %fiancée{$m}";
	}
    }

    say 'Stablility:';
    if @instabilities {
	.say for @instabilities;
    }
    else {
        say "\t(all marriages stable)";
    }
}

sub unmatched-guy { %he-likes.keys.first: { not %fiancée{$_} } }

sub preferred-choice($guy) { %he-likes{$guy}.first: { not %proposed{"$guy $_" } } }

sub engage($guy, $gal) {
    %fiancé{$gal} = $guy;
    %fiancée{$guy} = $gal;
}

sub perturb'em {                                            #'
    say 'Perturb:';
    say "\tengage abi with fred and bea with jon";
    engage('fred', 'abi');
    engage('jon', 'bea');
}

```

Output:

```
Matchmaking:
        cath and bob
        ivy and dan
        abi and jon
        hope and ian
        jan and ed
        eve and abe
        eve dumped abe for hal
        ivy dumped dan for abe
        fay and dan
        gay and gav
        bea and fred
        dee and col
Stablility:
        (all marriages stable)
Perturb:
        engage abi with fred and bea with jon
Stablility:
        fay prefers jon to dan and jon prefers fay to bea
        eve prefers jon to hal and jon prefers eve to bea
        gay prefers jon to gav and jon prefers gay to bea
        bea prefers fred to jon and fred prefers bea to abi
```


[User]
A **stack** is a container of elements with   last in, first out   access policy.   Sometimes it also called **LIFO**.

The stack is accessed through its **top**.

The basic stack operations are:

* *push*   stores a new element onto the stack top;
* *pop*   returns the last pushed stack element, while removing it from the stack;
* *empty*   tests if the stack contains no elements.

Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):

* *top*   (sometimes called *peek* to keep with the *p* theme) returns the topmost element without modifying the stack.

Stacks allow a very simple hardware implementation.

They are common in almost all processors.

In programming, stacks are also very popular for their way (**LIFO**) of resource management, usually memory.

Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).

This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.

See stack machine.

Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.

Task

Create a stack supporting the basic operations: push, pop, empty.

See also

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

[Assistant]
(formerly Perl 6)

Raku still has the stack functions from Perl 5, but now they also can be accessed by object notation:

```
my @stack;          # just a array
@stack.push($elem); # add $elem to the end of @stack
$elem = @stack.pop; # get the last element back
@stack.elems == 0   # true, because the stack is empty
not @stack          # also true because @stack is false
```


[User]
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.

Task

Print out (in a manner considered suitable for the platform) the current call stack.

The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.

You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.

The task should allow the program to continue after generating the stack trace.

The task report here must include the trace from a sample program.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2013-03-03

```
sub g { say Backtrace.new.concise }
sub f { g }
sub MAIN { f }

```

Output:

```
  in sub g at bt:1
  in sub f at bt:2
  in sub MAIN at bt:3
```


[User]
From Chung-Chieh Shan (LtU):

Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.

Write a function "step\_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step\_up"? Can you avoid using variables (even immutable ones) and numbers?

Here's a pseudo-code of a simple recursive solution without using variables:

```
func step_up()
{
    if not step() {
        step_up();
        step_up();
    }
}

```

Inductive proof that step\_up() steps up one step, if it terminates:

* Base case (if the step() call returns true): it stepped up one step. QED
* Inductive case (if the step() call returns false): Assume that recursive calls to step\_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step\_up() calls. QED

The second (tail) recursion above can be turned into an iteration, as follows:

```
func step_up()
{
    while not step() {
        step_up();
    }
}

```

[Assistant]
(formerly Perl 6)

```
sub step_up { step_up until step; }

```


[User]
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run.

Task

Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.

Languages that always run from main() can be omitted from this task.

[Assistant]
(formerly Perl 6)
When executed with the standard setting, Raku code always runs the mainline code automatically, followed by the MAIN function if you have one. However, it's possible to start up with an alternate setting that might want to create its own event loop or MAIN. In such cases you can
always capture control at various phases with blocks that we call "phasers":

```
BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
INIT {...}  # beginning of run time
END {...}   # end of run time

```


[User]
Build and show a web page displaying the data from the task separate the house number from the street name in a formatted and colored table.

Task

Write the code which automatically opens a web page in a browser showing the addresses.
*No static data must be shown, only processed data.*

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.09

Uses the code from the Separate the house number from the street name task almost verbatim. Included here to make a complete, runnable example.

```
use File::Temp;

my $addresses = qq :to /END/;
    Plataanstraat 5
    Straat 12
    Straat 12 II
    Dr. J. Straat   12
    Dr. J. Straat 12 a
    Dr. J. Straat 12-14
    Laan 1940 – 1945 37
    Plein 1940 2
    1213-laan 11
    16 april 1944 Pad 1
    1e Kruisweg 36
    Laan 1940-’45 66
    Laan ’40-’45
    Langeloërduinen 3 46
    Marienwaerdt 2e Dreef 2
    Provincialeweg N205 1
    Rivium 2e Straat 59.
    Nieuwe gracht 20rd
    Nieuwe gracht 20rd 2
    Nieuwe gracht 20zw /2
    Nieuwe gracht 20zw/3
    Nieuwe gracht 20 zw/4
    Bahnhofstr. 4
    Wertstr. 10
    Lindenhof 1
    Nordesch 20
    Weilstr. 6
    Harthauer Weg 2
    Mainaustr. 49
    August-Horch-Str. 3
    Marktplatz 31
    Schmidener Weg 3
    Karl-Weysser-Str. 6
    END

my @row-color = '#d7fffe', '#9dbcd4';

# build the table
sub genTable () {
    my $table = '<table border="2"> <tr bgcolor="#02ccfe">' ~
    qq|<th>Address</th><th>Street</th><th>House Number</th>\n|;
    my $i = 0;
    for $addresses.lines -> $addr {
        $table ~= qq|<tr bgcolor="{@row-color[$i++ % 2]}"><td>{$addr}</td>|;
        $addr ~~ m[
            ( .*? )
            [
                \s+
                (
                | \d+ [ \- | \/ ] \d+
                | <!before 1940 | 1945> \d+ <[ a..z I . / \x20 ]>* \d*
                )
            ]?
            $
        ];
        quietly $table ~= qq|<td>{$0.Str}</td><td>{$1.Str||''}</td></tr>\n|;
    }
    $table ~ '</table>';
}

# generate the page content
sub content {
    qq :to /END/;
    <html>
    <head>
    <title>Rosetta Code - Start a Web Browser</title>
    <meta charset="UTF-8">
    </head>
    <body bgcolor="#d8dcd6">
    <p align="center">
    <font face="Arial, sans-serif" size="5">Split the house number from the street name</font>
    </p>
    <p align="center">
    { genTable }
    </p>
    </body>
    </html>
    END
}

# Use a temporary file name and file handle
my ($fn, $fh) = tempfile :suffix('.html');

# dump the content to the file
$fh.spurt: content;

# use appropriate command for Windows or X11
# other OSs/WMs may need different invocation
my $command = $*DISTRO.is-win ?? "start $fn" !! "xdg-open $fn";

# start the browser
shell $command;

# wait for a bit to give browser time to load before destroying temp file
sleep 5;

```

Output:

Will start the default browser (or open a new tab/window in a running one) and display this table.

| Address | Street | House Number |
| --- | --- | --- |
| Plataanstraat 5 | Plataanstraat | 5 |
| Straat 12 | Straat | 12 |
| Straat 12 II | Straat | 12 II |
| Dr. J. Straat 12 | Dr. J. Straat | 12 |
| Dr. J. Straat 12 a | Dr. J. Straat | 12 a |
| Dr. J. Straat 12-14 | Dr. J. Straat | 12-14 |
| Laan 1940 – 1945 37 | Laan 1940 – 1945 | 37 |
| Plein 1940 2 | Plein 1940 | 2 |
| 1213-laan 11 | 1213-laan | 11 |
| 16 april 1944 Pad 1 | 16 april 1944 Pad | 1 |
| 1e Kruisweg 36 | 1e Kruisweg | 36 |
| Laan 1940-’45 66 | Laan 1940-’45 | 66 |
| Laan ’40-’45 | Laan ’40-’45 |  |
| Langeloërduinen 3 46 | Langeloërduinen | 3 46 |
| Marienwaerdt 2e Dreef 2 | Marienwaerdt 2e Dreef | 2 |
| Provincialeweg N205 1 | Provincialeweg N205 | 1 |
| Rivium 2e Straat 59. | Rivium 2e Straat | 59. |
| Nieuwe gracht 20rd | Nieuwe gracht | 20rd |
| Nieuwe gracht 20rd 2 | Nieuwe gracht | 20rd 2 |
| Nieuwe gracht 20zw /2 | Nieuwe gracht | 20zw /2 |
| Nieuwe gracht 20zw/3 | Nieuwe gracht | 20zw/3 |
| Nieuwe gracht 20 zw/4 | Nieuwe gracht | 20 zw/4 |
| Bahnhofstr. 4 | Bahnhofstr. | 4 |
| Wertstr. 10 | Wertstr. | 10 |
| Lindenhof 1 | Lindenhof | 1 |
| Nordesch 20 | Nordesch | 20 |
| Weilstr. 6 | Weilstr. | 6 |
| Harthauer Weg 2 | Harthauer Weg | 2 |
| Mainaustr. 49 | Mainaustr. | 49 |
| August-Horch-Str. 3 | August-Horch-Str. | 3 |
| Marktplatz 31 | Marktplatz | 31 |
| Schmidener Weg 3 | Schmidener Weg | 3 |
| Karl-Weysser-Str. 6 | Karl-Weysser-Str. | 6 |


[User]
**Background**

This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.

The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two *different* U.S. States (so that all four state names differ from one another).

What states are these?

The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.

A second challenge in the form of a set of fictitious new states was also presented.

Task

Write a program to solve the challenge using both the original list of states and the fictitious list.

Caveats

* case and spacing aren't significant - just letters (harmonize case)
* don't expect the names to be in any order - such as being sorted
* don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)

Comma separated list of state names used in the original puzzle:

```
    "Alabama",  "Alaska",  "Arizona",  "Arkansas",
    "California",  "Colorado",  "Connecticut",  "Delaware",
    "Florida",  "Georgia",  "Hawaii",  "Idaho",  "Illinois",
    "Indiana",  "Iowa",  "Kansas",  "Kentucky",  "Louisiana",
    "Maine",  "Maryland",  "Massachusetts",  "Michigan",
    "Minnesota",  "Mississippi",  "Missouri",  "Montana",
    "Nebraska",  "Nevada",  "New Hampshire",  "New Jersey",
    "New Mexico",  "New York",  "North Carolina",  "North Dakota",
    "Ohio",  "Oklahoma",  "Oregon",  "Pennsylvania",  "Rhode Island",
    "South Carolina",  "South Dakota",  "Tennessee",  "Texas",
    "Utah",  "Vermont",  "Virginia",
    "Washington",  "West Virginia",  "Wisconsin",  "Wyoming"

```

Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):

```
"New Kory",  "Wen Kory",  "York New",  "Kory New",  "New Kory"

```

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
my @states = <
    Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware
    Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky
    Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi
    Missouri Montana Nebraska Nevada New_Hampshire New_Jersey New_Mexico
    New_York North_Carolina North_Dakota Ohio Oklahoma Oregon Pennsylvania
    Rhode_Island South_Carolina South_Dakota Tennessee Texas Utah Vermont
    Virginia Washington West_Virginia Wisconsin Wyoming
>;

say "50 states:";
.say for anastates @states;

say "\n54 states:";
.say for sort anastates @states, < New_Kory Wen_Kory York_New Kory_New New_Kory >;

sub anastates (*@states) {
    my @s = @states.unique».subst('_', ' ');

    my @pairs = gather for ^@s -> $i {
	for $i ^..^ @s -> $j {
	    take [ @s[$i], @s[$j] ];
	}
    }

    my $equivs = hash @pairs.classify: *.lc.comb.sort.join;

    gather for $equivs.values -> @c {
	for ^@c -> $i {
	    for $i ^..^ @c -> $j {
		my $set = set @c[$i].list, @c[$j].list;
		take @c[$i].list.join(', ') ~ ' = ' ~ @c[$j].list.join(', ') if $set == 4;
	    }
	}
    }
}

```

Output:

```
50 states:
North Carolina, South Dakota = North Dakota, South Carolina

54 states:
New Kory, Kory New = Wen Kory, York New
New Kory, Wen Kory = York New, Kory New
New Kory, York New = Wen Kory, Kory New
New York, Kory New = New Kory, Wen Kory
New York, Kory New = New Kory, York New
New York, Kory New = Wen Kory, York New
New York, New Kory = Wen Kory, Kory New
New York, New Kory = Wen Kory, York New
New York, New Kory = York New, Kory New
New York, Wen Kory = New Kory, Kory New
New York, Wen Kory = New Kory, York New
New York, Wen Kory = York New, Kory New
New York, York New = New Kory, Kory New
New York, York New = New Kory, Wen Kory
New York, York New = Wen Kory, Kory New
North Carolina, South Dakota = North Dakota, South Carolina
```


[User]
Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data

x

i
{\displaystyle {\displaystyle x\_{i}}}
 where

i
=
1
,
2
,
…
,
n

{\displaystyle {\displaystyle i=1,2,\ldots ,n\,\!}}
, the mean is

x
¯
≡

1
n

∑

i

x

i
{\displaystyle {\displaystyle {\bar {x}}\equiv {1 \over n}\sum \_{i}x\_{i}}}
, while the stddev is

σ
≡

1
n

∑

i

(

x

i
−

x
¯
)

2
{\displaystyle {\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum \_{i}\left(x\_{i}-{\bar {x}}\right)^{2}}}}}
.

When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.

**Task** Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?

**Extra** Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)

Hint

For a finite population with equal probabilities at all points, one can derive:

:   (
    x
    −

    x
    ¯

    )

    2
    ¯
    =

    x

    2
    ¯
    −

    x
    ¯

    2
    {\displaystyle {\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}}

Or, more verbosely:

:   1
    N

    ∑

    i
    =
    1

    N
    (

    x

    i
    −

    x
    ¯

    )

    2
    =

    1
    N

    (

    ∑

    i
    =
    1

    N

    x

    i

    2
    )
    −

    x
    ¯

    2
    .
    {\displaystyle {\displaystyle {\frac {1}{N}}\sum \_{i=1}^{N}(x\_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum \_{i=1}^{N}x\_{i}^{2}\right)-{\overline {x}}^{2}.}}

See also

* Statistics/Normal distribution

|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| | Tasks for calculating statistical measures | | | --- | --- | |  | | |  |  |  |  |  | | --- | --- | --- | --- | --- | |  | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic  Averages/Arithmetic mean  Averages/Pythagorean means | Averages/Simple moving average |  | | Geometric | Averages/Pythagorean means |  |  | | Harmonic | Averages/Pythagorean means |  |  | | Quadratic | Averages/Root mean square |  |  | | Circular | Averages/Mean angle  Averages/Mean time of day |  |  | | Median | | Averages/Median |  |  | | Mode | | Averages/Mode |  |  | | Standard deviation | | Statistics/Basic |  | Cumulative standard deviation | | | |

---

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
for 100, 1_000, 10_000 -> $N {
    say "size: $N";
    my @data = rand xx $N;
    printf "mean: %f\n", my $mean = $N R/ [+] @data;
    printf "stddev: %f\n", sqrt
    $mean**2 R- $N R/ [+] @data »**» 2;
    printf "%.1f %s\n", .key, '=' x (500 * .value.elems / $N)
        for sort @data.classify: (10 * *).Int / 10;
    say '';
}

```

Output:

```
size: 100
mean: 0.52518699464629726
stddev: 0.28484207464779548
0.0	==============================
0.1	======================================================================
0.2	===================================
0.3	==================================================
0.4	============================================================
0.5	=============================================
0.6	====================
0.7	===========================================================================
0.8	======================================================================
0.9	=============================================

size: 1000
mean: 0.51043974182914975
stddev: 0.29146336553431618
0.0	==============================================
0.1	==================================================
0.2	===========================================
0.3	========================================================
0.4	===================================================
0.5	=======================================
0.6	===========================================================
0.7	====================================================
0.8	==============================================
0.9	========================================================

size: 10000
mean: 0.50371817503544458
stddev: 0.2900716333092252
0.0	===================================================
0.1	=================================================
0.2	=============================================
0.3	====================================================
0.4	==============================================
0.5	====================================================
0.6	================================================
0.7	===================================================
0.8	====================================================
0.9	==================================================
```


[User]
The probability density function (pdf) of the chi-squared (or χ2) distribution as used in statistics is

:   f
    (
    x
    ;

    k
    )
    =

    x

    k
    2
    −
    1

    e

    −

    x
    2

    2

    k
    2
    Γ

    (

    k
    2
    )
    {\displaystyle {\displaystyle f(x;\,k)={\dfrac {x^{{\frac {k}{2}}-1}e^{-{\frac {x}{2}}}}{2^{\frac {k}{2}}\Gamma \left({\frac {k}{2}}\right)}}}}
    , where

    x
    >
    0
    {\textstyle x>0}

Here,

Γ
(
k

/
2
)
{\textstyle \Gamma (k/2)}
 denotes the Gamma\_function.

The use of the gamma function in the equation below reflects the chi-squared distribution's origin as a special case of the gamma
distribution.

In probability theory and statistics, the gamma distribution is a two-parameter family of continuous probability distributions.
The exponential distribution, Erlang distribution, and chi-square distribution are special cases of the gamma distribution.

The probability density function (pdf) of the gamma distribution is given by the formula

:   f
    (
    x
    ;
    k
    ,
    θ
    )
    =

    x

    k
    −
    1

    e

    −
    x

    /
    θ

    θ

    k
    Γ
    (
    k
    )

     for
    x
    >
    0

     and
    k
    ,
    θ
    >
    0.
    {\displaystyle {\displaystyle f(x;k,\theta )={\frac {x^{k-1}e^{-x/\theta }}{\theta ^{k}\Gamma (k)}}\quad {\text{ for }}x>0{\text{ and }}k,\theta >0.}}

where Γ(*k*) is the Gamma\_function, with shape parameter k and a scale parameter θ.

The cumulative probability distribution of the gamma distribution is the area under the curve of the distribution, which indicates
the increasing probability of the x value of a single random point within the gamma distribution being less than or equal to the x value
of the cumulative probability distribution. The gamma cumulative probability distribution function can be calculated as

:   F
    (
    x
    ;
    k
    ,
    θ
    )
    =

    ∫

    0

    x
    f
    (
    u
    ;
    k
    ,
    θ
    )

    d
    u
    =

    γ

    (

    k
    ,

    x
    θ
    )

    Γ
    (
    k
    )
    ,
    {\displaystyle {\displaystyle F(x;k,\theta )=\int \_{0}^{x}f(u;k,\theta )\,du={\frac {\gamma \left(k,{\frac {x}{\theta }}\right)}{\Gamma (k)}},}}

where

γ

(

k
,

x
θ
)
{\displaystyle {\displaystyle \gamma \left(k,{\frac {x}{\theta }}\right)}}
 is the lower incomplete gamma function.

The lower incomplete gamma function can be calculated as

x

s

e

−
x

∑

m
=
0

∞

x

m

Γ
(
s
+
m
+
1
)
{\displaystyle x^{s}\,e^{-x}\sum \_{m=0}^{\infty }{\frac {x^{m}}{\Gamma (s+m+1)}}}

and so, for the chi-squared cumulative probability distribution and substituting chi-square k into s as k/2 and chi-squared x into x as x / 2,

:   F
    (
    x
    ;

    k
    )
    =
    (
    x

    /
    2

    )

    (
    k

    /
    2
    )

    e

    −
    x

    /
    2

    ∑

    m
    =
    0

    ∞

    (
    x

    /
    2

    )

    m

    Γ
    (

    k
    2
    +
    m
    +
    1
    )
    .
    {\displaystyle F(x;\,k)=(x/2)^{(k/2)}\,e^{-x/2}\sum \_{m=0}^{\infty }{\frac {(x/2)^{m}}{\Gamma ({\frac {k}{2}}+m+1)}}.}

Because series formulas may be subject to accumulated errors from rounding in the frequently used region where x and k are under 10 and near one another, you may instead use a mathematics function library, if available for your programming task, to calculate gamma and incomplete gamma.

Task

* Calculate and show the values of the χ2(x; k) for k = 1 through 5 inclusive and x integer from 0 and through 10 inclusive.

* Create a function to calculate the cumulative probability function for the χ2 distribution. This will need to be reasonably accurate (at least 6 digit accuracy) for k = 3.

* Calculate and show the p values of statistical samples which result in a χ2(k = 3) value of 1, 2, 4, 8, 16, and 32. (Statistical *p values* can be calculated for the purpose of this task as approximately 1 - P(x), with P(x) the cumulative probability function at x for χ2.)

:   :   The following is a chart for 4 airports:

Flight Delays

| Airport | On Time | Delayed | Totals |
| --- | --- | --- | --- |
| Dallas/Fort Worth | 77 | 23 | 100 |
| Honolulu | 88 | 12 | 100 |
| LaGuardia | 79 | 21 | 100 |
| Orlando | 81 | 19 | 100 |
| All Totals | 325 | 75 | 400 |
| Expected per 100 | 81.25 | 18.75 | 100 |

:   :   χ2 on a 2D table is calculated as the sum of the squares of the differences from expected divided by the expected numbers for each entry on the table. The k for the chi-squared distribution is to be calculated as df, the degrees of freedom for the table, which is a 2D parameter, (count of airports - 1) \* (count of measures per airport - 1), which here is (4 - 1 )(2 - 1) = 3.

* Calculate the Chi-squared statistic for the above table and find its p value using your function for the cumulative probability for χ2 with k = 3 from the previous task.

Stretch task

* Show how you could make a plot of the curves for the probability distribution function χ2(x; k) for k = 0, 1, 2, and 3.

Related Tasks

* Statistics/Basic
* Statistics/Normal\_distribution

See also

[Chi Squared Test]
[NIST page on the Chi-Square Distribution]

[Assistant]
**Translation of**: Julia

```
# 20221101 Raku programming solution

use Graphics::PLplot;

sub Γ(\z) { # https://rosettacode.org/wiki/Gamma_function#Raku
    constant g = 9;
    z < .5 ?? π/ sin(π * z) / Γ(1 - z)
           !! sqrt(2*π) * (z + g - 1/2)**(z - 1/2) * exp(-(z + g - 1/2)) *
              [+] < 1.000000000000000174663        5716.400188274341379136
                    -14815.30426768413909044       14291.49277657478554025
                    -6348.160217641458813289       1301.608286058321874105
                    -108.1767053514369634679       2.605696505611755827729
                    -0.7423452510201416151527e-2   0.5384136432509564062961e-7
                    -0.4023533141268236372067e-8 > Z* 1, |map 1/(z + *), 0..*
}

sub χ2(\x,\k) {x>0 && k>0 ?? (x**(k/2 - 1)*exp(-x/2)/(2**(k/2)*Γ(k / 2))) !! 0}

sub Γ_cdf(\k,\x) { x**k * exp(-x) * sum( ^101 .map: { x** $_ / Γ(k+$_+1) } ) }

sub cdf_χ2(\x,\k) { (x <= 0 or k <= 0) ?? 0.0 !!  Γ_cdf(k / 2, x / 2) }

say ' 𝒙          χ² ', [~] (1..5)».&{ "𝒌 = $_" ~ ' ' x 13 };
say '-' x my \width = 93;
for 0..10 -> \x {
   say x.fmt('%2d'), [~] (1…5)».&{χ2(x, $_).fmt: "  %-.{((width-2) div 5)-4}f"}
}

say "\nχ² 𝒙     cdf for χ²   P value (df=3)\n", '-' x 36;
for 2 «**« ^6 -> \p {
   my $cdf = cdf_χ2(p, 3).fmt: '%-.10f';
   say p.fmt('%2d'), "     $cdf   ", (1-$cdf).fmt: '%-.10f'
}

my \airport   = [ <77 23>, <88 12>, <79 21>, <81 19> ];
my \expected  = [ <81.25 18.75> xx 4 ];
my \dtotal    = ( (airport »-« expected)»² »/» expected )».List.flat.sum;

say "\nFor the airport data, diff total is ",dtotal,", χ² is ", χ2(dtotal, 3), ", p value ", cdf_χ2(dtotal, 3);

given Graphics::PLplot.new( device => 'png', file-name => 'output.png' ) {
   .begin;
   .pen-width: 3 ;
   .environment: x-range => [-1.0, 10.0], y-range => [-0.1, 0.5], just => 0 ;
   .label: x-axis => '', y-axis => '', title => 'Chi-squared distribution' ;
   for 0..3 -> \𝒌 {
      .color-index0: 1+2*𝒌;
      .line: (0, .1 … 10).map: -> \𝒙 { ( 𝒙, χ2( 𝒙, 𝒌 ) )».Num };
      .text-viewport: side=>'t', disp=>-𝒌-2, pos=>.5, just=>.5, text=>'k = '~𝒌
   } # plplot.sourceforge.net/docbook-manual/plplot-html-5.15.0/plmtex.html
   .end
}

```

Output:

```
 𝒙          χ² 𝒌 = 1             𝒌 = 2             𝒌 = 3             𝒌 = 4             𝒌 = 5
---------------------------------------------------------------------------------------------
 0  0.00000000000000  0.00000000000000  0.00000000000000  0.00000000000000  0.00000000000000
 1  0.24197072451914  0.30326532985632  0.24197072451914  0.15163266492816  0.08065690817305
 2  0.10377687435515  0.18393972058572  0.20755374871030  0.18393972058572  0.13836916580686
 3  0.05139344326792  0.11156508007421  0.15418032980377  0.16734762011132  0.15418032980377
 4  0.02699548325659  0.06766764161831  0.10798193302638  0.13533528323661  0.14397591070183
 5  0.01464498256193  0.04104249931195  0.07322491280963  0.10260624827987  0.12204152134939
 6  0.00810869555494  0.02489353418393  0.04865217332964  0.07468060255180  0.09730434665928
 7  0.00455334292164  0.01509869171116  0.03187340045148  0.05284542098906  0.07437126772012
 8  0.00258337316926  0.00915781944437  0.02066698535409  0.03663127777747  0.05511196094425
 9  0.00147728280398  0.00555449826912  0.01329554523581  0.02499524221105  0.03988663570744
10  0.00085003666025  0.00336897349954  0.00850036660252  0.01684486749771  0.02833455534173

χ² 𝒙     cdf for χ²   P value (df=3)
------------------------------------
 1     0.1987480431   0.8012519569
 2     0.4275932955   0.5724067045
 4     0.7385358701   0.2614641299
 8     0.9539882943   0.0460117057
16     0.9988660157   0.0011339843
32     0.9999994767   0.0000005233

For the airport data, diff total is 4.512821, χ² is 0.08875392598443506, p value 0.7888504263193072
```


[User]
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.

The task

1. Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
2. Mention any native language support for the generation of normally distributed random numbers.

Reference

* You may refer to code in Statistics/Basic if available.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

```
sub normdist ($m, $σ) {
    my $r = sqrt -2 * log rand;
    my $Θ = τ * rand;
    $r * cos($Θ) * $σ + $m;
}

sub MAIN ($size = 100000, $mean = 50, $stddev = 4) {
    my @dataset = normdist($mean,$stddev) xx $size;

    my $m = [+](@dataset) / $size;
    say (:$m);

    my $σ = sqrt [+](@dataset X** 2) / $size - $m**2;
    say (:$σ);

    (my %hash){.round}++ for @dataset;
    my $scale = 180 * $stddev / $size;
    constant @subbar = < ⎸ ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ >;
    for %hash.keys».Int.minmax(+*) -> $i {
        my $x = (%hash{$i} // 0) * $scale;
        my $full = floor $x;
        my $part = 8 * ($x - $full);
        say $i, "\t", '█' x $full, @subbar[$part];
    }
}

```

Output:

```
"m" => 50.006107405837142e0
"σ" => 4.0814435639885254e0
33	⎸
34	⎸
35	⎸
36	▏
37	▎
38	▊
39	█▋
40	███⎸
41	█████▊
42	██████████⎸
43	███████████████▋
44	███████████████████████▏
45	████████████████████████████████▌
46	███████████████████████████████████████████▍
47	██████████████████████████████████████████████████████▏
48	███████████████████████████████████████████████████████████████▏
49	█████████████████████████████████████████████████████████████████████▋
50	███████████████████████████████████████████████████████████████████████▊
51	█████████████████████████████████████████████████████████████████████▌
52	███████████████████████████████████████████████████████████████⎸
53	██████████████████████████████████████████████████████▎
54	███████████████████████████████████████████⎸
55	████████████████████████████████▌
56	███████████████████████▍
57	███████████████▉
58	█████████▉
59	█████▍
60	███▍
61	█▋
62	▊
63	▍
64	▏
65	⎸
66	⎸
67	⎸
```


[User]
Euler Project #284

Task

The 3-digit number 376 in the decimal numbering system is an example of numbers with the special property that its square ends with the same digits: **376\*376 = 141376**. Let's call a number with this property a steady square. Find steady squares under **10.000**

[Assistant]
```
.say for ({$++²}…*).kv.grep( {$^v.ends-with: $^k} )[1..10]

```

Output:

```
(1 1)
(5 25)
(6 36)
(25 625)
(76 5776)
(376 141376)
(625 390625)
(9376 87909376)
(90625 8212890625)
(109376 11963109376)
```


[User]
Steffensen's method is a numerical method to find the roots of functions. It is similar to Newton's method, but, unlike Newton's, does not require derivatives. Like Newton's, however, it is prone towards not finding a solution at all.

In this task we will do a root-finding problem that illustrates both the advantage—that no derivatives are required—and the disadvantage—that the method often gives no answer. We will try to find intersection points of two Bézier curves.

### Steffensen's method

We will be using the variant of Steffensen's method that employs Aitken's extrapolation. Aitken's extrapolation is illustrated by the following ATS function:

```
fun aitken
     (f  : double -> double,   (* function double to double *)
      p0 : double)             (* initial fixed point estimate *)
   : double =
 let
   val p1 = f(p0)
   val p2 = f(p1)
   val p1m0 = p1 - p0
 in
   p0 - (p1m0 * p1m0) / (p2 - (2.0 * p1) + p0)
 end

```

The return value is a function of

p
0
{\displaystyle {\displaystyle p0}}
,

p
1
=
f
(
p
0
)
{\displaystyle {\displaystyle p1=f(p0)}}
, and

p
2
=
f
(
f
(
p
0
)
)
{\displaystyle {\displaystyle p2=f(f(p0))}}
. What one is trying to find is a so-called fixed point of

f
{\displaystyle {\displaystyle f}}
: a value of

p
{\displaystyle {\displaystyle p}}
 such that

f
(
p
)
=
p
{\displaystyle {\displaystyle f(p)=p}}
. Our implementation of Steffensen's method will be to repeat Aitken's extrapolation until either a tolerance is satisfied or too many iterations have been executed:

```
fun steffensen_aitken     (* finds fixed point p such that f(p) = p *)
     (f       : double -> double, (* function double to double *)
      pinit   : double,           (* initial estimate *)
      tol     : double,           (* tolerance *)
      maxiter : int)              (* maximum number of iterations *)
   : Option (double) =     (* return a double, IF tolerance is met *)
 let
   var p0   : double = pinit
   var p    : double = aitken (f, p0)
   var iter : int = 1          (* iteration counter *)
 in
   while (abs (p - p0) > tol andalso iter < maxiter)
     begin
       p0 := p;
       p := aitken (f, p0);
       iter := iter + 1
     end;
   if abs (p - p0) > tol then None () else Some (p)
 end

```

The function `steffensen_aitken` will find a fixed point for us, but how can we use that to find a root? In particular, suppose one wants to find

t
{\displaystyle {\displaystyle t}}
 such that

g
(
t
)
=
0
{\displaystyle {\displaystyle g(t)=0}}
. Then what one can do (and what we will try to do) is find a fixed point

p
{\displaystyle {\displaystyle p}}
 of

f
(
t
)
=
g
(
t
)
+
t
{\displaystyle {\displaystyle f(t)=g(t)+t}}
. In that case,

p
=
f
(
p
)
=
g
(
p
)
+
p
{\displaystyle {\displaystyle p=f(p)=g(p)+p}}
, and therefore

g
(
p
)
=
0
{\displaystyle {\displaystyle g(p)=0}}
.

### The problem we wish to solve

Suppose we have two quadratic planar Bézier curves, with control points

(
−
1
,
0
)
,
(
0
,
10
)
,
(
1
,
0
)
{\displaystyle {\displaystyle (-1,0),(0,10),(1,0)}}
 and

(
2
,
1
)
,
(
−
8
,
2
)
,
(
2
,
3
)
{\displaystyle {\displaystyle (2,1),(-8,2),(2,3)}}
, respectively. These two parabolas are shown in the following figure. As you can see, they intersect at four points.

We want to try to find the points of intersection.

The method we will use is *implicitization*. In this method, one first rewrites one of the curves as an implicit equation in

x
{\displaystyle {\displaystyle x}}
 and

y
{\displaystyle {\displaystyle y}}
. For this we will use the parabola that is convex upwards: it has implicit equation

5

x

2
+
y
−
5
=
0
{\displaystyle {\displaystyle 5x^{2}+y-5=0}}
. Then what one does is plug the parametric equations of the *other* curve into the implicit equation. The resulting equation is

5
(
x
(
t
)

)

2
+
y
(
t
)
−
5
=
0
{\displaystyle {\displaystyle 5(x(t))^{2}+y(t)-5=0}}
, where

t
{\displaystyle {\displaystyle t}}
 is the independent parameter for the curve that is convex *leftwards*. After expansion, this will be a degree-4 equation in

t
{\displaystyle {\displaystyle t}}
. Find its four roots and you have found the points of intersection of the two curves.

That is easier said than done.

There are excellent ways to solve this problem, but we will not be using those. Our purpose, after all, is to illustrate Steffensen's method: both its advantages and its drawbacks. Let us look at an advantage: to use Steffensen's method (which requires only function values, not derivatives), we do not actually have to expand that polynomial in

t
{\displaystyle {\displaystyle t}}
. Instead, we can evaluate

x
(
t
)
{\displaystyle {\displaystyle x(t)}}
 and

y
(
t
)
{\displaystyle {\displaystyle y(t)}}
 and plug the resulting numbers into the implicit equation. What is more, we do not even need to write

x
(
t
)
{\displaystyle {\displaystyle x(t)}}
 and

y
(
t
)
{\displaystyle {\displaystyle y(t)}}
 as polynomials, but instead can evaluate them directly from their control points, using de Casteljau's algorithm:

```
fun de_casteljau
     (c0 : double,         (* control point coordinates (one axis) *)
      c1 : double,
      c2 : double,
      t  : double)             (* the independent parameter *)
   : double =                  (* value of x(t) or y(t) *)
 let
   val s = 1.0 - t
   val c01 = (s * c0) + (t * c1)
   val c12 = (s * c1) + (t * c2)
   val c012 = (s * c01) + (t * c12)
 in
   c012
 end

fun x_convex_left_parabola (t : double) : double =
 de_casteljau (2.0, ~8.0, 2.0, t)

fun y_convex_left_parabola (t : double) : double =
 de_casteljau (1.0, 2.0, 3.0, t)

```

Plugging

x
(
t
)
{\displaystyle {\displaystyle x(t)}}
 and

y
(
t
)
{\displaystyle {\displaystyle y(t)}}
 into the implicit equation, and writing

f
(
t
)
{\displaystyle {\displaystyle f(t)}}
 as the function whose fixed points are to be found:

```
fun implicit_equation (x : double, y : double) : double =
 (5.0 * x * x) + y - 5.0

fun f (t : double) : double = (* find fixed points of this function *)
 let
   val x = x_convex_left_parabola (t)
   val y = y_convex_left_parabola (t)
 in
   implicit_equation (x, y) + t
 end

```

What is left to be done is simple, but tricky: use the `steffensen_aitken` function to find those fixed points. This is where a huge disadvantage of Steffensen's method (shared with Newton's method) will be illustrated. What is likely to happen is that only some of the intersection points will be found. Furthermore, for most of our initial estimates, Steffensen's method will not give us an answer at all.

### The task

Use the methods described above to try to find intersection points of the two parabolas. For initial estimates, use

p
i
n
i
t
=

t

0
=
0.0
,
0.1
,
0.2
,
⋯
,
0.9
,
1.0
{\displaystyle {\displaystyle {\it {pinit}}=t\_{0}=0.0,0.1,0.2,\cdots ,0.9,1.0}}
. Choose reasonable settings for tolerance and maximum iterations. (The ATS example has 0.00000001 and 1000, respectively.) For each initial estimate, if tolerance was not met before maximum iterations was reached, print that there was no answer. On the other hand, if there was an answer, plug the resulting value of

t
{\displaystyle {\displaystyle t}}
 into

x
(
t
)
{\displaystyle {\displaystyle x(t)}}
 and

y
(
t
)
{\displaystyle {\displaystyle y(t)}}
 to find the intersection point

(
x
,
y
)
{\displaystyle {\displaystyle (x,y)}}
. Check that that this answer is correct, by plugging

(
x
,
y
)
{\displaystyle {\displaystyle (x,y)}}
 into the implicit equation. If it is not correct, print that Steffensen's method gave a spurious answer. Otherwise print the value of

(
x
,
y
)
{\displaystyle {\displaystyle (x,y)}}
.

(*The ATS example has purposely been written in a fashion to be readable as if it were pseudocode. You may use it as a reference implementation.*)

### See also

* Bézier curves/Intersections

[Assistant]
**Translation of**: Go

```
# 20230928 Raku programming solution

sub aitken($f, $p0) {
   my $p2   = $f( my $p1 = $f($p0) );
   my $p1m0 = $p1 - $p0;
   return $p0 - $p1m0*$p1m0/($p2-2.0*$p1+$p0);
}

sub steffensenAitken($f, $pinit, $tol, $maxiter) {
   my ($iter, $p) = 1, aitken($f, my $p0 = $pinit);
   while abs($p-$p0) > $tol and $iter < $maxiter {
      $p = aitken($f, $p0 = $p);
      $iter++
   }
   return abs($p-$p0) > $tol ?? NaN !! $p
}

sub deCasteljau($c0, $c1, $c2, $t) {
   my $s = 1.0 - $t;
   return $s*($s*$c0 + $t*$c1) + $t*($s*$c1 + $t*$c2)
}

sub xConvexLeftParabola($t) { return deCasteljau(2.0, -8.0, 2.0, $t) }

sub yConvexRightParabola($t) { return deCasteljau(1.0, 2.0, 3.0, $t) }

sub implicitEquation($x, $y) { return 5.0*$x*$x + $y - 5.0 }

sub f($t) {
   implicitEquation(xConvexLeftParabola($t), yConvexRightParabola($t)) + $t
}

my $t0 = 0.0;
for ^11 {
   print "t0 = {$t0.fmt: '%0.1f'} : ";
   my $t = steffensenAitken(&f, $t0, 0.00000001, 1000);
   if $t.isNaN {
      say "no answer";
   } else {
      my ($x, $y) = xConvexLeftParabola($t), yConvexRightParabola($t);
      if abs(implicitEquation($x, $y)) <= 0.000001 {
         printf "intersection at (%f, %f)\n", $x, $y;
      } else {
         say "spurious solution";
      }
   }
   $t0 += 0.1;
}

```

You may Attempt This Online!


[User]
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:

> 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146

The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.

If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.

**Note:** If you wish to try multiple data sets, you might try this generator.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

Handles negative stems properly.

```
my @data = <
     12 127  28  42  39 113  42  18  44 118  44
     37 113 124  37  48 127  36  29  31 125 139
    131 115 105 132 104 123  35 113 122  42 117
    119  58 109  23 105  63  27  44 105  99  41
    128 121 116 125  32  61  37 127  29 113 121
     58 114 126  53 114  96  25 109   7  31 141
     46  13  27  43 117 116  27   7  68  40  31
    115 124  42 128  52  71 118 117  38  27 106
     33 117 116 111  40 119  47 105  57 122 109
    124 115  43 120  43  27  27  18  28  48 125
    107 114  34 133  45 120  30 127  31 116 146
>».Int.sort;

my Int $stem_unit = 10;
my %h = @data.classify: * div $stem_unit;

my $range = [minmax] %h.keys».Int;
my $stem_format =  "%{$range.min.chars max $range.max.chars}d";

for $range.list -> $stem {
    my $leafs = %h{$stem} // [];
    say $stem.fmt($stem_format), ' | ', ~$leafs.map: * % $stem_unit;
}

```

Output:

```
 0 | 7 7
 1 | 2 3 8 8
 2 | 3 5 7 7 7 7 7 7 8 8 9 9
 3 | 0 1 1 1 1 2 3 4 5 6 7 7 7 8 9
 4 | 0 0 1 2 2 2 2 3 3 3 4 4 4 5 6 7 8 8
 5 | 2 3 7 8 8
 6 | 1 3 8
 7 | 1
 8 |
 9 | 6 9
10 | 4 5 5 5 5 6 7 9 9 9
11 | 1 3 3 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 8 9 9
12 | 0 0 1 1 2 2 3 4 4 4 5 5 5 6 7 7 7 7 8 8
13 | 1 2 3 9
14 | 1 6
```


[User]
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.

1. The first and second members of the sequence are both 1:
   * 1, 1
2. Start by considering the second member of the sequence
3. Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
   * 1, 1, 2
4. Append the considered member of the sequence to the end of the sequence:
   * 1, 1, 2, 1
5. Consider the next member of the series, (the third member i.e. 2)
6. GOTO 3

   * ─── Expanding another loop we get: ───
7. Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
   * 1, 1, 2, 1, 3
8. Append the considered member of the sequence to the end of the sequence:
   * 1, 1, 2, 1, 3, 2
9. Consider the next member of the series, (the fourth member i.e. 1)

The task is to

* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.

Show your output on this page.

Related tasks
:   * Fusc sequence.
    * Continued fraction/Arithmetic

Ref

* Infinite Fractions - Numberphile (Video).
* Trees, Teeth, and Time: The mathematics of clock making.
* A002487 The On-Line Encyclopedia of Integer Sequences.

[Assistant]
(formerly Perl 6)

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

```
constant @Stern-Brocot = 1, 1, { |(@_[$_ - 1] + @_[$_], @_[$_]) given ++$ } ... *;

put @Stern-Brocot[^15];

for flat 1..10, 100 -> $ix {
    say "First occurrence of {$ix.fmt('%3d')} is at index: {(1+@Stern-Brocot.first($ix, :k)).fmt('%4d')}";
}

say so 1 == all map ^1000: { [gcd] @Stern-Brocot[$_, $_ + 1] }

```

Output:

```
1 1 2 1 3 2 3 1 4 3 5 2 5 3 4
First occurrence of   1 is at index:    1
First occurrence of   2 is at index:    3
First occurrence of   3 is at index:    5
First occurrence of   4 is at index:    9
First occurrence of   5 is at index:   11
First occurrence of   6 is at index:   33
First occurrence of   7 is at index:   19
First occurrence of   8 is at index:   21
First occurrence of   9 is at index:   35
First occurrence of  10 is at index:   39
First occurrence of 100 is at index: 1179
True
```


[User]
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number
of cycles (counting fixed points as cycles of length one).

They may be defined directly to be the number of permutations of **n**
elements with **k** disjoint cycles.

Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.

Depending on the application, Stirling numbers of the first kind may be "signed"
or "unsigned". Signed Stirling numbers of the first kind arise when the
polynomial expansion is expressed in terms of falling factorials; unsigned when
expressed in terms of rising factorials. The only substantial difference is that,
for signed Stirling numbers of the first kind, values of S1(n, k) are negative
when n + k is odd.

Stirling numbers of the first kind follow the simple identities:

```
   S1(0, 0) = 1
   S1(n, 0) = 0 if n > 0
   S1(n, k) = 0 if k > n
   S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned
     or
   S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed

```

Task

:   * Write a routine (function, procedure, whatever) to find **Stirling numbers of the first kind**. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.

:   * Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, **S1(n, k)**, up to **S1(12, 12)**. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.

:   * If your language supports large integers, find and show here, on this page, the maximum value of **S1(n, k)** where **n == 100**.

See also

:   * **Wikipedia - Stirling numbers of the first kind**
    * **OEIS:A008275 - Signed Stirling numbers of the first kind**
    * **OEIS:A130534 - Unsigned Stirling numbers of the first kind**

Related Tasks

:   * **Stirling numbers of the second kind**
    * **Lah numbers**

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

```
sub Stirling1 (Int \n, Int \k) {
    return 1 unless n || k;
    return 0 unless n && k;
    state %seen;
    (%seen{"{n - 1}|{k - 1}"} //= Stirling1(n - 1, k - 1)) +
    (n - 1) * (%seen{"{n - 1}|{k}"} //= Stirling1(n - 1, k))
}

my $upto = 12;

my $mx = (1..^$upto).map( { Stirling1($upto, $_) } ).max.chars;

put 'Unsigned Stirling numbers of the first kind: S1(n, k):';
put 'n\k', (0..$upto)».fmt: "%{$mx}d";

for 0..$upto -> $row {
    $row.fmt('%-3d').print;
    put (0..$row).map( { Stirling1($row, $_) } )».fmt: "%{$mx}d";
}

say "\nMaximum value from the S1(100, *) row:";
say (^100).map( { Stirling1 100, $_ } ).max;

```

Output:

```
Unsigned Stirling numbers of the first kind: S1(n, k):
n\k        0         1         2         3         4         5         6         7         8         9        10        11        12
0          1
1          0         1
2          0         1         1
3          0         2         3         1
4          0         6        11         6         1
5          0        24        50        35        10         1
6          0       120       274       225        85        15         1
7          0       720      1764      1624       735       175        21         1
8          0      5040     13068     13132      6769      1960       322        28         1
9          0     40320    109584    118124     67284     22449      4536       546        36         1
10         0    362880   1026576   1172700    723680    269325     63273      9450       870        45         1
11         0   3628800  10628640  12753576   8409500   3416930    902055    157773     18150      1320        55         1
12         0  39916800 120543840 150917976 105258076  45995730  13339535   2637558    357423     32670      1925        66         1

Maximum value from the S1(100, *) row:
19710908747055261109287881673376044669240511161402863823515728791076863288440277983854056472903481625299174865860036734731122707870406148096000000000000000000
```


[User]
Stirling numbers of the second kind, or Stirling partition numbers, are the
number of ways to partition a set of n objects into k non-empty subsets. They are
closely related to Bell numbers, and may be derived from them.

Stirling numbers of the second kind obey the recurrence relation:

```
   S2(n, 0) and S2(0, k) = 0 # for n, k > 0
   S2(n, n) = 1
   S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)

```

Task

:   * Write a routine (function, procedure, whatever) to find **Stirling numbers of the second kind**. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.

:   * Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, **S2(n, k)**, up to **S2(12, 12)**. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).

:   * If your language supports large integers, find and show here, on this page, the maximum value of **S2(n, k)** where **n == 100**.

See also

:   * **Wikipedia - Stirling numbers of the second kind**
    * **OEIS:A008277 - Stirling numbers of the second kind**

Related Tasks

:   * **Stirling numbers of the first kind**
    * **Bell numbers**
    * **Lah numbers**

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

```
sub Stirling2 (Int \n, Int \k) {
    ((1,), { (0, |@^last) »+« (|(@^last »*« @^last.keys), 0) } … *)[n;k]
}

my $upto = 12;

my $mx = (1..^$upto).map( { Stirling2($upto, $_) } ).max.chars;

put 'Stirling numbers of the second kind: S2(n, k):';
put 'n\k', (0..$upto)».fmt: "%{$mx}d";

for 0..$upto -> $row {
    $row.fmt('%-3d').print;
    put (0..$row).map( { Stirling2($row, $_) } )».fmt: "%{$mx}d";
}

say "\nMaximum value from the S2(100, *) row:";
say (^100).map( { Stirling2 100, $_ } ).max;

```

Output:

```
Stirling numbers of the second kind: S2(n, k):
n\k      0       1       2       3       4       5       6       7       8       9      10      11      12
0        1
1        0       1
2        0       1       1
3        0       1       3       1
4        0       1       7       6       1
5        0       1      15      25      10       1
6        0       1      31      90      65      15       1
7        0       1      63     301     350     140      21       1
8        0       1     127     966    1701    1050     266      28       1
9        0       1     255    3025    7770    6951    2646     462      36       1
10       0       1     511    9330   34105   42525   22827    5880     750      45       1
11       0       1    1023   28501  145750  246730  179487   63987   11880    1155      55       1
12       0       1    2047   86526  611501 1379400 1323652  627396  159027   22275    1705      66       1

Maximum value from the S2(100, *) row:
7769730053598745155212806612787584787397878128370115840974992570102386086289805848025074822404843545178960761551674
```


[User]
Task

Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.

Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

The .trans method in Raku improves on Perl 5's tr/// by allowing multi-character translation tables.

We build the full table during .new, which simplifies .encode and .decode.

```
class Straddling_Checkerboard {
    has @!flat_board; # 10x3 stored as 30x1
    has $!plain2code; # full translation table, invertable
    has @!table;      # Printable layout, like Wikipedia entry

    my $numeric_escape = '/';
    my $exclude = /<-[A..Z0..9.]>/; # Omit the escape character

    method display_table { gather { take ~ .list for @!table } };

    method decode ( Str $s --> Str ) {
        $s.trans($!plain2code.antipairs);
    }

    method encode ( Str $s, :$collapse? --> Str ) {
        my $replace = $collapse ?? '' !! '.';
        $s.uc.subst( $exclude, $replace, :g ).trans($!plain2code);
    }

    submethod BUILD ( :$alphabet, :$u where 0..9, :$v where 0..9 ) {
        die if $u == $v;
        die if $alphabet.comb.sort.join ne [~] flat './', 'A'..'Z';

        @!flat_board = $alphabet.uc.comb;
        @!flat_board.splice( $u min $v, 0, Any );
        @!flat_board.splice( $u max $v, 0, Any );

        @!table = [ ' ',|            [ 0 ..  9]                              ],
                  [ ' ',|@!flat_board[ 0 ..  9].map: {.defined ?? $_ !! ' '} ],
                  [ $u, |@!flat_board[10 .. 19]                              ],
                  [ $v, |@!flat_board[20 .. 29]                              ];

        my @order = 0..9; # This may be passed as a param in the future

        my @nums = flat @order,
                   @order.map({ +"$u$_" }),
                   @order.map({ +"$v$_" });

        my %c2p = @nums Z=> @!flat_board;
        %c2p{$_}:delete if %c2p{$_} eqv Any for keys %c2p;
        my %p2c = %c2p.invert;
        %p2c{$_} = %p2c{$numeric_escape} ~ $_ for 0..9;
        $!plain2code = [%p2c.keys] => [%p2c.values];
    }
}

sub MAIN ( :$u = 3, :$v = 7, :$alphabet = 'HOLMESRTABCDFGIJKNPQUVWXYZ./' ) {
    my Straddling_Checkerboard $sc .= new: :$u, :$v, :$alphabet;
    $sc.display_table;

    for 0..1 -> $collapse {
        my $original = 'One night-it was on the twentieth of March, 1888-I was returning';
        my $en = $sc.encode($original, :$collapse);
        my $de = $sc.decode($en);
        say '';
        say "Original: $original";
        say "Encoded:  $en";
        say "Decoded:  $de";
    }
}

```

Output:

```
  0 1 2 3 4 5 6 7 8 9
  H O L   M E S   R T
3 A B C D F G I J K N
7 P Q U V W X Y Z . /

Original: One night-it was on the twentieth of March, 1888-I was returning
Encoded:  13957839363509783697874306781397890578974539936590781347843083207878791798798798783678743067885972839363935
Decoded:  ONE.NIGHT.IT.WAS.ON.THE.TWENTIETH.OF.MARCH..1888.I.WAS.RETURNING

Original: One night-it was on the twentieth of March, 1888-I was returning
Encoded:  139539363509369743061399059745399365901344308320791798798798367430685972839363935
Decoded:  ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING
```


[User]
Definition

**n**   is a   **strange number**   (expressed in base ten)   if every adjacent decimal digit differs from its neighbour by a prime number.

Task

Show all strange numbers for   100   <   **n**   <   500

Stretch goal

Show the number of 10-digit strange numbers that begin with 1

[Assistant]
```
sub infix:<′>(\x,\y) { abs(x - y) ∈ (2, 3, 5, 7) }

my ($low,$high) = 100, 500;
my @strange.push: $_ if so all .comb.rotor(2 => -1).map: { .[0] ′ .[1] } for $low ^..^ $high;

say "Between $low and $high there are {+@strange} strange numbers:\n";
print @strange.batch(20)».fmt("%4d").join: "\n";

```

Output:

```
Between 100 and 500 there are 87 strange numbers:

 130  131  135  136  138  141  142  146  147  149  161  163  164  168  169  181  183  185  186  202
 203  205  207  241  242  246  247  249  250  252  253  257  258  270  272  274  275  279  292  294
 296  297  302  303  305  307  313  314  316  318  350  352  353  357  358  361  363  364  368  369
 381  383  385  386  413  414  416  418  420  424  425  427  429  461  463  464  468  469  470  472
 474  475  479  492  494  496  497
```


[User]
**n**   is a **strange plus number** if the sum of the first two digits is prime and the sum of the second two digits is also prime.

Where     100   <   **n**   <   500

Related task

* Strange\_numbers

[Assistant]
```
unit sub MAIN ($start = 100, $end = 500);
put +$_, " matching numbers from $start to $end:\n", $_ given
  ($start .. $end).hyper(:256batch,:8degree).grep: { all .comb.rotor(2 => -1).map: { .sum.is-prime } };

```

Output:

```
65 matching numbers from 100 to 500:
111 112 114 116 120 121 123 125 129 141 143 147 149 161 165 167 202 203 205 207 211 212 214 216 230 232 234 238 250 252 256 258 292 294 298 302 303 305 307 320 321 323 325 329 341 343 347 349 383 385 389 411 412 414 416 430 432 434 438 470 474 476 492 494 498
```


[User]
Primes   **n,   m,**   and   **p**   are   *strange unique primes*   if   **n,   m,**   and   **p**   are unique and their sum     **n + m + p**     is also prime. Assume **n** < **m** < **p**.

Task
:   * Find all triplets of strange unique primes in which   **n,   m,**   and   **p**   are all less than   **30**.
    * (stretch goal)   Show the count (only) of all the triplets of strange unique primes in which     **n, m,** and **p**    are all less than   **1,000**.

[Assistant]
(formerly Perl 6)

```
# 20210312 Raku programming solution

for 30, 1000 -> \k {
   given (2..k).grep(*.is-prime).combinations(3).grep(*.sum.is-prime) {
      say "Found ", +$_, " strange unique prime triplets up to ", k
   }
}

```

Output:

```
Found 42 strange unique prime triplets up to 30
Found 241580 strange unique prime triplets up to 1000

```


[User]
Description

In linear algebra, the Strassen algorithm   (named after Volker Strassen),   is an algorithm for matrix multiplication.

It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices,   but would be slower than the fastest known algorithms for extremely large matrices.

Task

Write a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.

While practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than   512×512   according to Wikipedia),   for the purposes of this task you should not switch until reaching a size of 1 or 2.

Related task
:   * Matrix multiplication

See also
:   * Wikipedia article

[Assistant]
Special thanks go to the module author, Fernando Santagata, on showing how to deal with a pass-by-value case.

**Translation of**: Julia

```
# 20210126 Raku programming solution

use Math::Libgsl::Constants;
use Math::Libgsl::Matrix;
use Math::Libgsl::BLAS;

my @M;

sub SQM (\in) { # create custom sq matrix from CSV
   die "Not a ■" if (my \L = in.split(/\,/)).sqrt != (my \size = L.sqrt.Int);
   my Math::Libgsl::Matrix \M .= new: size, size;
   for ^size Z L.rotor(size) -> ($i, @row) { M.set-row: $i, @row }
   M
}

sub infix:<⊗>(\x,\y) { # custom multiplication
   my Math::Libgsl::Matrix \z .= new: x.size1, x.size2;
   dgemm(CblasNoTrans, CblasNoTrans, 1, x, y, 1, z);
   z
}

sub infix:<⊕>(\x,\y) { # custom addition
   my Math::Libgsl::Matrix \z .= new: x.size1, x.size2;
   z.copy(x).add(y)
}

sub infix:<⊖>(\x,\y) { # custom subtraction
   my Math::Libgsl::Matrix \z .= new: x.size1, x.size2;
   z.copy(x).sub(y)
}

sub Strassen($A, $B) {

   { return $A ⊗ $B } if (my \n = $A.size1) == 1;

   my Math::Libgsl::Matrix        ($A11,$A12,$A21,$A22,$B11,$B12,$B21,$B22);
   my Math::Libgsl::Matrix        ($P1,$P2,$P3,$P4,$P5,$P6,$P7);
   my Math::Libgsl::Matrix::View  ($mv1,$mv2,$mv3,$mv4,$mv5,$mv6,$mv7,$mv8);
   ($mv1,$mv2,$mv3,$mv4,$mv5,$mv6,$mv7,$mv8)».=new ;

   my \half = n div 2; # dimension of quarter submatrices

   $A11 = $mv1.submatrix($A, 0,0,       half,half); #
   $A12 = $mv2.submatrix($A, 0,half,    half,half); #  create quarter views
   $A21 = $mv3.submatrix($A, half,0,    half,half); #  of operand matrices
   $A22 = $mv4.submatrix($A, half,half, half,half); #
   $B11 = $mv5.submatrix($B, 0,0,       half,half); #       11    12
   $B12 = $mv6.submatrix($B, 0,half,    half,half); #
   $B21 = $mv7.submatrix($B, half,0,    half,half); #       21    22
   $B22 = $mv8.submatrix($B, half,half, half,half); #

   $P1 = Strassen($A12 ⊖ $A22, $B21 ⊕ $B22);
   $P2 = Strassen($A11 ⊕ $A22, $B11 ⊕ $B22);
   $P3 = Strassen($A11 ⊖ $A21, $B11 ⊕ $B12);
   $P4 = Strassen($A11 ⊕ $A12, $B22        );
   $P5 = Strassen($A11,         $B12 ⊖ $B22);
   $P6 = Strassen($A22,         $B21 ⊖ $B11);
   $P7 = Strassen($A21 ⊕ $A22, $B11        );

   my Math::Libgsl::Matrix        $C .= new: n, n;               # Build C from
   my Math::Libgsl::Matrix::View  ($mvC11,$mvC12,$mvC21,$mvC22); #    C11 C12
   ($mvC11,$mvC12,$mvC21,$mvC22)».=new ;                         #    C21 C22

   given $mvC11.submatrix($C, 0,0,       half,half) { .add: (($P1 ⊕ $P2) ⊖ $P4) ⊕ $P6 };
   given $mvC12.submatrix($C, 0,half,    half,half) { .add:   $P4 ⊕ $P5 };
   given $mvC21.submatrix($C, half,0,    half,half) { .add:   $P6 ⊕ $P7 };
   given $mvC22.submatrix($C, half,half, half,half) { .add: (($P2 ⊖ $P3) ⊕ $P5) ⊖ $P7 };

   $C
}

for $=pod[0].contents { next if /^\n$/ ; @M.append: SQM $_ }

for @M.rotor(2) {
   my $product = @_[0] ⊗ @_[1];
#   $product.get-row($_)».round(1).fmt('%2d').put for ^$product.size1;

   say "Regular multiply:";
   $product.get-row($_)».fmt('%.10g').put for ^$product.size1;

   $product = Strassen @_[0], @_[1];

   say "Strassen multiply:";
   $product.get-row($_)».fmt('%.10g').put for ^$product.size1;
}

=begin code
1,2,3,4
5,6,7,8
1,1,1,1,2,4,8,16,3,9,27,81,4,16,64,256
4,-3,4/3,-1/4,-13/3,19/4,-7/3,11/24,3/2,-2,7/6,-1/4,-1/6,1/4,-1/6,1/24
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1
=end code

```

Output:

```
Regular multiply:
19 22
43 50
Strassen multiply:
19 22
43 50
Regular multiply:
1 0 -1.387778781e-16 -2.081668171e-17
1.33226763e-15 1 -4.440892099e-16 -1.110223025e-16
0 0 1 0
7.105427358e-15 0 7.105427358e-15 1
Strassen multiply:
1 5.684341886e-14 -2.664535259e-15 -1.110223025e-16
-1.136868377e-13 1 -7.105427358e-15 2.220446049e-15
0 0 1 5.684341886e-14
0 0 -2.273736754e-13 1
Regular multiply:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Strassen multiply:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
```


[User]
2-stream merge
:   Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
:   Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.

*N*-stream merge
:   The same as above, but reading from    ***N***    sources.
:   Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.

Assume streams are very big. You must not suck them whole in the memory, but read them as streams.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.02

```
sub merge_streams ( @streams ) {
    my @s = @streams.map({ hash( STREAM => $_, HEAD => .get ) })\
                    .grep({ .<HEAD>.defined });

    return gather while @s {
        my $h = @s.min: *.<HEAD>;
        take $h<HEAD>;
        $h<HEAD> := $h<STREAM>.get
            orelse @s .= grep( { $_ !=== $h } );
    }
}

say merge_streams([ @*ARGS».&open ]);

```


[User]
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.

Task

Create a string variable equal to any text value.

Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.

Show the contents of the variable after the append operation.

[Assistant]
(formerly Perl 6)

```
my $str = "foo";
$str ~= "bar";
say $str;

```

Output:

```
foobar
```


[User]
Task

Take the string     **alphaBETA**     and demonstrate how to convert it to:

:   :   :   * upper-case     and
            * lower-case

Use the default encoding of a string literal or plain ASCII if there is no string literal in your language.

Note: In some languages alphabets toLower and toUpper is not reversable.

Show any additional case conversion functions   (e.g. swapping case, capitalizing the first letter, etc.)   that may be included in the library of your language.

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
(formerly Perl 6)
In Raku, case modification is implemented as builtin subroutine or method:

```
my $word = "alpha BETA" ;
say uc $word;         # all uppercase (subroutine call)
say $word.uc;         # all uppercase (method call)
# from now on we use only method calls as examples
say $word.lc;         # all lowercase
say $word.tc;         # first letter titlecase
say $word.tclc;       # first letter titlecase, rest lowercase
say $word.wordcase;   # capitalize each word
```

Output:

```
ALPHA BETA
alpha beta
Alpha BETA
Alpha beta
Alpha Beta
```


[User]
Task

Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison.

The task should demonstrate:

* Comparing two strings for exact equality
* Comparing two strings for inequality (i.e., the inverse of exact equality)
* Comparing two strings to see if one is lexically ordered before than the other
* Comparing two strings to see if one is lexically ordered after than the other
* How to achieve both case sensitive comparisons and case insensitive comparisons within the language
* How the language handles comparison of numeric strings if these are not treated lexically
* Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system.

For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.

Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance.

In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type;   instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can,   and the operator simply fails if the arguments cannot be viewed somehow as strings.   A language may have one or both of these kinds of operators;   see the Raku entry for an example of a language with both kinds of operators.

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)

Raku uses strong typing dynamically (and gradual typing statically), but normal string and numeric comparisons are coercive. (You may use generic comparison operators if you want polymorphic comparison—but usually you don't. :)

String comparisons never do case folding because that's a very complicated subject in the modern world of Unicode. (You can explicitly apply an appropriate case-folding function to the arguments before doing the comparison, or for "equality" testing you can do matching with a case-insensitive regex, assuming Unicode's language-neutral case-folding rules are okay.)

```
sub compare($a,$b) {
    my $A = "{$a.WHAT.^name} '$a'";
    my $B = "{$b.WHAT.^name} '$b'";

    if $a eq $b { say "$A and $B are lexically equal" }
    if $a ne $b { say "$A and $B are not lexically equal" }

    if $a gt $b { say "$A is lexically after $B" }
    if $a lt $b { say "$A is lexically before than $B" }

    if $a ge $b { say "$A is not lexically before $B" }
    if $a le $b { say "$A is not lexically after $B" }

    if $a === $b { say "$A and $B are identical objects" }
    if $a !=== $b { say "$A and $B are not identical objects" }

    if $a eqv $b { say "$A and $B are generically equal" }
    if $a !eqv $b { say "$A and $B are not generically equal" }

    if $a before $b { say "$A is generically after $B" }
    if $a after $b { say "$A is generically before $B" }

    if $a !after $b { say "$A is not generically before $B" }
    if $a !before $b { say "$A is not generically after $B" }

    say "The lexical relationship of $A and $B is { $a leg $b }" if $a ~~ Stringy;
    say "The generic relationship of $A and $B is { $a cmp $b }";
    say "The numeric relationship of $A and $B is { $a <=> $b }" if $a ~~ Numeric;
    say '';
}

compare 'YUP', 'YUP';
compare 'BALL', 'BELL';
compare 24, 123;
compare 5.1, 5;
compare 5.1e0, 5 + 1/10;

```

Output:

```
Str 'YUP' and Str 'YUP' are lexically equal
Str 'YUP' is not lexically before Str 'YUP'
Str 'YUP' is not lexically after Str 'YUP'
Str 'YUP' and Str 'YUP' are identical objects
Str 'YUP' and Str 'YUP' are generically equal
Str 'YUP' is not generically before Str 'YUP'
Str 'YUP' is not generically after Str 'YUP'
The lexical relationship of Str 'YUP' and Str 'YUP' is Same
The generic relationship of Str 'YUP' and Str 'YUP' is Same

Str 'BALL' and Str 'BELL' are not lexically equal
Str 'BALL' is lexically before than Str 'BELL'
Str 'BALL' is not lexically after Str 'BELL'
Str 'BALL' and Str 'BELL' are not identical objects
Str 'BALL' and Str 'BELL' are not generically equal
Str 'BALL' is generically after Str 'BELL'
Str 'BALL' is not generically before Str 'BELL'
The lexical relationship of Str 'BALL' and Str 'BELL' is Increase
The generic relationship of Str 'BALL' and Str 'BELL' is Increase

Int '24' and Int '123' are not lexically equal
Int '24' is lexically after Int '123'
Int '24' is not lexically before Int '123'
Int '24' and Int '123' are not identical objects
Int '24' and Int '123' are not generically equal
Int '24' is generically after Int '123'
Int '24' is not generically before Int '123'
The generic relationship of Int '24' and Int '123' is Increase
The numeric relationship of Int '24' and Int '123' is Increase

Rat '5.1' and Int '5' are not lexically equal
Rat '5.1' is lexically after Int '5'
Rat '5.1' is not lexically before Int '5'
Rat '5.1' and Int '5' are not identical objects
Rat '5.1' and Int '5' are not generically equal
Rat '5.1' is generically before Int '5'
Rat '5.1' is not generically after Int '5'
The generic relationship of Rat '5.1' and Int '5' is Decrease
The numeric relationship of Rat '5.1' and Int '5' is Decrease

Num '5.1' and Rat '5.1' are lexically equal
Num '5.1' is not lexically before Rat '5.1'
Num '5.1' is not lexically after Rat '5.1'
Num '5.1' and Rat '5.1' are not identical objects
Num '5.1' and Rat '5.1' are not generically equal
Num '5.1' is not generically before Rat '5.1'
Num '5.1' is not generically after Rat '5.1'
The generic relationship of Num '5.1' and Rat '5.1' is Same
The numeric relationship of Num '5.1' and Rat '5.1' is Same
```

### Unicode normalization by default

Be aware that Raku applies normalization (Unicode NFC form (Normalization Form Canonical)) by default to all input and output except for file names See docs. Raku follows the Unicode spec. Raku follows **all** of the Unicode spec, including parts that some people don't like. There are some graphemes for which the Unicode consortium has specified that the NFC form is a different (though usually visually identical) grapheme. Referred to in Unicode standard annex #15 as **Canonical Equivalence**. Raku adheres to that spec.

One that people seem to get hung up on is the Kelvin symbol "K" getting automatically converted to ASCII uppercase "K".

```
say "\c[KELVIN SIGN]".uniname;
# => LATIN CAPITAL LETTER K

my $kelvin = "\c[KELVIN SIGN]";
my $k = "\c[LATIN CAPITAL LETTER K]";
say ($kelvin eq $k); # True, lexically equal
say ($kelvin eqv $k); # True, generically equal
say ($kelvin === $k); # True, identical objects

```

In most programming language the previous two objects wouldn't be equivalent, but since Raku follows the Unicode specification, and normalization is applied automatically, they show up as equivalent.

It's officially identified as a possible trap for string handling. See docs.


[User]
Task

Create a string variable equal to any text value.

Create another string variable whose value is the original variable concatenated with another string literal.

To illustrate the operation, show the content of the variables.

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 #22 "Thousand Oaks"

```
my $s = 'hello';
say $s ~ ' literal';
my $s1 = $s ~ ' literal';
say $s1;

# or, using mutating concatenation:

$s ~= ' literal';
say $s;
```

Note also that most concatenation in Raku is done implicitly via interpolation.


[User]
Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.

:   For example, given an original string of `"Mary had a X lamb."`, a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string `"Mary had a big lamb"`.

:   (Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").

Task

1. Use your languages inbuilt string interpolation abilities to interpolate a string missing the text `"little"` which is held in a variable, to produce the output string `"Mary had a little lamb"`.
2. If possible, give links to further documentation on your languages string interpolation features.

Note: The task is not to create a string interpolation routine, but to show a language's built-in capability.

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)

```
my $extra = "little";
say "Mary had a $extra lamb";           # variable interpolation
say "Mary had a { $extra } lamb";       # expression interpolation
printf "Mary had a %s lamb.\n", $extra; # standard printf
say $extra.fmt("Mary had a %s lamb");   # inside-out printf
my @lambs = <Jimmy Bobby Tommy>;
say Q :array { $$$ The lambs are called @lambs[]\\\.} # only @-sigiled containers are interpolated

```