[User]
Define and give an example of the Amb operator.

The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").

The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.

Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.

Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.

For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x \* y == 8) which unless x and y add to four.

A pseudo-code program which satisfies this constraint might look like:

```
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
```

The output is `2 4` because `Amb(1, 2, 3)` correctly chooses the future in which `x` has value `2`, `Amb(7, 6, 4, 5)` chooses `4` and consequently `Amb(x * y = 8)` produces a success.

Alternatively, failure could be represented using strictly `Amb()`:

```
unless x * y = 8 do Amb()
```

Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:

```
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
```

where `Ambassert` behaves like `Amb()` if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.

The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:

1. `"the" "that" "a"`
2. `"frog" "elephant" "thing"`
3. `"walked" "treaded" "grows"`
4. `"slowly" "quickly"`

The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.

The only successful sentence is `"that thing grows slowly"`; other combinations do not satisfy the constraint and thus fail.

The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.

[Assistant]
(formerly Perl 6)

### Using Junctions

Junctions are a construct that behave similarly to the wanted Amb operator. The only difference is, that they don't preserve the state that was True inside any control structure (like an if).

There is currently a trick, how you only get the "true" values from a Junction for any test: return from a subroutine. Because of DeMorgans Law, you'll have to switch and and or, since you want to return on falseness. Just look at 'all' in combination with the sub(){return unless test} as the amb operator.

```
#| an array of four words, that have more possible values.
#| Normally we would want `any' to signify we want any of the values, but well negate later and thus we need `all'
my @a =
(all «the that a»),
(all «frog elephant thing»),
(all «walked treaded grows»),
(all «slowly quickly»);

sub test (Str $l, Str $r) {
    $l.ends-with($r.substr(0,1))
}

(sub ($w1, $w2, $w3, $w4){
  # return if the values are false
  return unless [and] test($w1, $w2), test($w2, $w3),test($w3, $w4);
  # say the results. If there is one more Container layer around them this doesn't work, this is why we need the arguments here.
  say "$w1 $w2 $w3 $w4"
})(|@a); # supply the array as argumetns

```

### Using the Regex Engine

By using a reduction metaoperator to calculate all possible combinations, we can Amb any number of sets with no arbitrary limits. A simple regex pattern can find out if a certain combination is correct or not.

```
# The Task #
my @firstSet  = «the that a»;
my @secondSet = «frog elephant thing»;
my @thirdSet  = «walked treaded grows»;
my @fourthSet = «slowly quickly»;

.say for doAmb [@firstSet, @secondSet, @thirdSet, @fourthSet];

sub doAmb( @lol ) {	# Takes out the correct sentences.
	my @sentences = map *.join(" "), [X] @lol;
	grep &isAmb, @sentences;
}

sub isAmb( $sentence ) {	# Checks `$sentence` for correctness.
	$sentence !~~ / (.) " " (.)	<!{$0 eq $1}> /	# <https://docs.raku.org/language/regexes#Regex_boolean_condition_check>
}

```


[User]
Two integers

N
{\displaystyle {\displaystyle N}}
 and

M
{\displaystyle {\displaystyle M}}
 are said to be amicable pairs if

N
≠
M
{\displaystyle {\displaystyle N\neq M}}
 and the sum of the proper divisors of

N
{\displaystyle {\displaystyle N}}
 (

s
u
m
(

p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}}
)

=
M
{\displaystyle {\displaystyle =M}}
 as well as

s
u
m
(

p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}}
.

Example

**1184** and **1210** are an amicable pair, with proper divisors:

* 1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and
* 1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively.

Task

Calculate and show here the Amicable pairs below 20,000; (there are eight).

Related tasks

* Proper divisors
* Abundant, deficient and perfect number classifications
* Aliquot sequence classifications and its amicable *classification*.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03.1

```
sub propdivsum (\x) {
    my @l = 1 if x > 1;
    (2 .. x.sqrt.floor).map: -> \d {
        unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
    }
    sum @l
}

(1..20000).race.map: -> $i {
    my $j = propdivsum($i);
    say "$i $j" if $j > $i and $i == propdivsum($j);
}

```

Output:

```
220 284
1184 1210
2620 2924
5020 5564
6232 6368
10744 10856
12285 14595
17296 18416
```


[User]
An anadrome is similar to a palindrome except, rather than spelling the *same* word or phrase when reversed, it spells a *different* word or phrase. An anadrome is a special case of an anagram.

*Anadrome is a portmanteau of the words anagram and palindrome.*

For instance, **regal** and **lager** are anadromes.

Task

Using the words.txt file from https://github.com/dwyl/english-words, find and display all of the anadrome pairs with more than 6 characters.

Each word pair should only show up one time in the list.

Alternate download location.

[Assistant]
```
my @words = 'words.txt'.IO.slurp.words.grep: *.chars > 6;

my %words = @words.pairs.invert;

put join "\n", @words.map: { %words{$_}:delete and sprintf "%10s ↔ %s", $_, .flip if ($_ ne .flip) && %words{.flip} }

```

Output:

```
   amaroid ↔ diorama
   degener ↔ reneged
   deifier ↔ reified
   deliver ↔ reviled
   dessert ↔ tressed
  desserts ↔ stressed
   deviler ↔ relived
  dioramas ↔ samaroid
   gateman ↔ nametag
   leveler ↔ relevel
   pat-pat ↔ tap-tap
  redrawer ↔ rewarder
   reknits ↔ stinker
   relever ↔ reveler
   reliver ↔ reviler
   revotes ↔ setover
   sallets ↔ stellas
```


[User]
There are already other tasks relating to *finding* **existing** anagrams. This one is about **creating** them.

Write a (set of) routine(s) that, when given a word list to work from, and word or phrase as a seed, generates anagrams of that word or phrase. Feel free to ignore letter case, white-space, punctuation and symbols. Probably best to avoid numerics too, but feel free to include them if that floats your boat.

It is not necessary to (only) generate anagrams that make sense. That is a hard problem, much more difficult than can realistically be done in a small program; though again, if you feel the need, you are invited to amaze your peers.

In general, try to form phrases made up of longer words. Feel free to manually reorder output words or add punctuation and/or case changes to get a better meaning.

Task

Write an anagram generator program.

Use a publicly and freely available word file as its word list.

:   unixdict.txt from http://wiki.puzzlers.org is a popular, though somewhat limited choice.
:   A much larger word list: words\_alpha.txt file from https://github.com/dwyl/english-words. May be better as far as coverage but may return unreasonably large results.

Use your program to generate anagrams of some words / phrases / names of your choice. No need to show **all** the output. It is likely to be very large. Just pick out one or two of the best results and show the seed word/phrase and anagram.

For example, show the seed and one or two of the best anagrams:

:   **Purefox -> Fur expo**
:   **Petelomax -> Metal expo**

*.oO(hmmm. Seem to be detecting something of a trend here...)*

[Assistant]
Using the unixdict.txt word file by default.

```
unit sub MAIN ($in is copy = '', :$dict = 'unixdict.txt');

say 'Enter a word or phrase to be anagramed. (Loading dictionary)' unless $in.chars;

# Load the words into a word / Bag hash
my %words = $dict.IO.slurp.lc.words.race.map: { .comb(/\w/).join => .comb(/\w/).Bag };

# Declare some globals
my ($phrase, $count, $bag);

loop {
    ($phrase, $count, $bag) = get-phrase;
    find-anagram Hash.new: %words.grep: { .value ⊆ $bag };
}

sub get-phrase {
    my $prompt = $in.chars ?? $in !! prompt "\nword or phrase? (press Enter to quit) ";
    $in = '';
    exit unless $prompt;
    $prompt,
    +$prompt.comb(/\w/),
    $prompt.lc.comb(/\w/).Bag;
}

sub find-anagram (%subset, $phrase is copy = '', $last = Inf) {
    my $remain = $bag ∖ $phrase.comb(/\w/).Bag;        # Find the remaining letters
    my %filtered = %subset.grep: { .value ⊆ $remain }; # Find words using the remaining letters
    my $sofar = +$phrase.comb(/\w/);                   # Get the count of the letters used so far
    for %filtered.sort: { -.key.chars, ~.key } {       # Sort by length then alphabetically then iterate
        my $maybe = +.key.comb(/\w/);                  # Get the letter count of the maybe addition
        next if $maybe > $last;                        # Next if it is longer than last - only consider descending length words
        next if $maybe == 1 and $last == 1;            # Only allow one one character word
        next if $count - $sofar - $maybe > $maybe;     # Try to balance word lengths
        if $sofar + $maybe == $count {                 # It's an anagram
            say $phrase ~ ' ' ~ .key and next;         # Display it and move on
        } else {                                       # Not yet a full anagram, recurse
            find-anagram %filtered, $phrase ~ ' ' ~ .key, $maybe;
        }
    }
}

```

Truncated to only show the best few as subjectively determined by me:

*Punctuation, capitalization and (in some cases) word order manually massaged.*

```
Enter a word or phrase to be anagramed. (Loading dictionary)

word or phrase? (press Enter to quit) Rosettacode
doctor tease

word or phrase? (press Enter to quit) thundergnat
dragnet hunt
Gent? Nah, turd.

word or phrase? (press Enter to quit) Clint Eastwood
downcast eliot
I contest waldo
nose to wildcat
```


[User]
When two or more words are composed of the same characters, but in a different order, they are called anagrams.

Task

Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,

find the sets of words that share the same characters that contain the most words in them.

Related tasks

* |  |  |  |  |  |  |
  | --- | --- | --- | --- | --- | --- |
  | | Word plays | | | --- | --- | |  | | Ordered words  Palindrome detection  Semordnilap  Anagrams  Anagrams/Deranged anagrams | | |

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 2016.08

```
my @anagrams = 'unixdict.txt'.IO.words.classify(*.comb.sort.join).values;

my $max = @anagrams».elems.max;

.put for @anagrams.grep(*.elems == $max);
```

Output:

```
caret carte cater crate trace
angel angle galen glean lange
alger glare lager large regal
elan lane lean lena neal
evil levi live veil vile
abel able bale bela elba

```

Just for the fun of it, here's a one-liner that uses no temporaries. Since it would be rather long, we've oriented it vertically:

**Works with**: Rakudo version 2016.08

```
.put for                         # print each element of the array made this way:
    'unixdict.txt'.IO.words      # load words from file
    .classify(*.comb.sort.join)  # group by common anagram
    .classify(*.value.elems)     # group by number of anagrams in a group
    .max(*.key).value            # get the group with highest number of anagrams
    .map(*.value)                # get all groups of anagrams in the group just selected
```


[User]
Two or more words are said to be anagrams if they have the same characters, but in a different order.

By analogy with derangements we define a *deranged anagram* as two words with the same characters, but in which the same character does *not* appear in the same position in both words.

Task

Use the word list at unixdict to find and display the longest deranged anagram.

Related

* Permutations/Derangements
* Best shuffle

* |  |  |  |  |  |  |
  | --- | --- | --- | --- | --- | --- |
  | | Word plays | | | --- | --- | |  | | Ordered words  Palindrome detection  Semordnilap  Anagrams  Anagrams/Deranged anagrams | | |

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 2016.08

```
my @anagrams = 'unixdict.txt'.IO.words
    .map(*.comb.cache)             # explode words into lists of characters
    .classify(*.sort.join).values  # group words with the same characters
    .grep(* > 1)                   # only take groups with more than one word
    .sort(-*[0])                   # sort by length of the first word
;

for @anagrams -> @group {
    for @group.combinations(2) -> [@a, @b] {
        if none @a Zeq @b {
            say "{@a.join}   {@b.join}";
            exit;
        }
    }
}

```

Output:

```
excitation   intoxicate
```


[User]
Anaprimes are prime numbers that are anagrams of each other, i.e. they use exactly the same digits with the same frequency but in a different order.

Anaprimes are *very* common. To illustrate this, we will investigate the sizes of the equivalence classes defined by the "is an anagram of" relation.

For example, the equivalence class of 149 has four anaprimes: {149, 419, 491, 941}. It turns out that there is no larger equivalence class of 3-digit anaprimes.

Task

* Find prime numbers that are anagrams of each other.
* Find the **largest** anagram group of prime numbers and display the count, and minimum and maximum members for prime numbers:
  + up to three digits long (before 1,000)
  + up to four digits long (before 10,000)
  + up to five digits long (before 100,000)
  + up to six digits long (before 1,000,000)

Stretch

* Find the **largest** anagram group and display the count, and smallest and largest members for prime numbers:
  + up to seven digits long (before 10,000,000)
  + up to eight digits long (before 100,000,000)
  + up to nine digits long (before 1,000,000,000)
  + ???!

Related tasks

* Circular primes * Ormiston pairs * Emirp primes

[Assistant]
9 digit is slooow. I didn't have the patience for 10.

```
use Lingua::EN::Numbers;
use Math::Primesieve;
use List::Allmax;

my $p = Math::Primesieve.new;

for 3 .. 9 {
    my @largest = $p.primes(10**($_-1), 10**$_).classify(*.comb.sort.join).List.&all-max(:by(+*.value)).values;

    put "\nLargest group of anaprimes before {cardinal 10 ** $_}: {+@largest[0].value} members.";
    put 'First: ', ' Last: ' Z~ .value[0, *-1] for sort @largest;
}

```

Output:

```
Largest group of anaprimes before one thousand: 4 members.
First: 149  Last: 941
First: 179  Last: 971
First: 379  Last: 937

Largest group of anaprimes before ten thousand: 11 members.
First: 1237  Last: 7321
First: 1279  Last: 9721

Largest group of anaprimes before one hundred thousand: 39 members.
First: 13789  Last: 98731

Largest group of anaprimes before one million: 148 members.
First: 123479  Last: 974213

Largest group of anaprimes before ten million: 731 members.
First: 1235789  Last: 9875321

Largest group of anaprimes before one hundred million: 4,333 members.
First: 12345769  Last: 97654321

Largest group of anaprimes before one billion: 26,519 members.
First: 102345697  Last: 976542103
```


[User]
Finding the angle between two bearings is often confusing.[1]

Task

Find the angle which is the result of the subtraction **b2 - b1**, where **b1** and **b2** are the bearings.

Input bearings are expressed in the range   **-180**   to   **+180**   degrees.

The  result  is also expressed in the range   **-180**   to   **+180**   degrees.

Compute the angle for the following pairs:

* 20 degrees (**b1**) and 45 degrees (**b2**)
* -45 and 45
* -85 and 90
* -95 and 90
* -45 and 125
* -45 and 145
* 29.4803 and -88.6381
* -78.3251 and -159.036

Optional extra

Allow the input bearings to be any (finite) value.

Test cases

* -70099.74233810938 and 29840.67437876723
* -165313.6666297357 and 33693.9894517456
* 1174.8380510598456 and -154146.66490124757
* 60175.77306795546 and 42213.07192354373

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.11

```
sub infix:<∠> (Real $b1, Real $b2) {
   (my $b = ($b2 - $b1 + 720) % 360) > 180 ?? $b - 360 !! $b;
}

for 20, 45,
   -45, 45,
   -85, 90,
   -95, 90,
   -45, 125,
   -45, 145,
   29.4803, -88.6381,
   -78.3251, -159.036,
   -70099.74233810938, 29840.67437876723,
   -165313.6666297357, 33693.9894517456,
   1174.8380510598456, -154146.66490124757,
   60175.77306795546, 42213.07192354373

  -> $b1, $b2 { printf "%10.2f %10.2f = %8.2f\n", $b1, $b2, $b1 ∠ $b2 }

```

Output:

```
     20.00      45.00 =    25.00
    -45.00      45.00 =    90.00
    -85.00      90.00 =   175.00
    -95.00      90.00 =  -175.00
    -45.00     125.00 =   170.00
    -45.00     145.00 =  -170.00
     29.48     -88.64 =  -118.12
    -78.33    -159.04 =   -80.71
 -70099.74   29840.67 =  -139.58
-165313.67   33693.99 =   -72.34
   1174.84 -154146.66 =  -161.50
  60175.77   42213.07 =    37.30
```


[User]
This task is about the normalization and/or conversion of (geometric) angles using
some common scales.

The angular scales that will be used in this task are:

:   :   * degree
        * gradian
        * mil
        * radian

Definitions

The angular scales used or referenced here:

:   :   * **turn**   is a full turn or 360 degrees, also shown as 360º
        * **degree**   is   **1/360**   of a turn
        * **gradian**   is   **1/400**   of a turn
        * **mil**   is   **1/6400**   of a turn
        * **radian**   is   **1/2

          π
          {\displaystyle {\displaystyle \pi }}**   of a turn   (or   **0.5/π
          {\displaystyle {\displaystyle \pi }}**   of a turn)

Or, to put it another way,   for a full circle:

:   :   * there are   **360**   degrees
        * there are   **400**   gradians
        * there are   **6,400**   mils
        * there are   **2

          π
          {\displaystyle {\displaystyle \pi }}**   radians   (roughly equal to **6.283+**)

A   **mil**   is approximately equal to a   *milliradian*   (which is   **1/1000**   of a radian).

There is another definition of a   **mil**   which
is   **1/1000**   of a radian   ─── this
definition won't be used in this Rosetta Code task.

**Turns**   are sometimes known or shown as:

:   :   :   * turn(s)
            * 360 degrees
            * unit circle
            * a (full) circle

**Degrees**   are sometimes known or shown as:

:   :   :   * degree(s)
            * deg
            * º       (a symbol)
            * °       (another symbol)

**Gradians**   are sometimes known or shown as:

:   :   :   * gradian(s)
            * grad(s)
            * grade(s)
            * gon(s)
            * metric degree(s)
            * (Note that   **centigrade**   was used for 1/100th of a grade, see the note below.)

**Mils**   are sometimes known or shown as:

:   :   :   * mil(s)
            * NATO mil(s)

**Radians**   are sometimes known or shown as:

:   :   :   * radian(s)
            * rad(s)

Notes

In continental Europe, the French term   **centigrade**   was used
for   **1/100**   of a grad (grade);   this was
one reason for the adoption of the term   **Celsius**   to
replace   **centigrade**   as the name of a temperature scale.

Gradians were commonly used in civil engineering.

Mils were normally used for artillery   (elevations of the gun barrel for ranging).

Positive and negative angles

Although the definition of the measurement of an angle doesn't support the
concept of a negative angle,   it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference.   It is this reason that
negative angles will keep their sign and not be normalized to positive angles.

Normalization

Normalization   (for this Rosetta Code task)   will keep the same
sign,   but it will reduce the magnitude to less than a full circle;   in
other words, less than 360º.

Normalization   shouldn't   change   **-45º**   to   **315º**,

An angle of   **0º**,   **+0º**,   **0.000000**,   or   **-0º**   should be
shown as   **0º**.

Task
:   :   * write a function (or equivalent) to do the normalization for each scale

        :   :   :   * Suggested names:
                    * **d2d**,   **g2g**,   **m2m**,   and  **r2r**

        * write a function (or equivalent) to convert one scale to another

        :   :   :   * Suggested names for comparison of different computer language function names:
                    * **d2g**,   **d2m**,   and   **d2r**   for degrees
                    * **g2d**,   **g2m**,   and   **g2r**   for gradians
                    * **m2d**,   **m2g**,   and   **m2r**   for mils
                    * **r2d**,   **r2g**,   and   **r2m**   for radians

        * normalize all angles used   (except for the "original" or "base" angle)
        * show the angles in every scale and convert them to all other scales
        * show all output here on this page

For the (above) conversions,   use these dozen numbers   (in the order shown):

:   * **-2   -1   0   1   2   6.2831853   16   57.2957795   359   399   6399   1000000**

[Assistant]
(formerly Perl 6)

```
my @units =
    { code => 'd', name => 'degrees' , number =>  360 },
    { code => 'g', name => 'gradians', number =>  400 },
    { code => 'm', name => 'mills'   , number => 6400 },
    { code => 'r', name => 'radians' , number =>  tau },
;

my Code %cvt = (@units X @units).map: -> ($a, $b) {
    "{$a.<code>}2{$b.<code>}" => sub ($angle) {
        my $norm = $angle % $a.<number>
                 - ( $a.<number> if $angle < 0 );
        $norm * $b.<number> / $a.<number>
    }
}

say '     Angle Unit     ', @units».<name>».tc.fmt('%11s');

for -2, -1, 0, 1, 2, tau, 16, 360/tau, 360-1, 400-1, 6400-1, 1_000_000 -> $angle {
    say '';
    for @units -> $from {
        my @sub_keys = @units.map: { "{$from.<code>}2{.<code>}" };

        my @results = %cvt{@sub_keys}».($angle);

        say join ' ', $angle      .fmt('%10g'),
                      $from.<name>.fmt('%-8s'),
                      @results    .fmt('%11g');
    }
}

```

Output:

```
     Angle Unit         Degrees    Gradians       Mills     Radians

        -2 degrees           -2    -2.22222    -35.5556  -0.0349066
        -2 gradians        -1.8          -2         -32  -0.0314159
        -2 mills        -0.1125      -0.125          -2  -0.0019635
        -2 radians     -114.592    -127.324    -2037.18          -2

        -1 degrees           -1    -1.11111    -17.7778  -0.0174533
        -1 gradians        -0.9          -1         -16   -0.015708
        -1 mills       -0.05625     -0.0625          -1 -0.000981748
        -1 radians     -57.2958     -63.662    -1018.59          -1

         0 degrees            0           0           0           0
         0 gradians           0           0           0           0
         0 mills              0           0           0           0
         0 radians            0           0           0           0

         1 degrees            1     1.11111     17.7778   0.0174533
         1 gradians         0.9           1          16    0.015708
         1 mills        0.05625      0.0625           1 0.000981748
         1 radians      57.2958      63.662     1018.59           1

         2 degrees            2     2.22222     35.5556   0.0349066
         2 gradians         1.8           2          32   0.0314159
         2 mills         0.1125       0.125           2   0.0019635
         2 radians      114.592     127.324     2037.18           2

   6.28319 degrees      6.28319     6.98132     111.701    0.109662
   6.28319 gradians     5.65487     6.28319     100.531    0.098696
   6.28319 mills       0.353429    0.392699     6.28319   0.0061685
   6.28319 radians            0           0           0           0

        16 degrees           16     17.7778     284.444    0.279253
        16 gradians        14.4          16         256    0.251327
        16 mills            0.9           1          16    0.015708
        16 radians      196.732     218.592     3497.47     3.43363

   57.2958 degrees      57.2958      63.662     1018.59           1
   57.2958 gradians     51.5662     57.2958     916.732         0.9
   57.2958 mills        3.22289     3.58099     57.2958     0.05625
   57.2958 radians      42.8064     47.5626     761.002    0.747112

       359 degrees          359     398.889     6382.22     6.26573
       359 gradians       323.1         359        5744     5.63916
       359 mills        20.1938     22.4375         359    0.352447
       359 radians      49.1848     54.6498     874.397    0.858437

       399 degrees           39     43.3333     693.333    0.680678
       399 gradians       359.1         399        6384     6.26748
       399 mills        22.4438     24.9375         399    0.391717
       399 radians      181.016     201.129     3218.06     3.15933

      6399 degrees          279         310        4960     4.86947
      6399 gradians       359.1         399        6384     6.26748
      6399 mills        359.944     399.938        6399      6.2822
      6399 radians      155.693     172.992     2767.88     2.71736

   1000000 degrees          280     311.111     4977.78     4.88692
   1000000 gradians           0           0           0           0
   1000000 mills             90         100        1600      1.5708
   1000000 radians      339.513     377.237     6035.79     5.92562
```

Alternately, implemented as a series of postfix operators:

*(Much of the complexity is due to the requirement that negative angles must normalize to a negative number.)*

```
sub postfix:<t>( $t ) { my $a = $t % 1 * τ;           $t >=0 ?? $a !! $a - τ }
sub postfix:<d>( $d ) { my $a = $d % 360 * τ / 360;   $d >=0 ?? $a !! $a - τ }
sub postfix:<g>( $g ) { my $a = $g % 400 * τ / 400;   $g >=0 ?? $a !! $a - τ }
sub postfix:<m>( $m ) { my $a = $m % 6400 * τ / 6400; $m >=0 ?? $a !! $a - τ }
sub postfix:<r>( $r ) { my $a = $r % τ;               $r >=0 ?? $a !! $a - τ }

sub postfix:«->t» ($angle) { my $a = $angle / τ;        ($angle < 0 and $a == -1)    ?? -0 !! $a }
sub postfix:«->d» ($angle) { my $a = $angle / τ * 360;  ($angle < 0 and $a == -360)  ?? -0 !! $a }
sub postfix:«->g» ($angle) { my $a = $angle / τ * 400;  ($angle < 0 and $a == -400)  ?? -0 !! $a }
sub postfix:«->m» ($angle) { my $a = $angle / τ * 6400; ($angle < 0 and $a == -6400) ?? -0 !! $a }
sub postfix:«->r» ($angle) { my $a = $angle;            ($angle < 0 and $a == -τ)    ?? -0 !! $a }

for <-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000> -> $a {
    say '';
    say '  Quantity  Unit      ', <turns degrees gradians mils radians>.fmt('%15s');
    for 'turns', &postfix:«t», 'degrees', &postfix:«d», 'gradians', &postfix:«g»,
        'mils',  &postfix:«m», 'radians', &postfix:«r»
      -> $unit, &f {
            printf "%10s %-10s %15s %15s %15s %15s %15s\n", $a, $unit,
            |($a.&f->t, $a.&f->d, $a.&f->g, $a.&f->m, $a.&f->r)».round(.00000001);
    }
}

```

```
 Quantity  Unit                turns         degrees        gradians            mils         radians
        -2 turns                    0               0               0               0               0
        -2 degrees        -0.00555556              -2     -2.22222222    -35.55555556     -0.03490659
        -2 gradians            -0.005            -1.8              -2             -32     -0.03141593
        -2 mils             -0.000313         -0.1125          -0.125              -2      -0.0019635
        -2 radians        -0.31830989   -114.59155903   -127.32395447  -2037.18327158              -2

  Quantity  Unit                turns         degrees        gradians            mils         radians
        -1 turns                    0               0               0               0               0
        -1 degrees        -0.00277778              -1     -1.11111111    -17.77777778     -0.01745329
        -1 gradians           -0.0025            -0.9              -1             -16     -0.01570796
        -1 mils             -0.000156        -0.05625         -0.0625              -1     -0.00098175
        -1 radians        -0.15915494    -57.29577951    -63.66197724  -1018.59163579              -1

  Quantity  Unit                turns         degrees        gradians            mils         radians
         0 turns                    0               0               0               0               0
         0 degrees                  0               0               0               0               0
         0 gradians                 0               0               0               0               0
         0 mils                     0               0               0               0               0
         0 radians                  0               0               0               0               0

  Quantity  Unit                turns         degrees        gradians            mils         radians
         1 turns                    0               0               0               0               0
         1 degrees         0.00277778               1      1.11111111     17.77777778      0.01745329
         1 gradians            0.0025             0.9               1              16      0.01570796
         1 mils              0.000156         0.05625          0.0625               1      0.00098175
         1 radians         0.15915494     57.29577951     63.66197724   1018.59163579               1

  Quantity  Unit                turns         degrees        gradians            mils         radians
         2 turns                    0               0               0               0               0
         2 degrees         0.00555556               2      2.22222222     35.55555556      0.03490659
         2 gradians             0.005             1.8               2              32      0.03141593
         2 mils              0.000313          0.1125           0.125               2       0.0019635
         2 radians         0.31830989    114.59155903    127.32395447   2037.18327158               2

  Quantity  Unit                turns         degrees        gradians            mils         radians
 6.2831853 turns            0.2831853      101.946708       113.27412      1812.38592      1.77930572
 6.2831853 degrees         0.01745329       6.2831853        6.981317      111.701072      0.10966227
 6.2831853 gradians        0.01570796      5.65486677       6.2831853     100.5309648      0.09869604
 6.2831853 mils            0.00098175      0.35342917      0.39269908       6.2831853       0.0061685
 6.2831853 radians                  1    359.99999959    399.99999954   6399.99999269       6.2831853

  Quantity  Unit                turns         degrees        gradians            mils         radians
        16 turns                    0               0               0               0               0
        16 degrees         0.04444444              16     17.77777778    284.44444444      0.27925268
        16 gradians              0.04            14.4              16             256      0.25132741
        16 mils                0.0025             0.9               1              16      0.01570796
        16 radians         0.54647909    196.73247221    218.59163579   3497.46617261      3.43362939

  Quantity  Unit                turns         degrees        gradians            mils         radians
57.2957795 turns            0.2957795       106.48062        118.3118       1892.9888      1.85843741
57.2957795 degrees         0.15915494      57.2957795     63.66197722   1018.59163556               1
57.2957795 gradians        0.14323945     51.56620155      57.2957795      916.732472             0.9
57.2957795 mils            0.00895247       3.2228876      3.58098622      57.2957795         0.05625
57.2957795 radians         0.11890653     42.80634926     47.56261029    761.00176466      0.74711174

  Quantity  Unit                turns         degrees        gradians            mils         radians
       359 turns                    0               0               0               0               0
       359 degrees         0.99722222             359    398.88888889   6382.22222222      6.26573201
       359 gradians            0.8975           323.1             359            5744      5.63915881
       359 mils              0.056094        20.19375         22.4375             359      0.35244743
       359 radians         0.13662457      49.1848452       54.649828    874.39724794      0.85843749

  Quantity  Unit                turns         degrees        gradians            mils         radians
       399 turns                    0               0               0               0               0
       399 degrees         0.10833333              39     43.33333333    693.33333333      0.68067841
       399 gradians            0.9975           359.1             399            6384      6.26747734
       399 mils              0.062344        22.44375         24.9375             399      0.39171733
       399 radians         0.50282229    181.01602572    201.12891747   3218.06267946      3.15932565

  Quantity  Unit                turns         degrees        gradians            mils         radians
      6399 turns                    0               0               0               0               0
      6399 degrees              0.775             279             310            4960      4.86946861
      6399 gradians            0.9975           359.1             399            6384      6.26747734
      6399 mils              0.999844       359.94375        399.9375            6399      6.28220356
      6399 radians         0.43248085    155.69310421    172.99233802   2767.87740825      2.71735729

  Quantity  Unit                turns         degrees        gradians            mils         radians
   1000000 turns                    0               0               0               0               0
   1000000 degrees         0.77777778             280    311.11111111   4977.77777778      4.88692191
   1000000 gradians                 0               0               0               0               0
   1000000 mils                  0.25              90             100            1600      1.57079633
   1000000 radians          0.9430919    339.51308233    377.23675814   6035.78813022      5.92562114
```


[User]
Capture of the Oz version.

One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.

The classic such physical system is a simple gravity pendulum.

Task

Create a simple physical model of a pendulum and animate it.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.09

Handles window resizing, modifies pendulum length and period as window height changes. May need to tweek $ppi scaling to get good looking animation.

```
use SDL2::Raw;
use Cairo;

my $width = 1000;
my $height = 400;

SDL_Init(VIDEO);

my $window = SDL_CreateWindow(
    'Pendulum - Raku',
    SDL_WINDOWPOS_CENTERED_MASK,
    SDL_WINDOWPOS_CENTERED_MASK,
    $width, $height, RESIZABLE
);

my $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);

my $bob = Cairo::Image.create( Cairo::FORMAT_ARGB32, 32, 32 );
given Cairo::Context.new($bob) {
     my Cairo::Pattern::Gradient::Radial $sphere .=
        create(13.3, 12.8, 3.2, 12.8, 12.8, 32);
     $sphere.add_color_stop_rgba(0, 1, 1, .698, 1);
     $sphere.add_color_stop_rgba(1, .623, .669, .144, 1);
     .pattern($sphere);
     .arc(16, 16, 15, 0, 2 * pi);
     .fill;
     $sphere.destroy;
}

my $bob_texture = SDL_CreateTexture(
    $render, %PIXELFORMAT<ARGB8888>,
    STATIC, 32, 32
);

SDL_UpdateTexture(
    $bob_texture,
    SDL_Rect.new(:x(0), :y(0), :w(32), :h(32)),
    $bob.data, $bob.stride // 32
);

SDL_SetTextureBlendMode($bob_texture, 1);

SDL_SetRenderDrawBlendMode($render, 1);

my $event = SDL_Event.new;

my $now = now;   # time
my $Θ   = -π/3;  # start angle
my $ppi = 500;   # scale
my $g   = -9.81; # accelaration of gravity
my $ax  = $width/2; # anchor x
my $ay  = 25;       # anchor y
my $len = $height - 75; # 'rope' length
my $vel; # velocity
my $dt;  # delta time

main: loop {
    while SDL_PollEvent($event) {
        my $casted_event = SDL_CastEvent($event);
        given $casted_event {
            when *.type == QUIT    { last main }
            when *.type == WINDOWEVENT {
                if .event == 5 {
                    $width  = .data1;
                    $height = .data2;
                    $ax = $width/2;
                    $len = $height - 75;
                }
            }
        }
    }

    $dt = now - $now;
    $now = now;
    $vel += $g / $len * sin($Θ) * $ppi * $dt;
    $Θ   += $vel * $dt;
    my $bx = $ax + sin($Θ) * $len;
    my $by = $ay + cos($Θ) * $len;

    SDL_SetRenderDrawColor($render, 255, 255, 255, 255);
    SDL_RenderDrawLine($render, |($ax, $ay, $bx, $by)».round);
    SDL_RenderCopy( $render, $bob_texture, Nil,
      SDL_Rect.new($bx - 16, $by - 16, 32, 32)
    );
    SDL_RenderPresent($render);
    SDL_SetRenderDrawColor($render, 0, 0, 0, 0);
    SDL_RenderClear($render);
}

SDL_Quit();

```


[User]
Task

Create and display five spinners.
One spinner in the middle and four spinners surrounding it.
Each spinner is created by drawing radius lines around a center axis and then looping through the drawing to simulate a moving clock hand.
When the loop is sped up, the illusion of a spinner is created.
NOTE: The animated GIF example is actually slower than what you should be able to create. A fast animation will fill in more radial lines with a pleasing appearance.

Stretch goal

Extra credit for offsetting the spinners with mouse movement.

|  |  |  |
| --- | --- | --- |
| Slow Spinners | Fast Spinners | Spinners offset with mouse movement |

[Assistant]
```
# 20250206 Raku programming solution

use NativeCall;

class Window is repr('CPointer') {}
class Monitor is repr('CPointer') {}

constant $lib   = ('glfw', v3);
constant $gllib = 'GL';

sub glfwInit(--> int32) is native($lib) {*}
sub glfwCreateWindow(int32, int32, Str, Monitor, Window --> Window) is native($lib) {*}
sub glfwTerminate() is native($lib) {*}
sub glfwMakeContextCurrent(Window) is native($lib) {*}
sub glfwWindowShouldClose(Window --> int32) is native($lib) {*}
sub glfwSwapBuffers(Window) is native($lib) {*}
sub glfwSwapInterval(int32) is native($lib) {*}
sub glfwPollEvents() is native($lib) {*}

sub glClear(int32) is native($gllib) {*}
sub glLoadIdentity() is native($gllib) {*}
sub glTranslatef(num32, num32, num32) is native($gllib) {*}
sub glRotatef(num32, num32, num32, num32) is native($gllib) {*}
sub glColor4f(num32, num32, num32, num32) is native($gllib) {*}
sub glBegin(int32) is native($gllib) {*}
sub glVertex2f(num32, num32) is native($gllib) {*}
sub glEnd() is native($gllib) {*}
sub glPushMatrix() is native($gllib) {*}
sub glPopMatrix() is native($gllib) {*}

enum PrimitiveMode( GL_LINES => 0x0001 );
constant GL_COLOR_BUFFER_BIT = 0x00004000;

my (\NUM_LINES,\INNER_RADIUS,\OUTER_RADIUS,\ROTATION_SPEED) = 1, 0.0, 0.5, 2.0;

sub drawLine($angle, $opacity, $centerX, $centerY) {
   glPushMatrix();
   glTranslatef($centerX, $centerY, 0e0);
   glRotatef($angle, 0e0, 0e0, 1e0);
   glColor4f(1e0, 1e0, 1e0, $opacity);

   glBegin(GL_LINES);
      (INNER_RADIUS, OUTER_RADIUS)>>.Num.map: { glVertex2f($_, 0e0) };
   glEnd();

   glPopMatrix();
}

die 'Failed to initialize GLFW' unless glfwInit().so;

my $w = glfwCreateWindow(640, 480, "Spinners", Nil, Nil);
without $w { glfwTerminate(); die 'Failed to create window' }

glfwMakeContextCurrent($w);
glfwSwapInterval(1);

my @angles    = 0.0 xx 5;
my @positions = (<0 0>, <-.5 .5>, <.5 .5>, <-.5 -.5>, <.5 -.5>).map: *>>.Num;

until glfwWindowShouldClose($w) {
   glClear(GL_COLOR_BUFFER_BIT);
   glLoadIdentity();

   for 0 ..^ NUM_LINES -> $i {
      my $opacity = 1.0e0 - ($i / NUM_LINES);
      for @positions.kv -> $index, $pos {
         drawLine((@angles[$index] + 360 / NUM_LINES * $i).Num, $opacity, $pos[0], $pos[1]);
      }
   }

   glfwSwapBuffers($w);
   glfwPollEvents();

   for 0 ..^ 5 -> $i {
      @angles[$i] += (ROTATION_SPEED * (1 / 60).Num);
      @angles[$i] -= 360 if @angles[$i] >= 360;
   }
}

glfwTerminate();

```


[User]
**Animation** is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this.

Task

Create a window containing the string "`Hello World!` " (the trailing space is significant).

Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.

When the user clicks on the (windowed) text, it should reverse its direction.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

```
use GTK::Simple;
use GTK::Simple::App;

my $app    = GTK::Simple::App.new(:title<Animation>);
my $button = GTK::Simple::Button.new(label => 'Hello World! ');
my $vbox   = GTK::Simple::VBox.new($button);

my $repeat = $app.g-timeout(100); # milliseconds

my $dir = 1;
$button.clicked.tap({ $dir *= -1 });

$repeat.tap( &{$button.label = $button.label.comb.List.rotate($dir).join} );

$app.set-content($vbox);

$app.run;

```


[User]
While implementing a recursive function, it often happens that we must resort to a separate   *helper function*   to handle the actual recursion.

This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values.

So we end up inventing some silly name like   **foo2**   or   **foo\_helper**.   I have always found it painful to come up with a proper name, and see some disadvantages:

:   :   * You have to think up a name, which then pollutes the namespace
        * Function is created which is called from nowhere else
        * The program flow in the source code is interrupted

Some languages allow you to embed recursion directly in-place.   This might work via a label, a local *gosub* instruction, or some special keyword.

Anonymous recursion can also be accomplished using the   Y combinator.

Task

If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.

Related tasks
:   * Y combinator

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

In addition to the methods in the Perl entry above, and the Y-combinator described in Y\_combinator, you may also refer to an anonymous block or function from the inside:

```
sub fib($n) {
    die "Naughty fib" if $n < 0;
    return {
        $_ < 2
            ?? $_
            !!  &?BLOCK($_-1) + &?BLOCK($_-2);
    }($n);
}

say fib(10);
```

However, using any of these methods is insane, when Raku provides a sort of inside-out combinator that lets you define lazy infinite constants, where the demand for a particular value is divorced from dependencies on more primitive values. This operator, known as the sequence operator, does in a sense provide anonymous recursion to a closure that refers to more primitive values.

```
constant @fib = 0, 1, *+* ... *;
say @fib[10];
```

Here the closure, \*+\*, is just a quick way to write a lambda, -> $a, $b { $a + $b }. The sequence operator implicitly maps the two arguments to the -2nd and -1st elements of the sequence. So the sequence operator certainly applies an anonymous lambda, but whether it's recursion or not depends on whether you view a sequence as iteration or as simply a convenient way of memoizing a recursion. Either view is justifiable.

At this point someone may complain that the solution is doesn't fit the specified task because the sequence operator doesn't do the check for negative. True, but the sequence operator is not the whole of the solution; this check is supplied by the subscripting operator itself when you ask for @fib[-1]. Instead of scattering all kinds of arbitrary boundary conditions throughout your functions, the sequence operator maps them quite naturally to the boundary of definedness at the start of a list.


[User]
The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.

Task

Generate and show here, the first twenty anti-primes.

Related tasks
:   * Factors of an integer
    * Sieve of Eratosthenes

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.11

At its heart, this task is almost exactly the same as Proper\_Divisors, it is just asking for slightly different results. Much of this code is lifted straight from there.

Implemented as an auto-extending lazy list. Displaying the count of anti-primes less than 5e5 also because... why not.

```
sub propdiv (\x) {
    my @l = 1 if x > 1;
    (2 .. x.sqrt.floor).map: -> \d {
        unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
    }
    @l
}

my $last = 0;

my @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).grep: -> $c {
    my \mx = +propdiv($c);
    next if mx <= $last;
    $last = mx;
    $c
}

my $upto = 5e5;

put "First 20 anti-primes:\n{ @anti-primes[^20] }";

put "\nCount of anti-primes <= $upto: {+@anti-primes[^(@anti-primes.first: * > $upto, :k)]}";

```

Output:

```
First 20 anti-primes:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560

Count of anti-primes <= 500000: 35
```


[User]
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.

This feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care *must* be taken to avoid concurrently overwriting the same record from another job.

Task

Given a two record sample for a mythical "passwd" file:

* Write these records out in the typical system format.
  + Ideally these records will have named fields of various types.
* Close the file, then reopen the file for append.
  + **Append** a new record to the file and close the file again.
  + Take appropriate care to avoid concurrently overwrites from another job.
* Open the file and demonstrate the new record has indeed written to the end.

Source record field types and contents.

| account | password | UID | GID | fullname,office,extension,homephone,email | directory | shell |
| --- | --- | --- | --- | --- | --- | --- |
| string | string | int | int | struct(string,string,string,string,string) | string | string |
| jsmith | x | 1001 | 1000 | Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org | /home/jsmith | /bin/bash |
| jdoe | x | 1002 | 1000 | Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org | /home/jdoe | /bin/bash |

Record to be appended.

| account | password | UID | GID | fullname,office,extension,homephone,email | directory | shell |
| --- | --- | --- | --- | --- | --- | --- |
| string | string | int | int | struct(string,string,string,string,string) | string | string |
| xyz | x | 1003 | 1000 | X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org | /home/xyz | /bin/bash |

**Resulting file format:** should mimic Linux's /etc/passwd file format with particular attention to the "," separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.

**Expected output:**

```
Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash

```

**Finally:** Provide a summary of the language's "append record" capabilities in a table. eg.

Append Capabilities.

| Data Representation | | IO Library | Append Possible | Automatic Append | Multi-tasking Safe |
| --- | --- | --- | --- | --- | --- |
| In core | On disk |
| C struct | CSV text file | glibc/stdio | ☑ | ☑ | ☑ (Not all, eg NFS) |

Alternatively: If the language's appends can not guarantee its writes will **always** append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.09

This is kind of silly as it takes a string, converts it to a record, and then instantly converts it back to a string to write out to a file. Most of the "record handling" code is just demonstrating a possible way to store records in memory. It really has nothing to do with appending a string to a file.

```
class record {
    has $.name;
    has $.password;
    has $.UID;
    has $.GID;
    has $.fullname;
    has $.office;
    has $.extension;
    has $.homephone;
    has $.email;
    has $.directory;
    has $.shell;

    method gecos { join ',', $.fullname, $.office, $.extension, $.homephone, $.email }

    method gist {
        join ':',
        $.name,
        $.password,
        $.UID,
        $.GID,
        self.gecos,
        $.directory,
        $.shell;
    }
};

my $fname = 'foo.fil';

given $fname.IO.open(:w) { .close }; # clear file

sub append ($file, $line){
    my $fh = $file.IO.open(:a) or fail "Unable to open $file";
    given $fh {
        # Get a lock on the file, waits until lock is active
        .lock;
        # seek to the end in case some other process wrote to
        # the file while we were waiting for the lock
        .seek(0, SeekType::SeekFromEnd);
        # write the record
        .say: $line;
        .close;
    }
}

sub str-to-record ($str) {
    my %rec = <name password UID GID fullname office extension
      homephone email directory shell> Z=> $str.split(/<[:,]>/);
    my $user = record.new(|%rec);
}

for
  'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash',
  'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'
-> $line {
        my $thisuser = str-to-record $line;
       $fname.&append: $thisuser.gist;
}

put "Last line of $fname before append:";
put $fname.IO.lines.tail;

$fname.&append: str-to-record('xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash').gist;

put "Last line of $fname after append:";
put $fname.IO.lines.tail;

```

Output:

```
Last line of foo.fil before append:
jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash
Last line of foo.fil after append:
xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash
```

Append Capabilities.

| Data Representation | | IO Library | Append Possible | Automatic Append | Multi-tasking Safe |
| --- | --- | --- | --- | --- | --- |
| In core | On disk |
| Class | Text file | Whichever is provided by the underlying VM | ☑ | ☑ | ☑ Advisory lock Depends on OS and VM |

Note that advisory locks do not prevent some other program (if it doesn't use flock) from unexpectedly writing to the file.


[User]
Task

Given three lists:

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

list2 = [10,11,12,13,14,15,16,17,18]

list3 = [19,20,21,22,23,24,25,26,27]

At each index, turn the numbers into strings and concatenate them.

The result should be:

list = [11019,21120,31221,41322,51423,61524,71625,81726,91827]

[Assistant]
Various manipulations.

```
my @lists = 1..9, 10..18, 19..27;
put [Z~] @lists;         # the task
put [Z~] @lists».flip;   # each component reversed
put [RZ~] @lists;        # in reversed order
put ([Z~] @lists)».flip; # reversed components in reverse order

```

Output:

```
11019 21120 31221 41322 51423 61524 71625 81726 91827
10191 21102 32112 43122 54132 65142 76152 87162 98172
19101 20112 21123 22134 23145 24156 25167 26178 27189
91011 02112 12213 22314 32415 42516 52617 62718 72819
```


[User]
Task

Take a combined set of elements and apply a function to each element.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.10-11

```
sub function { 2 * $^x + 3 };
my @array = 1 .. 5;

# via map function
.say for map &function, @array;

# via map method
.say for @array.map(&function);

# via for loop
for @array {
    say function($_);
}

# via the "hyper" metaoperator and method indirection
say @array».&function;

# we neither need a variable for the array nor for the function
say [1,2,3]>>.&({ $^x + 1});
```


[User]
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]

Task

Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]

The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]

See also

[Wikipedia on Butterworth filters]

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.11

**Translation of**: zkl

```
sub TDF-II-filter ( @signal, @a, @b ) {
    my @out = 0 xx @signal;
    for ^@signal -> $i {
        my $this;
        $this += @b[$_] * @signal[$i-$_] if $i-$_ >= 0 for ^@b;
        $this -= @a[$_] *    @out[$i-$_] if $i-$_ >= 0 for ^@a;
        @out[$i] = $this / @a[0];
    }
    @out
}

my @signal = [
    -0.917843918645,  0.141984778794, 1.20536903482,   0.190286794412,
    -0.662370894973, -1.00700480494, -0.404707073677,  0.800482325044,
     0.743500089861,  1.01090520172,  0.741527555207,  0.277841675195,
     0.400833448236, -0.2085993586,  -0.172842103641, -0.134316096293,
     0.0259303398477, 0.490105989562, 0.549391221511,  0.9047198589
];
my @a = [ 1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ];
my @b = [ 0.16666667,  0.5,            0.5,             0.16666667     ];

say TDF-II-filter(@signal, @a, @b)».fmt("% 0.8f")
    Z~ flat (', ' xx 4, ",\n") xx *;

```

Output:

```
(-0.15297399,  -0.43525783,  -0.13604340,   0.69750333,   0.65644469,
 -0.43548245,  -1.08923946,  -0.53767655,   0.51704999,   1.05224975,
  0.96185430,   0.69569009,   0.42435630,   0.19626223,  -0.02783512,
 -0.21172192,  -0.17474556,   0.06925841,   0.38544587,   0.65177084,
)
```


[User]
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.

For example, a difference between **32** bit and **64** bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.

Task

Create a function which returns true if two floating point numbers are approximately equal.

The function should allow for differences in the magnitude of numbers, so that, for example,

**100000000000000.01**   may be approximately equal to   **100000000000000.011**,

even though   **100.01**   is not approximately equal to   **100.011**.

If the language has such a feature in its standard library, this may be used instead of a custom function.

Show the function results with comparisons on the following pairs of values:

:   1. 100000000000000.01,   100000000000000.011     (note: should return *true*)
    2. 100.01,   100.011                                                     (note: should return *false*)
    3. 10000000000000.001 / 10000.0,   1000000000.0000001000
    4. 0.001,   0.0010000001
    5. 0.000000000000000000000101,   0.0
    6. sqrt(2) \* sqrt(2),    2.0
    7. -sqrt(2) \* sqrt(2),   -2.0
    8. 3.14159265358979323846,   3.14159265358979324

Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

Is approximately equal to is a built-in operator in Raku. Unicode ≅, or the ASCII equivalent: =~=. By default it uses a tolerance of 1e-15 times the order of magnitude of the larger comparand, though that is adjustable by setting the dynamic variable $\*TOLERANCE to the desired value. Probably a good idea to localize the changed $\*TOLERANCE as it will affect all comparisons within its scope.

Most of the following tests are somewhat pointless in Raku. To a large extent, when dealing with Rational values, you don't really need to worry about "approximately equal to", and all of the test values below, with the exception of `sqrt(2)`, are Rats by default, and exact. You would have to specifically coerce them to Nums (floating point) to lose the precision.

For example, in Raku, the sum of .1, .2, .3, & .4 is *identically* equal to 1.

```
say 0.1 + 0.2 + 0.3 + 0.4 === 1.0000000000000000000000000000000000000000000000000000000000000000000000000; # True

```

It's also *approximately* equal to 1 but... ¯\\_(ツ)\_/¯

```
for
    100000000000000.01, 100000000000000.011,
    100.01, 100.011,
    10000000000000.001 / 10000.0, 1000000000.0000001000,
    0.001, 0.0010000001,
    0.000000000000000000000101, 0.0,
    sqrt(2) * sqrt(2), 2.0,
    -sqrt(2) * sqrt(2), -2.0,
    100000000000000003.0, 100000000000000004.0,
    3.14159265358979323846, 3.14159265358979324

  -> $a, $b {
    say "$a ≅ $b: ", $a ≅ $b;
}

say "\nTolerance may be adjusted.";

say 22/7, " ≅ ", π, ": ", 22/7 ≅ π;
{ # Localize the tolerance to only this block
  my $*TOLERANCE = .001;
  say 22/7, " ≅ ", π, ": ", 22/7 ≅ π;
}

```

Output:

```
100000000000000.01 ≅ 100000000000000.011: True
100.01 ≅ 100.011: False
1000000000.0000001 ≅ 1000000000.0000001: True
0.001 ≅ 0.0010000001: False
0.000000000000000000000101 ≅ 0: True
2.0000000000000004 ≅ 2: True
-2.0000000000000004 ≅ -2: True
100000000000000003 ≅ 100000000000000004: True
3.141592653589793226752 ≅ 3.14159265358979324: True

Tolerance may be adjusted.
3.142857 ≅ 3.141592653589793: False
3.142857 ≅ 3.141592653589793: True
```


[User]
Apéry's constant is the sum of the reciprocals of the positive cubes.

That is, it is defined as the number

ζ
(
3
)
=

∑

k
=
1

∞

1

k

3
,
{\displaystyle {\displaystyle \zeta (3)=\sum \_{k=1}^{\infty }{\frac {1}{k^{3}}},}}
 *where ζ is the Riemann zeta function*.

Approximately equal to:

:   **1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581**

This constant was known and studied by many early mathematicians, but was not named until 1978, after Roger Apéry, who was first to prove it was an irrational number.

ζ
(
3
)
{\displaystyle {\displaystyle \zeta (3)}}
 by summing reciprocal cubes is easy to calculate, but converges very slowly. The first 1000 terms are only accurate to 6 decimal places.

There have been many fast convergence representations developed / discovered that generate correct digits much more quickly.

One of the earliest, discovered in the late 1800s by A. Markov and later widely published by Apéry is:

:   ζ
    (
    3
    )
    =

    5
    2

    ∑

    k
    =
    1

    ∞
    (
    −
    1

    )

    k
    −
    1

    k

    !

    2

    (
    2
    k
    )
    !

    k

    3
    .
    {\displaystyle {\displaystyle \zeta (3)={\frac {5}{2}}\sum \_{k=1}^{\infty }(-1)^{k-1}{\frac {k!^{2}}{(2k)!k^{3}}}.}}

Much better than direct calculation of

ζ
(
3
)
{\displaystyle {\displaystyle \zeta (3)}}
, but still only yielding about .63 correct digits per iteration.

Several even faster converging representions are available. The fastest known to date, yielding about 5.04 correct digits per term, is by Sebastian Wedeniwski.

:   ζ
    (
    3
    )
    =

    1
    24

    ∑

    k
    =
    0

    ∞
    (
    −
    1

    )

    k

    (
    2
    k
    +
    1
    )

    !

    3
    (
    2
    k
    )

    !

    3
    k

    !

    3
    (
    126392

    k

    5
    +
    412708

    k

    4
    +
    531578

    k

    3
    +
    336367

    k

    2
    +
    104000
    k
    +
    12463
    )

    (
    3
    k
    +
    2
    )
    !
    (
    4
    k
    +
    3
    )

    !

    3
    .
    {\displaystyle {\displaystyle \zeta (3)={\frac {1}{24}}\sum \_{k=0}^{\infty }(-1)^{k}{\frac {(2k+1)!^{3}(2k)!^{3}k!^{3}(126392k^{5}+412708k^{4}+531578k^{3}+336367k^{2}+104000k+12463)}{(3k+2)!(4k+3)!^{3}}}.}}

Task

* Show the value of Apéry's constant calculated at least three different ways.

:   1. Show the value of at least the first 1000 terms of

       ζ
       (
       3
       )
       {\displaystyle {\displaystyle \zeta (3)}}
        by direct summing of reciprocal cubes, truncated to 100 decimal digits.
    2. Show the value of the first 158 terms of Markov / Apéry representation truncated to 100 decimal digits.
    3. Show the value of the first 20 terms of Wedeniwski representation truncated to 100 decimal digits.

See also

* Wikipedia: Apéry's constant * OEIS:A002117 - Decimal expansion of zeta(3)

[Assistant]
```
sub postfix:<!> (Int $n) { (constant f = 1, |[\×] 1..*)[$n] }

say 'Actual value to 100 decimal places:';
say '1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581';

say "\nFirst 1000 terms of ζ(3) truncated to 100 decimal places. (accurate to 6 decimal places):";
say (1..1000).map({FatRat.new: 1, .³}).sum.substr: 0, 102;

say "\nFirst 158 terms of Markov / Apéry representation truncated to 100 decimal places:";
say (5/2 × (1..158).map( -> \k { (-1)**(k-1) × FatRat.new: k!², ((2×k)! × k³) } ).sum).substr: 0, 102;

say "\nFirst 20 terms of Wedeniwski representation truncated to 100 decimal places:";
say (1/24 × ((^20).map: -> \k {
    (-1)**k × FatRat.new: (2×k+1)!³ × (2×k)!³ × k!³ × (126392×k⁵ + 412708×k⁴ + 531578×k³ + 336367×k² + 104000×k + 12463), (3×k+2)! × (4×k+3)!³
}).sum).substr: 0, 102;

```

Output:

Actual value to 100 decimal places:

1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581

First 1000 terms of ζ(3) truncated to 100 decimal places. (accurate to 6 decimal places):
1.2020564036593442854830714115115999903483212709031775135036540966118572571921400836130084123260473111

First 158 terms of Markov / Apéry representation truncated to 100 decimal places:
1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581

First 20 terms of Wedeniwski representation truncated to 100 decimal places:
1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581


[User]
Using the in-built capabilities of your language, calculate the integer value of:

```

              5

                  4

                      3

                        2

    {\displaystyle {\displaystyle 5^{4^{3^{2}}}}}

```

* Confirm that the first and last twenty digits of the answer are:

```
     62060698786608744707...92256259918212890625

```

* Find and show the number of decimal digits in the answer.

Note:

* Do not submit an *implementation* of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that *may* be used instead.
* Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the **only** recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.

Related tasks

* Long multiplication
* Exponentiation order
* exponentiation operator
* Exponentiation with infix operators in (or operating on) the base

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2022.07

```
given [**] 5, 4, 3, 2 {
  use Test;
  ok /^ 62060698786608744707 <digit>* 92256259918212890625 $/,
     '5**4**3**2 has expected first and last twenty digits';
  printf 'This number has %d digits', .chars;
}

```

Output:

```
ok 1 - 5**4**3**2 has expected first and last twenty digits
This number has 183231 digits
```


[User]
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.

An Archimedean spiral can be described by the equation:

:   r
    =
    a
    +
    b
    θ
    {\displaystyle {\displaystyle \,r=a+b\theta }}

with real numbers *a* and *b*.

Task

Draw an Archimedean spiral.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.10

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

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

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

(0, .025 ... 52*π).race.map: -> \Θ {
    $png.set: |((cis( Θ / π ) * Θ).reals »+« ($w/2, $h/2))».Int, 255, 0, 255;
}

$png.write: 'Archimedean-spiral-perl6.png';

```


[User]
Dynamically allocated objects take their memory from a heap.

The memory for an object is provided by an **allocator** which maintains the storage pool used for the heap.

Often a call to allocator is denoted as

```
P := new T

```

where   **T**   is the type of an allocated object,   and   **P**   is a reference to the object.

The storage pool chosen by the allocator can be determined by either:

* the object type   **T**
* the type of pointer   **P**

In the former case objects can be allocated only in one storage pool.

In the latter case objects of the type can be allocated in any storage pool or on the stack.

Task

The task is to show how allocators and user-defined storage pools are supported by the language.

In particular:

1. define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups.
2. allocate some objects (e.g., integers) in the pool.

Explain what controls the storage pool choice in the language.

[Assistant]
(formerly Perl 6)

Raku is a high level language where, to a first approximation, everything is an object. Raku dynamically allocates memory as objects are created and does automatic garbage collection and freeing of memory as objects go out of scope. There is almost no high level control over how memory is managed, it is considered to be an implementation detail of the virtual machine on which it is running.

If you absolutely must take manual control over memory management you would need to use the foreign function interface to call into a language that provides the capability, but even that would only affect items in the scope of that function, not anything in the mainline process.

There is some ability to specify data types for various objects which allows for (but does not guarantee) more efficient memory layout, but again, it is considered to be an implementation detail, the use that the virtual machine makes of that information varies by implementation maturity and capabilities.


[User]
Arithmetic coding is a form of entropy encoding used in lossless data compression. Normally, a string of characters such as the words "hello there" is represented using a fixed number of bits per character, as in the ASCII code. When a string is converted to arithmetic encoding, frequently used characters will be stored with fewer bits and not-so-frequently occurring characters will be stored with more bits, resulting in fewer bits used in total. Arithmetic coding differs from other forms of entropy encoding, such as Huffman coding, in that rather than separating the input into component symbols and replacing each with a code, arithmetic coding encodes the entire message into a single number.

Task

Create a program which implements the arithmetic coding as a generalized change of radix.

Show the results, in base 10, for all the following strings:

* "DABDDB"
* "DABDDBBDDBA"
* "ABRACADABRA"
* "TOBEORNOTTOBEORTOBEORNOT"

Verify the implementation by decoding the results back into strings and checking for equality with the given strings.

[Assistant]
(formerly Perl 6)

```
sub cumulative_freq(%freq) {
    my %cf;
    my $total = 0;
    for %freq.keys.sort -> $c {
        %cf{$c} = $total;
        $total += %freq{$c};
    }
    return %cf;
}

sub arithmethic_coding($str, $radix) {
    my @chars = $str.comb;

    # The frequency characters
    my %freq;
    %freq{$_}++ for @chars;

    # The cumulative frequency table
    my %cf = cumulative_freq(%freq);

    # Base
    my $base = @chars.elems;

    # Lower bound
    my $L = 0;

    # Product of all frequencies
    my $pf = 1;

    # Each term is multiplied by the product of the
    # frequencies of all previously occurring symbols
    for @chars -> $c {
        $L = $L*$base + %cf{$c}*$pf;
        $pf *= %freq{$c};
    }

    # Upper bound
    my $U = $L + $pf;

    my $pow = 0;
    loop {
        $pf div= $radix;
        last if $pf == 0;
        ++$pow;
    }

    my $enc = ($U - 1) div ($radix ** $pow);
    ($enc, $pow, %freq);
}

sub arithmethic_decoding($encoding, $radix, $pow, %freq) {

    # Multiply encoding by radix^pow
    my $enc = $encoding * $radix**$pow;

    # Base
    my $base = [+] %freq.values;

    # Create the cumulative frequency table
    my %cf = cumulative_freq(%freq);

    # Create the dictionary
    my %dict;
    for %cf.kv -> $k,$v {
        %dict{$v} = $k;
    }

    # Fill the gaps in the dictionary
    my $lchar;
    for ^$base -> $i {
        if (%dict{$i}:exists) {
            $lchar = %dict{$i};
        }
        elsif (defined $lchar) {
            %dict{$i} = $lchar;
        }
    }

    # Decode the input number
    my $decoded = '';
    for reverse(^$base) -> $i {

        my $pow = $base**$i;
        my $div = $enc div $pow;

        my $c  = %dict{$div};
        my $fv = %freq{$c};
        my $cv = %cf{$c};

        my $rem = ($enc - $pow*$cv) div $fv;

        $enc = $rem;
        $decoded ~= $c;
    }

    # Return the decoded output
    return $decoded;
}

my $radix = 10;    # can be any integer greater or equal with 2

for <DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT> -> $str {
    my ($enc, $pow, %freq) = arithmethic_coding($str, $radix);
    my $dec = arithmethic_decoding($enc, $radix, $pow, %freq);

    printf("%-25s=> %19s * %d^%s\n", $str, $enc, $radix, $pow);

    if ($str ne $dec) {
        die "\tHowever that is incorrect!";
    }
}

```

Output:

```
DABDDB                   =>                 251 * 10^2
DABDDBBDDBA              =>              167351 * 10^6
ABRACADABRA              =>             7954170 * 10^4
TOBEORNOTTOBEORTOBEORNOT => 1150764267498783364 * 10^15

```


[User]
The **arithmetic derivative** of an integer (more specifically, the
**Lagarias arithmetic derivative**) is a function defined for integers, based on prime
factorization, by analogy with the product rule for the derivative of a function that is
used in mathematical analysis. Accordingly, for natural numbers n, the arithmetic
derivative D(n) is defined as follows:

* D ( 0 ) = D ( 1 ) = 0 {\displaystyle {\displaystyle D(0)=D(1)=0}} . * D ( p ) = 1 for any prime p {\displaystyle {\displaystyle D(p)=1\;{\text{for any prime}}\;p}} . * D ( m n ) = D ( m ) n + m D ( n ) for any m , n ∈ N {\displaystyle {\displaystyle D(mn)=D(m)n+mD(n)\;{\text{for any}}\;m,n\in N}} . (Leibniz rule for derivatives).

Additionally, for negative integers the arithmetic derivative may be defined as

−
D
(
−
n
)

for

(
n
<
0
)
{\displaystyle {\displaystyle -D(-n)\;{\text{for}}\;(n<0)}}
.

Examples

D
(
2
)
=
1
{\displaystyle {\displaystyle D(2)=1}}
 and

D
(
3
)
=
1
{\displaystyle {\displaystyle D(3)=1}}
 (both are prime) so if

m
n
=
2
⋅
3
{\displaystyle {\displaystyle mn=2\cdot 3}}
, then

D
(
6
)
=
D
(
2
⋅
3
)
=
D
(
2
)
⋅
3
+
2
⋅
D
(
3
)
=
1
⋅
3
+
2
⋅
1
=
5
{\displaystyle {\displaystyle D(6)=D(2\cdot 3)=D(2)\cdot 3+2\cdot D(3)=1\cdot 3+2\cdot 1=5}}
.

D
(
9
)
=
D
(
3
)
⋅
3
+
3
⋅
D
(
3
)
=
1
⋅
3
+
3
⋅
1
=
6
{\displaystyle {\displaystyle D(9)=D(3)\cdot 3+3\cdot D(3)=1\cdot 3+3\cdot 1=6}}

D
(
27
)
=
D
(
3
)
⋅
9
+
3
⋅
D
(
9
)
=
1
⋅
9
+
3
⋅
6
=
27
{\displaystyle {\displaystyle D(27)=D(3)\cdot 9+3\cdot D(9)=1\cdot 9+3\cdot 6=27}}

D
(
30
)
=
D
(
5
)
⋅
6
+
5
⋅
D
(
6
)
=
1
⋅
6
+
5
⋅
5
=
31
{\displaystyle {\displaystyle D(30)=D(5)\cdot 6+5\cdot D(6)=1\cdot 6+5\cdot 5=31}}
.

Task

Find and show the arithmetic derivatives for -99 through 100.

Stretch task

Find (the arithmetic derivative of

10

m
{\displaystyle {\displaystyle 10^{m}}}
) then divided by 7, where m is from 1 to 20.

See also

* OEIS:A003415 - a(n) = n' = arithmetic derivative of n. * Wikipedia: Arithmetic Derivative

[Assistant]
```
use Prime::Factor;

multi D (0) { 0 }
multi D (1) { 0 }
multi D ($n where &is-prime) { 1 }
multi D ($n where * < 0 ) { -D -$n }
multi D ($n) { sum $n.&prime-factors.Bag.map: { $n × .value / .key } }

put (-99 .. 100).map(&D).batch(10)».fmt("%4d").join: "\n";

put '';

put join "\n", (1..20).map: { sprintf "D(10**%-2d) / 7 == %d", $_, D(10**$_) / 7 }

```

Output:

```
 -75  -77   -1 -272  -24  -49  -34  -96  -20 -123
  -1 -140  -32  -45  -22 -124   -1  -43 -108 -176
  -1  -71  -18  -80  -55  -39   -1 -156   -1  -59
 -26  -72   -1  -61  -18 -192  -51  -33   -1  -92
  -1  -31  -22  -92  -16  -81   -1  -56  -20  -45
 -14 -112   -1  -25  -39  -48   -1  -41   -1  -68
 -16  -21   -1  -60  -12  -19  -14  -80   -1  -31
  -1  -32  -27  -15  -10  -44   -1  -13  -10  -24
  -1  -21   -1  -32   -8   -9   -1  -16   -1   -7
  -6  -12   -1   -5   -1   -4   -1   -1    0    0
   0    1    1    4    1    5    1   12    6    7
   1   16    1    9    8   32    1   21    1   24
  10   13    1   44   10   15   27   32    1   31
   1   80   14   19   12   60    1   21   16   68
   1   41    1   48   39   25    1  112   14   45
  20   56    1   81   16   92   22   31    1   92
   1   33   51  192   18   61    1   72   26   59
   1  156    1   39   55   80   18   71    1  176
 108   43    1  124   22   45   32  140    1  123
  20   96   34   49   24  272    1   77   75  140

D(10**1 ) / 7 == 1
D(10**2 ) / 7 == 20
D(10**3 ) / 7 == 300
D(10**4 ) / 7 == 4000
D(10**5 ) / 7 == 50000
D(10**6 ) / 7 == 600000
D(10**7 ) / 7 == 7000000
D(10**8 ) / 7 == 80000000
D(10**9 ) / 7 == 900000000
D(10**10) / 7 == 10000000000
D(10**11) / 7 == 110000000000
D(10**12) / 7 == 1200000000000
D(10**13) / 7 == 13000000000000
D(10**14) / 7 == 140000000000000
D(10**15) / 7 == 1500000000000000
D(10**16) / 7 == 16000000000000000
D(10**17) / 7 == 170000000000000000
D(10**18) / 7 == 1800000000000000000
D(10**19) / 7 == 19000000000000000000
D(10**20) / 7 == 200000000000000000000
```


[User]
Create a program which parses and evaluates arithmetic expressions.

Requirements

* An abstract-syntax tree (AST) for the expression must be created from parsing the input.
* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
* The expression will be a string or list of symbols like "(1+3)\*7".
* The four symbols + - \* / must be supported as binary operators with conventional precedence rules.
* Precedence-control parentheses must also be supported.

Note

For those who don't remember, mathematical precedence is as follows:

* Parentheses
* Multiplication/Division (left to right)
* Addition/Subtraction (left to right)

C.f

* 24 game Player.
* Parsing/RPN calculator algorithm.
* Parsing/RPN to infix conversion.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
sub ev (Str $s --> Numeric) {

    grammar expr {
        token TOP { ^ <sum> $ }
        token sum { <product> (('+' || '-') <product>)* }
        token product { <factor> (('*' || '/') <factor>)* }
        token factor { <unary_minus>? [ <parens> || <literal> ] }
        token unary_minus { '-' }
        token parens { '(' <sum> ')' }
        token literal { \d+ ['.' \d+]? || '.' \d+ }
    }

    my sub minus ($b) { $b ?? -1 !! +1 }

    my sub sum ($x) {
        [+] flat product($x<product>), map
            { minus($^y[0] eq '-') * product $^y<product> },
            |($x[0] or [])
    }

    my sub product ($x) {
        [*] flat factor($x<factor>), map
            { factor($^y<factor>) ** minus($^y[0] eq '/') },
            |($x[0] or [])
    }

    my sub factor ($x) {
        minus($x<unary_minus>) * ($x<parens>
          ?? sum $x<parens><sum>
          !! $x<literal>)
    }

    expr.parse([~] split /\s+/, $s);
    $/ or fail 'No parse.';
    sum $/<sum>;

}

# Testing:

say ev '5';                                    #   5
say ev '1 + 2 - 3 * 4 / 5';                    #   0.6
say ev '1 + 5*3.4 - .5  -4 / -2 * (3+4) -6';   #  25.5
say ev '((11+15)*15)* 2 + (3) * -4 *1';        # 768

```


[User]
Definition

A positive integer **n** is an arithmetic number if the average of its positive divisors is also an integer.

Clearly all odd primes **p** must be arithmetic numbers because their only divisors are **1** and **p** whose sum is even and hence their average must be an integer. However, the prime number **2** is not an arithmetic number because the average of its divisors is 1.5.

Example

30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer.

Task

Calculate and show here:

1. The first 100 arithmetic numbers.

2. The **x**th arithmetic number where **x** = 1,000 and **x** = 10,000.

3. How many of the first **x** arithmetic numbers are composite.

Note that, technically, the arithmetic number **1** is neither prime nor composite.

Stretch

Carry out the same exercise in 2. and 3. above for **x** = 100,000 and **x** = 1,000,000.

References

* Wikipedia: Arithmetic number
* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer

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

my @arithmetic = lazy (1..∞).hyper.grep: { my @div = .&divisors; @div.sum %% @div }

say "The first { .Int.&cardinal } arithmetic numbers:\n", @arithmetic[^$_].batch(10)».fmt("%{.chars}d").join: "\n" given 1e2;

for 1e3, 1e4, 1e5, 1e6 {
    say "\nThe { .Int.&ordinal }: { comma @arithmetic[$_-1] }";
    say "Composite arithmetic numbers ≤ { comma @arithmetic[$_-1] }: { comma +@arithmetic[^$_].grep({!.is-prime}) - 1 }";
}

```

```
The first one hundred arithmetic numbers:
  1   3   5   6   7  11  13  14  15  17
 19  20  21  22  23  27  29  30  31  33
 35  37  38  39  41  42  43  44  45  46
 47  49  51  53  54  55  56  57  59  60
 61  62  65  66  67  68  69  70  71  73
 77  78  79  83  85  86  87  89  91  92
 93  94  95  96  97  99 101 102 103 105
107 109 110 111 113 114 115 116 118 119
123 125 126 127 129 131 132 133 134 135
137 138 139 140 141 142 143 145 147 149

The one thousandth: 1,361
Composite arithmetic numbers ≤ 1,361: 782

The ten thousandth: 12,953
Composite arithmetic numbers ≤ 12,953: 8,458

The one hundred thousandth: 125,587
Composite arithmetic numbers ≤ 125,587: 88,219

The one millionth: 1,228,663
Composite arithmetic numbers ≤ 1,228,663: 905,043
```


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

Task

Write a function to compute the arithmetic-geometric mean of two numbers.

The arithmetic-geometric mean of two numbers can be (usefully) denoted as

a
g
m
(
a
,
g
)
{\displaystyle {\displaystyle \mathrm {agm} (a,g)}}
, and is equal to the limit of the sequence:

:   a

    0
    =
    a
    ;

    g

    0
    =
    g
    {\displaystyle {\displaystyle a\_{0}=a;\qquad g\_{0}=g}}
:   a

    n
    +
    1
    =

    1
    2
    (

    a

    n
    +

    g

    n
    )
    ;

    g

    n
    +
    1
    =

    a

    n

    g

    n
    .
    {\displaystyle {\displaystyle a\_{n+1}={\tfrac {1}{2}}(a\_{n}+g\_{n});\quad g\_{n+1}={\sqrt {a\_{n}g\_{n}}}.}}

Since the limit of

a

n
−

g

n
{\displaystyle {\displaystyle a\_{n}-g\_{n}}}
 tends (rapidly) to zero with iterations, this is an efficient method.

Demonstrate the function by calculating:

:   a
    g
    m
    (
    1
    ,
    1

    /

    2
    )
    {\displaystyle {\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}}

Also see

* mathworld.wolfram.com/Arithmetic-Geometric Mean

[Assistant]
(formerly Perl 6)

```
sub agm( $a is copy, $g is copy ) {
    ($a, $g) = ($a + $g)/2, sqrt $a * $g until $a ≅ $g;
    return $a;
}

say agm 1, 1/sqrt 2;
```

Output:

```
0.84721308479397917
```

It's also possible to write it recursively:

```
sub agm( $a, $g ) {
    $a ≅ $g ?? $a !! agm(|@$_)
        given ($a + $g)/2, sqrt $a * $g;
}

say agm 1, 1/sqrt 2;
```

We can also get a bit fancy and use a converging sequence of complex numbers:

```
sub agm {
  ($^z, {(.re+.im)/2 + (.re*.im).sqrt*1i} ... * ≅ *)
  .tail.re
}

say agm 1 + 1i/2.sqrt
```


[User]
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate

π
{\displaystyle {\displaystyle \pi }}
.

With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:

π
=

4

a
g
m
(
1
,
1

/

2

)

2

1
−

∑

n
=
1

∞

2

n
+
1
(

a

n

2
−

g

n

2
)
{\displaystyle {\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits \_{n=1}^{\infty }2^{n+1}(a\_{n}^{2}-g\_{n}^{2})}}}}

This allows you to make the approximation, for any large   **N**:

π
≈

4

a

N

2

1
−

∑

k
=
1

N

2

k
+
1
(

a

k

2
−

g

k

2
)
{\displaystyle {\displaystyle \pi \approx {\frac {4\;a\_{N}^{2}}{1-\sum \limits \_{k=1}^{N}2^{k+1}(a\_{k}^{2}-g\_{k}^{2})}}}}

The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of

π
{\displaystyle {\displaystyle \pi }}
.

[Assistant]
(formerly Perl 6)

**Translation of**: Ruby

There is not yet a FixDecimal type module in Raku, and using FatRat all along would be too slow and would be coerced to Num when computing the square root anyway, so we'll use a custom definition of the square root for Int and FatRat, with a limitation to the number of decimals. We'll show all the intermediate results.

The trick to compute the square root of a rational

n
d
{\displaystyle {\displaystyle n \over d}}
 up to a certain amount of decimals N is to write:

n
d
=

n

10

2
N

/
d

d

10

2
N

/
d
=

n

10

2
N

/
d

10

N
{\displaystyle {\displaystyle {\sqrt {\frac {n}{d}}}={\sqrt {\frac {n10^{2N}/d}{d10^{2N}/d}}}={\frac {\sqrt {n10^{2N}/d}}{10^{N}}}}}

so that what we need is one square root of a big number that we'll truncate to its integer part. We'll use the method described in Integer roots to compute the square root of this big integer.

Notice that we don't get the exact number of decimals required : the last two decimals or so can be wrong. This is because we don't need

a

n
{\displaystyle {\displaystyle a\_{n}}}
, but rather

a

n

2
{\displaystyle {\displaystyle a\_{n}^{2}}}
. Elevating to the square makes us lose a bit of precision. It could be compensated by choosing a slightly higher value of N (in a way that could be precisely calculated), but that would probably be overkill.

```
constant number-of-decimals = 100;

multi sqrt(Int $n) {
  (10**($n.chars div 2), { ($_ + $n div $_) div 2 } ... * == *).tail
}

multi sqrt(FatRat $r --> FatRat) {
  return FatRat.new:
    sqrt($r.numerator * 10**(number-of-decimals*2) div $r.denominator),
    10**number-of-decimals;
}

my FatRat ($a, $n) = 1.FatRat xx 2;
my FatRat $g = sqrt(1/2.FatRat);
my $z = .25;

for ^10 {
  given [ ($a + $g)/2, sqrt($a * $g) ] {
    $z -= (.[0] - $a)**2 * $n;
    $n += $n;
    ($a, $g) = @$_;
    say ($a ** 2 / $z).substr: 0, 2 + number-of-decimals;
  }
}

```

Output:

```
3.1876726427121086272019299705253692326510535718593692264876339862751228325281223301147286106601617972
3.1416802932976532939180704245600093827957194388154028326441894631956630010102553193888894275152646100
3.1415926538954464960029147588180434861088792372613115896511013576846530795030865017740975862898631567
3.1415926535897932384663606027066313217577024113424293564868460152384109486069277582680622007332762125
3.1415926535897932384626433832795028841971699491647266058346961259487480060953290058518515759317101932
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280468522286541140
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170668
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170665
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170664
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170663

```


[User]
A   **complex number**   is a number which can be written as:

a
+
b
×
i
{\displaystyle {\displaystyle a+b\times i}}
(sometimes shown as:

b
+
a
×
i
{\displaystyle {\displaystyle b+a\times i}}
where

a
{\displaystyle {\displaystyle a}}
   and

b
{\displaystyle {\displaystyle b}}
  are real numbers,   and
i
{\displaystyle {\displaystyle i}}
  is   √ -1

Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part",   where the imaginary part is the number to be multiplied by

i
{\displaystyle {\displaystyle i}}
.

Task

* Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
* Print the results for each operation tested.
* *Optional:* Show complex conjugation.

By definition, the   complex conjugate   of

a
+
b
i
{\displaystyle {\displaystyle a+bi}}
is

a
−
b
i
{\displaystyle {\displaystyle a-bi}}

Some languages have complex number libraries available.   If your language does, show the operations.   If your language does not, also show the definition of this type.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
my $a = 1 + i;
my $b = pi + 1.25i;

.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj;
.say for $a.abs, $a.sqrt, $a.re, $a.im;

```

Output:

(precision varies with different implementations)

```
4.1415926535897931+2.25i
1.8915926535897931+4.3915926535897931i
-1-1i
0.5-0.5i
1-1i
1.4142135623730951
1.0986841134678098+0.45508986056222733i
1
1

```


[User]
Task

Get two integers from the user,   and then (for those two integers), display their:

:   :   :   :   * sum
                * difference
                * product
                * integer quotient
                * remainder
                * exponentiation   (if the operator exists)

Don't include error handling.

For quotient, indicate how it rounds   (e.g. towards zero, towards negative infinity, etc.).

For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.

Bonus: Include an example of the integer `divmod` operator. For example: as in #Haskell, #Python and #ALGOL 68

[Assistant]
(formerly Perl 6)

Note that `div` **requires** integer arguments. If you want integer division with other types, say `floor($a/$b)`.

```
my Int $a = get.floor;
my Int $b = get.floor;

say 'sum:              ', $a + $b;
say 'difference:       ', $a - $b;
say 'product:          ', $a * $b;
say 'integer quotient: ', $a div $b;
say 'remainder:        ', $a % $b;
say 'exponentiation:   ', $a**$b;
```


[User]
Task

Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.

Example

Define a new type called **frac** with binary operator "//" of two integers that returns a **structure** made up of the numerator and the denominator (as per a rational number).

Further define the appropriate rational unary **operators** **abs** and '-', with the binary **operators** for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').

Define standard coercion **operators** for casting **int** to **frac** etc.

If space allows, define standard increment and decrement **operators** (e.g. '+:=' & '-:=' etc.).

Finally test the operators:
Use the new type **frac** to find all perfect numbers less than 219 by summing the reciprocal of the factors.

Related tasks

* Perfect Numbers
* Check Machin-like formulas

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.08

Raku supports rational arithmetic natively.

```
(2..2**19).hyper.map: -> $candidate {
    my $sum = 1 / $candidate;
    for 2 .. ceiling(sqrt($candidate)) -> $factor {
        if $candidate %% $factor {
            $sum += 1 / $factor + 1 / ($candidate / $factor);
        }
    }
    if $sum.nude[1] == 1 {
        say "Sum of reciprocal factors of $candidate = $sum exactly", ($sum == 1 ?? ", perfect!" !! ".");
    }
}

```

Note also that ordinary decimal literals are stored as Rats, so the following loop always stops exactly on 10 despite 0.1 not being exactly representable in floating point:

```
for 1.0, 1.1, 1.2 ... 10 { .say }

```

The arithmetic is all done in rationals, which are converted to floating-point just before display so that people don't have to puzzle out what 53/10 means.


[User]
Task

Show how to concatenate two arrays in your language.

If this is as simple as `array1 + array2`, so be it.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.06

```
my @array1 = 1, 2, 3;
my @array2 = 4, 5, 6;

# If you want to concatenate two array to form a third,
# either use the slip operator "|", to flatten each array.

my @array3 = |@array1, |@array2;
say @array3;

# or just flatten both arrays in one fell swoop

@array3 = flat @array1, @array2;
say @array3;

# On the other hand, if you just want to add the elements
# of the second array to the first, use the .append method.

say @array1.append: @array2;
```

Output:

```
[1 2 3 4 5 6]
[1 2 3 4 5 6]
[1 2 3 4 5 6]
```