[User]
Task

Determine the number of elements in an array.

As an example use an array holding the strings 'apple' and 'orange'.

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 2017.04

To get the number of elements of an array in Raku you put the array in a coercing Numeric context, or call `elems` on it.

```
my @array = <apple orange>;

say @array.elems;  # 2
say elems @array;  # 2
say + @array;      # 2
say @array + 0;    # 2
```

Watch out for infinite/lazy arrays though. You can't get the length of those.

```
my @infinite = 1 .. Inf;  # 1, 2, 3, 4, ...

say @infinite[5000];  # 5001
say @infinite.elems;  # Throws exception "Cannot .elems a lazy list"
```


[User]
This task is about arrays.

For hashes or associative arrays, please see Creating an Associative Array.

For a definition and in-depth discussion of what an array is, see Array.

Task

Show basic array syntax in your language.

Basically, create an array, assign a value to it, and retrieve an element   (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).

Please discuss at Village Pump:   Arrays.

Please merge code in from these obsolete tasks:

:   :   :   * Creating an Array
            * Assigning Values to an Array
            * Retrieving an Element of an Array

Related tasks

* Collections
* Creating an Associative Array
* Two-dimensional array (runtime)

[Assistant]
(formerly Perl 6)
At its most basic, an array in Raku is quite similar to an array in Perl 5.

```
my @arr;

push @arr, 1;
push @arr, 3;

@arr[0] = 2;

say @arr[0];
```

### Some further exposition:

In Raku, arrays have a very specific definition: "A collection of Scalar containers that do the Positional Role." Scalar container means it is mutable and may contain any object; an Integer, a Rational number, a String, another Array, whatever... literally any other object that can be instantiated in Raku. The Positional Role means that it uses integer indexing for access. The index must be a positive integer, an expression that evaluates to a positive integer, or something that can be coerced to a positive integer. Arrays are always indexed from 0. The starting index can not be changed.

Arrays are unconstrained by default. They may hold any number of any type of object up to available memory. They do not need to be pre-allocated. Simply assigning (or even referring in some cases) to an index slot is enough to autovivify the container and allocate enough memory to hold the assigned object. Memory will automatically be allocated and will grow and shrink as necessary to hold the values assigned.

Values may be pushed onto the end of an array, popped off of the end, shifted off of the front or unshifted onto the front, and spliced into or out of the interior.

```
   @array.push: 'value';
   my $value = @array.pop;
   @array.unshift: 'value';
   my $value = @array.shift;
   @array.splice(2,3, <some arbitrary string values>);

```

Arrays may be constrained to only accept a certain number of objects or only a certain type of object.

```
   my Int @array; # can only hold Integer objects. Assigning any other type will cause an exception.
   my @array[9];  # can only 10 objects (zero indexed). Trying to assign to an index greater than 9 with cause an exception.

```

Arrays are constructed with square brackets, an explicit constructor, or by coercing some other object either explicitly using a coercer or implicitly by simply assigning to an array variable. These are all arrays:

```
   [1, 2, 3, 4]
   ['a', 'b', 'c', 'd']
   Array.new<this is an array of words>
   ('as', 'is', 'this').Array
   my @implicit = <yep, this too>

```

Array variables in Raku are variables whose names bear the @ sigil, and are expected to contain some sort of list-like object. Of course, other variables may also contain these objects, but @-sigiled variables always do, and are expected to act the part. Array storage slots are accessed through postcircumfix square bracket notation. Unlike Perl 5, @-sigiled variables are invariant on access, whether you are accessing one slot, many slots, or all of the slots. The first slot in @array is @array[0] not $array[0]. @array and $array are two different unconnected variables.

```
   @array[1]      # a single value in the 2nd slot
   @array[*-1]    # a single value in the last slot
   @array[1..5]   # an array slice, 2nd through 6th slots
   @array[1,3,7]  # slice, 2nd, 4th and 8th slot
   @array[8,5,2]  # can be in any order
   @array[*]      # all the slots
   @array[]       # all the slots (zen slice)
   @array[^10]    # first 10 slots (upto 10 or 0..9)
   @array.head(5) # first 5 slots
   @array.tail(2) # last two

```

Multi-dimensioned arrays also use postcircumfix square brackets for access. If the array is not ragged, (every sub array is the same size) you may use semicolon subscripting.

```
   @array[1][1]   # 2nd item in the second slot
   @array[1;1]    # same thing, implies rectangular (non-ragged) arrays

```

There are several objects that have an Iterable Role and a PositionalBindFailover Role which makes them act similar to arrays and allows them to be used nearly interchangeably in read-only applications. (Raku is big on duck typing. "If it looks like a duck and quacks like a duck and waddles like a duck, it's a duck.") These constructs are ordered and use integer indexing and are often used in similar circumstances as arrays, however, **they are immutable**. Values in slots can not be changed. They can not be pushed to, popped from or spliced. They can easily converted to arrays by simply assigning them to an array variable.

**List**: A fixed Iterable collection of immutable values. Lists are constructed similarly to arrays:

```
   (1, 2, 3, 4)
   ('a', 'b', 'c', 'd')
   List.new(<this is a list of words>)
   ('as', 'is', 'this').List
   my @not-a-list = (<oops, this isn't>)
   my @implicit := (<but this is>) # note the values are bound := not assigned =

```

**Range**: Iterable list of consecutive numbers or strings with a lower and an upper boundary. (That boundary may be infinite.) Reified on demand.

```
   2..20    # integers two through twenty
   1..Inf   # natural numbers
   'a'..'z' # lowercase latin letters

```

**Sequence**: Iterable list of objects with some method to determine the next (or previous) item in the list. Reified on demand. Will try to automatically deduce simple arithmetic or geometric sequences. Pass in a code object to calculate more complex sequences.

```
  0,2,4 ... 64   # even numbers up to 64
  1,2,4 ... 64   # geometric increase
  1,1, *+* ... * # infinite Fibonacci sequence
  1,1,{$^n2 + $^n1 + 1} ... * # infinite Leonardo numbers

```

Postcircumfix indexing works for any object that has a Positional (or PositionalBindFailover) role, it need not be in a @-sigiled variable, or indeed, in a variable at all.

```
   [2,4,6,8,10][1]                             # 4 - anonymous array
   <my dog has fleas>[*-2]                     # 'has' - anonymous list
   sub a {(^Inf).grep: *.is-prime}; a()[99];   # 541 - (100th prime) subroutine returning a sequence
   my $lol = ((1,2), (3,4), (5,6)); $lol[1];   # (3 4) - list of lists in a Scalar variable

```


[User]
Generate and show all primes with strictly ascending decimal digits.

Aside: Try solving without peeking at existing solutions. I had a weird idea for generating
a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial
but generating them quickly is at least mildly interesting.
Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is
at least one significantly better and much faster way, needing a mere 511 odd/prime tests.

See also

* OEIS:A052015 - Primes with distinct digits in ascending order

Related

* Primes with digits in nondecreasing order (infinite series allowing duplicate digits, whereas this isn't and doesn't)
* Pandigital prime (whereas this is the smallest, with gaps in the used digits being permitted)
* Descending primes

[Assistant]
```
put (flat 2, 3, 5, 7, sort +*, gather (1..8).map: &recurse ).batch(10)».fmt("%8d").join: "\n";

sub recurse ($str) {
    .take for ($str X~ (3, 7, 9)).grep: { .is-prime && [<] .comb };
    recurse $str × 10 + $_ for $str % 10 ^.. 9;
}

printf "%.3f seconds", now - INIT now;

```

Output:

```
       2        3        5        7       13       17       19       23       29       37
      47       59       67       79       89      127      137      139      149      157
     167      179      239      257      269      347      349      359      367      379
     389      457      467      479      569     1237     1249     1259     1279     1289
    1367     1459     1489     1567     1579     1789     2347     2357     2389     2459
    2467     2579     2689     2789     3457     3467     3469     4567     4679     4789
    5689    12347    12379    12457    12479    12569    12589    12689    13457    13469
   13567    13679    13789    15679    23459    23567    23689    23789    25679    34589
   34679   123457   123479   124567   124679   125789   134789   145679   234589   235679
  235789   245789   345679   345689  1234789  1235789  1245689  1456789 12356789 23456789
0.075 seconds
```


[User]
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:
http://www.ietf.org/rfc/rfc1035.txt

```
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      ID                       |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    QDCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ANCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    NSCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ARCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

```

Where (every column of the table is 1 bit):

```
ID is 16 bits
QR = Query (0) or Response (1)
Opcode = Four bits defining kind of query:
  0:    a standard query (QUERY)
  1:    an inverse query (IQUERY)
  2:    a server status request (STATUS)
  3-15: reserved for future use
AA = Authoritative Answer bit
TC = Truncation bit
RD = Recursion Desired bit
RA = Recursion Available bit
Z = Reserved
RCODE = Response code
QC = Question Count
ANC = Answer Count
AUC = Authority Count
ADC = Additional Count

```

Write a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.

If your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.

Such "Header" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars "+--+". The code should perform a little of validation of the input string, but for brevity a full validation is not required.

Bonus: perform a thoroughly validation of the input string.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.05

```
grammar RFC1025 {
    rule  TOP {  <.line-separator> [<line> <.line-separator>]+ }
    rule  line-separator { <.ws> '+--'+ '+' }
    token line  { <.ws> '|' +%% <field>  }
    token field  { \s* <label> \s* }
    token label { \w+[\s+\w+]* }
}

sub bits ($item) { ($item.chars + 1) div 3 }

sub deconstruct ($bits, %struct) {
    map { $bits.substr(.<from>, .<bits>) }, @(%struct<fields>);
}

sub interpret ($header) {
    my $datagram = RFC1025.parse($header);
    my %struct;
    for $datagram.<line> -> $line {
        FIRST %struct<line-width> = $line.&bits;
        state $from = 0;
        %struct<fields>.push: %(:bits(.&bits), :ID(.<label>.Str), :from($from.clone), :to(($from+=.&bits)-1))
          for $line<field>;
    }
    %struct
}

use experimental :pack;

my $diagram = q:to/END/;

    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    |                      ID                       |
    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    |                    QDCOUNT                    |
    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    |                    ANCOUNT                    |
    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    |                    NSCOUNT                    |
    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    |                    ARCOUNT                    |
    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

END

my %structure = interpret($diagram);

say 'Line width: ', %structure<line-width>, ' bits';
printf("Name: %7s, bit count: %2d, bit %2d to bit %2d\n", .<ID>, .<bits>, .<from>, .<to>) for @(%structure<fields>);
say "\nGenerate a random 12 byte \"header\"";
say my $buf = Buf.new((^0xFF .roll) xx 12);
say "\nShow it converted to a bit string";
say my $bitstr = $buf.unpack('C*')».fmt("%08b").join;
say "\nAnd unpack it";
printf("%7s, %02d bits: %s\n", %structure<fields>[$_]<ID>,  %structure<fields>[$_]<bits>,
  deconstruct($bitstr, %structure)[$_]) for ^@(%structure<fields>);

```

Output:

```
Line width: 16 bits
Name:      ID, bit count: 16, bit  0 to bit 15
Name:      QR, bit count:  1, bit 16 to bit 16
Name:  Opcode, bit count:  4, bit 17 to bit 20
Name:      AA, bit count:  1, bit 21 to bit 21
Name:      TC, bit count:  1, bit 22 to bit 22
Name:      RD, bit count:  1, bit 23 to bit 23
Name:      RA, bit count:  1, bit 24 to bit 24
Name:       Z, bit count:  3, bit 25 to bit 27
Name:   RCODE, bit count:  4, bit 28 to bit 31
Name: QDCOUNT, bit count: 16, bit 32 to bit 47
Name: ANCOUNT, bit count: 16, bit 48 to bit 63
Name: NSCOUNT, bit count: 16, bit 64 to bit 79
Name: ARCOUNT, bit count: 16, bit 80 to bit 95

Generate a random 12 byte "header"
Buf:0x<78 47 7b bf 54 96 e1 2e 1b f1 69 a4>

Show it converted to a bit string
011110000100011101111011101111110101010010010110111000010010111000011011111100010110100110100100

And unpack it
     ID, 16 bits: 0111100001000111
     QR, 01 bits: 0
 Opcode, 04 bits: 1111
     AA, 01 bits: 0
     TC, 01 bits: 1
     RD, 01 bits: 1
     RA, 01 bits: 1
      Z, 03 bits: 011
  RCODE, 04 bits: 1111
QDCOUNT, 16 bits: 0101010010010110
ANCOUNT, 16 bits: 1110000100101110
NSCOUNT, 16 bits: 0001101111110001
ARCOUNT, 16 bits: 0110100110100100
```


[User]
ASCII is the American Standard Code for Information Interchange. There are 128 ASCII characters of which the first 32 and the last are 'control characters'.

Task

Show how your language might treat control characters *en bloc* by using an enum, an enum like structure or other approach to associate their names with their ASCII values thereby enabling them to be retrieved or listed by name.

Technically, the 33rd character 'space' is a printable character, not a control character, though you may treat it as the latter for the purposes of this task.

Reference

* Wikipedia: ASCII

[Assistant]
There doesn't seem to really be a point or a purpose to this task other than creating a enumeration...

'space' is absolutely **NOT** a control character. Pretending it is is just completely incorrect.

```
enum C0 (|(^32).map({ (0x2400 + $_).chr => $_ }), '␡' => 127);

printf "Ord: %3d, Unicode: %s, Enum: %s\n", $_, .uniname, C0($_)
   for (^128).grep: {.chr ~~ /<:Cc>/}

```

Output:

```
Ord:   0, Unicode: <control-0000>, Enum: ␀
Ord:   1, Unicode: <control-0001>, Enum: ␁
Ord:   2, Unicode: <control-0002>, Enum: ␂
Ord:   3, Unicode: <control-0003>, Enum: ␃
Ord:   4, Unicode: <control-0004>, Enum: ␄
Ord:   5, Unicode: <control-0005>, Enum: ␅
Ord:   6, Unicode: <control-0006>, Enum: ␆
Ord:   7, Unicode: <control-0007>, Enum: ␇
Ord:   8, Unicode: <control-0008>, Enum: ␈
Ord:   9, Unicode: <control-0009>, Enum: ␉
Ord:  10, Unicode: <control-000A>, Enum: ␊
Ord:  11, Unicode: <control-000B>, Enum: ␋
Ord:  12, Unicode: <control-000C>, Enum: ␌
Ord:  13, Unicode: <control-000D>, Enum: ␍
Ord:  14, Unicode: <control-000E>, Enum: ␎
Ord:  15, Unicode: <control-000F>, Enum: ␏
Ord:  16, Unicode: <control-0010>, Enum: ␐
Ord:  17, Unicode: <control-0011>, Enum: ␑
Ord:  18, Unicode: <control-0012>, Enum: ␒
Ord:  19, Unicode: <control-0013>, Enum: ␓
Ord:  20, Unicode: <control-0014>, Enum: ␔
Ord:  21, Unicode: <control-0015>, Enum: ␕
Ord:  22, Unicode: <control-0016>, Enum: ␖
Ord:  23, Unicode: <control-0017>, Enum: ␗
Ord:  24, Unicode: <control-0018>, Enum: ␘
Ord:  25, Unicode: <control-0019>, Enum: ␙
Ord:  26, Unicode: <control-001A>, Enum: ␚
Ord:  27, Unicode: <control-001B>, Enum: ␛
Ord:  28, Unicode: <control-001C>, Enum: ␜
Ord:  29, Unicode: <control-001D>, Enum: ␝
Ord:  30, Unicode: <control-001E>, Enum: ␞
Ord:  31, Unicode: <control-001F>, Enum: ␟
Ord: 127, Unicode: <control-007F>, Enum: ␡

```


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

The main goal of Aspect Oriented Programming (AOP) is to keep all the code relating to a single feature in one module of code.

There are a variety of ways to achieve this with object-oriented programming and functional programming, including inheritance, decorators and configuration trees.

In Aspect Oriented Programming existing code is extended with new behaviors invisibly, by means of stealthy instrumentation. There are some similarities between this concept and some debugging tools, such as Linux Kernel Probes. In fact, one obvious application for AOP is to add detailed tracing, with access to data, without touching the instrumented code. An aspect could be used to capture the calls to an entire API and log the arguments and return values.

The idea is that when the instrumented function is executes, either prior the execution of function, or at its point of return, or both, a block of code in instrumenting module is able to gain control. It can obtain access to the function arguments almost as if it were its own arguments, execute its own logic, and even decide whether or not the instrumented function will run at all, and with what argument values, and what it shall return.

Furthermore, there can be additional refinements, such as instrumenting calls to some function A, but only when it is directly called by function B. Or only when function B is somewhere in the activation chain, etc.

Also part of AOP is the idea of instrumenting data structures such as classes. An "aspect" is a hidden extension to some existing set of classes, which adds hidden new instance variables to the class. These variables are not accessible by the class itself, only by the instrumenting Aspect code. An object-oriented Aspect resembles a class, except that its instance variables are injected into another class (or classes!), and its methods are instrumenting hooks that capture control from the methods of other classes.

An Aspect Oriented Programming System provides the abstractions to make this happen: a way to write aspects which specify what classes and methods they instrument, and the code, data and activation rules for doing it.

AOP introduces some new terms. A "join point" is a place in the control flow where code is instrumented, like a function call or return. A "point cut" is a selection of join points according to some query, which are tied to a common instrumenting code. (A single instrumenting function can handle a large point cut of different join points.)

AOP allows for a "separation of concerns" because new features are introduced as aspects tied to the execution of existing code, but without touching any of it, thereby keeping code bases completely separate. For instance, a mutex locking discipline can be added to a class without touching any of its code. An aspect identifies the methods that need locking, introduces the mutex variable into every instance of every instrumented class, and gains control around the invocations of the targetted methods to manage the mutex. Without AOP, the concern for locking is spread everywhere. Mutex lock/unlock calls have to be written or at the very least, methods have to be declared as synchronized, and this is repeated in every class that requires locking.

Task

The task is to describe or show how, or to what extent, a given programming language implements, or is able to implement or simulate, Aspect Oriented Programming.

[Assistant]
(formerly Perl 6)

All methods in Raku are really just routines under the control of the meta-object protocol for purposes of dispatch, so there are several ways to subvert the system in order to deal with aspects. First, you could intercept the MOP calls, or you could install alternate metaclasses. More likely, since methods are really just routines in disguise, and since a routine can be wrapped (in place) in an outer routine via the .wrap method, you'd just wrap all the methods and other routines that share a cross-cutting concern.

Note that the optimizer is free to assume routines are immutable after CHECK time (the end of compilation), so while you can always wrap routines during compile time, you might need a "use soft" declaration or some such to enable wrapping at run time, that is, in order to keep considering the routine to be mutable. (Only code doing the Routine role is ever mutable in Raku—bare blocks and other lambdas are considered immutable from the start.) Note that keeping routines mutable is likely to pessimize spots where the optimizer might otherwise be able to inline the code.

Of course, you can also simply redefine Raku on the fly to be any language you want in the current lexical scope, so you are really only limited by your imagination in how you wish to express these "aspects", whatever you might mean by that term…


[User]
Assertions are a way of breaking out of code when there is an error or an unexpected input.

Some languages throw exceptions and some treat it as a break point.

Task

Show an assertion in your language by asserting that an integer variable is equal to **42**.

[Assistant]
(formerly Perl 6)

```
my $a = (1..100).pick;
$a == 42 or die '$a ain\'t 42';

```


[User]
According to   Wikipedia;   assertions can function as a form of documentation:   they can describe the state the code expects to find before it runs (its preconditions), and the state the code expects to result in when it is finished running (postconditions);   they can also specify invariants of a class.

Task

Show in the program language of your choice an example of the use of assertions as a form of documentation.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.05

Most of theses entries seem to have missed the point. This isn't about how to implement or use assertions, it is about how the language uses design-by-contract to help the programmer get correct results.

Raku doesn't have an assert routine in CORE. You could easily add one; several modules geared toward unit testing supply various "assertion" routines, though I'm not aware of any actually specifically named "assert()".

Raku core has subroutine signatures, multi-dispatch and exceptions to implement design-by-contract.

Subroutine signature allow the programmer to make the parameters supplied to a routine be checked to make sure they are the of correct quantity, type, and value and can constrain the returned value(s) to a particular type. See the below snippet for a brief demonstration. Raku does some static analysis to trap errors at compile time, but traps many errors at run time since it is often impossible to tell if a variable is of the correct type before the program is run.

When Raku encounters a design-by-contract violation, it will fail with an error message telling where the problem occurred, what it expected and what it actually got. Some failures are trappable and resumeable. Failures may be trapped by adding a CATCH { } block in the current scope. Failures will transfer execution to the CATCH block where the failure may be analysed and further action taken. Depending on the failure type, execution may be resumable. Some failures cause execution to halt unavoidably.

In this snippet, the routine repeat takes one Integer that must be greater than 1, a String and returns a String. (Note that as written, it is incorrect since it actually returns a boolean.)

```
sub repeat ( Int $repeat where * > 1, Str $message, --> Str ) {
    say $message x $repeat;
    True # wrong return type
}

repeat( 2, 'A' ); # parameters ok, return type check error

repeat( 4, 2 ); # wrong second parameter type

repeat( 'B', 3 ); # wrong first (and second) parameter type

repeat( 1, 'C' ); # constraint check fail

repeat( ); # wrong number of parameters

CATCH {
    default {
        say "Error trapped: $_";
        .resume;
    }
}

```

Output:

```
AA
Error trapped: Type check failed for return value; expected Str but got Bool (Bool::True)
Error trapped: Type check failed in binding to parameter '$message'; expected Str but got Int (2)
Error trapped: Type check failed in binding to parameter '$repeat'; expected Int but got Str ("B")
Error trapped: Constraint type check failed in binding to parameter '$repeat'; expected anonymous constraint to be met but got Int (1)
Error trapped: Too few positionals passed; expected 2 arguments but got 0
This exception is not resumable
  in block  at contract.p6 line 19
  in block <unit> at contract.p6 line 14

```


[User]
Task

The goal is to create an associative array (also known as a dictionary, map, or hash).

Related tasks:

* Associative arrays/Iteration
* Hash from two arrays

See also

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

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

The fatarrow, `=>`, is no longer just a quoting comma; it now constructs a `Pair` object. But you can still define a hash with an ordinary list of even length.

```
my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3';

# Creating a hash from two lists using a metaoperator.

my @a = 1..5;
my @b = 'a'..'e';
my %h = @a Z=> @b;

# Hash elements and hash slices now use the same sigil as the whole hash. This is construed as a feature.
# Curly braces no longer auto-quote, but Raku's qw (shortcut < ... >) now auto-subscripts.

say %h1{'key1'};
say %h1<key1>;
%h1<key1> = 'val1';
%h1<key1 three> = 'val1', -238.83;

# Special syntax is no longer necessary to access a hash stored in a scalar.

my $h = {key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3'};
say $h<key1>;

# Keys are of type Str or Int by default. The type of the key can be provided.

my %hash{Any}; # same as %hash{*}
class C {};
my %cash{C};
%cash{C.new} = 1;
```


[User]
Show how to iterate over the key-value pairs of an associative array, and print each pair out.

Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.

See also

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

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
my %pairs = hello => 13, world => 31, '!' => 71;

for %pairs.kv -> $k, $v {
    say "(k,v) = ($k, $v)";
}

# Stable order
for %pairs.sort(*.value)>>.kv -> ($k, $v) {
    say "(k,v) = ($k, $v)";
}

{ say "$^a => $^b" } for %pairs.kv;

say "key = $_" for %pairs.keys;

say "value = $_" for %pairs.values;
```


[User]
Task

Define two associative arrays, where one represents the following "base" data:

:   :   :   :   :   |  |  |
                    | --- | --- |
                    | **Key** | **Value** |
                    | "name" | "Rocket Skates" |
                    | "price" | 12.75 |
                    | "color" | "yellow" |

And the other represents "update" data:

:   :   :   :   :   |  |  |
                    | --- | --- |
                    | **Key** | **Value** |
                    | "price" | 15.25 |
                    | "color" | "red" |
                    | "year" | 1974 |

Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:

:   :   :   :   :   |  |  |
                    | --- | --- |
                    | **Key** | **Value** |
                    | "name" | "Rocket Skates" |
                    | "price" | 15.25 |
                    | "color" | "red" |
                    | "year" | 1974 |

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

I must say I somewhat disagree with the terminology. The requested operation is an update not a merge. Demonstrate both an update and a merge. Associative arrays are commonly called hashes in Raku.

```
# Show original hashes
say my %base   = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;

# Need to assign to anonymous hash to get the desired results and avoid mutating
# TIMTOWTDI
say "\nUpdate:\n", join "\n", sort %=%base, %update;
# Same
say "\nUpdate:\n", {%base, %update}.sort.join: "\n";

say "\nMerge:\n", join "\n", sort ((%=%base).push: %update)».join: ', ';
# Same
say "\nMerge:\n", ({%base}.push: %update)».join(', ').sort.join: "\n";

# Demonstrate unmutated hashes
say "\n", %base, "\n", %update;

```

Output:

```
{color => yellow, name => Rocket Skates, price => 12.75}
{color => red, price => 15.25, year => 1974}

Update:
color	red
name	Rocket Skates
price	15.25
year	1974

Update:
color	red
name	Rocket Skates
price	15.25
year	1974

Merge:
color	yellow, red
name	Rocket Skates
price	12.75, 15.25
year	1974

Merge:
color	yellow, red
name	Rocket Skates
price	12.75, 15.25
year	1974

{color => yellow, name => Rocket Skates, price => 12.75}
{color => red, price => 15.25, year => 1974}
```


[User]
Task

Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:

1. get the current value of any bucket
2. remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative

---

In order to exercise this data type, create one set of buckets, and start three concurrent tasks:

1. As often as possible, pick two buckets and make their values closer to equal.
2. As often as possible, pick two buckets and arbitrarily redistribute their values.
3. At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.

The display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.

---

This task is intended as an exercise in *atomic* operations.   The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is *atomic*.

[Assistant]
(formerly Perl 6)

**Translation of**: Ruby

**Works with**: Rakudo version 2016.07

```
#| A collection of non-negative integers, with atomic operations.
class BucketStore {

  has $.elems is required;
  has @!buckets = ^1024 .pick xx $!elems;
  has $lock     = Lock.new;

  #| Returns an array with the contents of all buckets.
  method buckets {
    $lock.protect: { [@!buckets] }
  }

  #| Transfers $amount from bucket at index $from, to bucket at index $to.
  method transfer ($amount, :$from!, :$to!) {
    return if $from == $to;

    $lock.protect: {
      my $clamped = $amount min @!buckets[$from];

      @!buckets[$from] -= $clamped;
      @!buckets[$to]   += $clamped;
    }
  }
}

# Create bucket store
my $bucket-store = BucketStore.new: elems => 8;
my $initial-sum = $bucket-store.buckets.sum;

# Start a thread to equalize buckets
Thread.start: {
  loop {
    my @buckets = $bucket-store.buckets;

    # Pick 2 buckets, so that $to has not more than $from
    my ($to, $from) = @buckets.keys.pick(2).sort({ @buckets[$_] });

    # Transfer half of the difference, rounded down
    $bucket-store.transfer: ([-] @buckets[$from, $to]) div 2, :$from, :$to;
  }
}

# Start a thread to distribute values among buckets
Thread.start: {
  loop {
    my @buckets = $bucket-store.buckets;

    # Pick 2 buckets
    my ($to, $from) = @buckets.keys.pick(2);

    # Transfer a random portion
    $bucket-store.transfer: ^@buckets[$from] .pick, :$from, :$to;
  }
}

# Loop to display buckets
loop {
  sleep 1;

  my @buckets = $bucket-store.buckets;
  my $sum = @buckets.sum;

  say "{@buckets.fmt: '%4d'}, total $sum";

  if $sum != $initial-sum {
    note "ERROR: Total changed from $initial-sum to $sum";
    exit 1;
  }
}

```

Output:

```
  23   52  831  195 1407  809  813   20, total 4150
1172   83  336  306  751  468  615  419, total 4150
 734  103 1086   88  313  136 1252  438, total 4150
 512  323  544  165  200    3 2155  248, total 4150
...

```


[User]
A number is an   *attractive number*   if the number of its prime factors (whether distinct or not) is also prime.

Example

The number   **20**,   whose prime decomposition is   **2 × 2 × 5**,   is an   *attractive number*   because the number of its prime factors   (**3**)   is also prime.

Task

Show sequence items up to   **120**.

Reference
:   * The OEIS entry:   A063989: Numbers with a prime number of prime divisors.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

This algorithm is concise but not really well suited to finding large quantities of consecutive attractive numbers. It works, but isn't especially speedy. More than a hundred thousand or so gets tedious. There are other, much faster (though more verbose) algorithms that *could* be used. This algorithm **is** well suited to finding **arbitrary** attractive numbers though.

```
use Lingua::EN::Numbers;
use ntheory:from<Perl5> <factor is_prime>;

sub display ($n,$m) { ($n..$m).grep: (~*).&factor.elems.&is_prime }

sub count ($n,$m) { +($n..$m).grep: (~*).&factor.elems.&is_prime }

# The Task
put "Attractive numbers from 1 to 120:\n" ~
display(1, 120)».fmt("%3d").rotor(20, :partial).join: "\n";

# Robusto!
for 1, 1000,  1, 10000, 1, 100000, 2**73 + 1, 2**73 + 100 -> $a, $b {
    put "\nCount of attractive numbers from {comma $a} to {comma $b}:\n" ~
    comma count $a, $b
}

```

Output:

```
Attractive numbers from 1 to 120:
  4   6   8   9  10  12  14  15  18  20  21  22  25  26  27  28  30  32  33  34
 35  38  39  42  44  45  46  48  49  50  51  52  55  57  58  62  63  65  66  68
 69  70  72  74  75  76  77  78  80  82  85  86  87  91  92  93  94  95  98  99
102 105 106 108 110 111 112 114 115 116 117 118 119 120

Count of attractive numbers from 1 to 1,000:
636

Count of attractive numbers from 1 to 10,000:
6,396

Count of attractive numbers from 1 to 100,000:
63,255

Count of attractive numbers from 9,444,732,965,739,290,427,393 to 9,444,732,965,739,290,427,492:
58
```


[User] **AudioAlarm** is a program that asks the user to enter a certain number, representing a number of seconds. After the user enters the number, the program will ask the user to enter the name of an MP3 audio file (without the .mp3 file extension). The program will then display a (usually blank) page. After the time (indicated by the number) is up, a sound (indicated by the MP3 file) will go off. Useful for timers and alarm clocks. The app must be installed in its own folder, preferrably with a name like *AudioAlarm*. To install a sound on the app, just copy the MP3 to the app folder you set up. Then, when the app asks you for the filename, you just type in the name without an extension.

[Assistant]
requires mpg123 to be installed.

```
# 20221111 Raku programming solution

loop (my $wait; $wait !~~ Int;) { $wait=prompt('enter seconds to wait: ') }

loop (my $mp3='';!"$mp3.mp3".IO.e;) { $mp3=prompt('enter filename to play: ') }

run '/usr/bin/clear';

sleep($wait);

run '/usr/bin/mpg123', "$mp3.mp3";

```


[User]
An audio frequency generator produces a continual audible monotone at a set frequency and level of volume.
There are controls to adjust the frequency and the volume up and down as desired.
Some also have a selector to switch the waveform type between sine wave, square wave and triangular sawtooth.

The task is to emulate an audio frequency generator.
It is permissible to use an inbuilt computer speaker
if the system does not have the facility to utilize dedicated sound hardware.

The solution should include:

* A demonstration of how to check for availability of sound hardware on the system (on systems where this is possible)
* A demonstration of how to produce a continual audible monotone (on sound hardware this would typically be a sine wave)
* A method of adjusting the frequency and volume of the monotone. (one way would be to use left and right arrow keys to increase or decrease frequency, and up and down keys to increase or decrease the volume)
* A method to silence or reset the sound hardware on exit.

Optionally the solution can also include:

* A demonstration of how to fall back to internal speaker, if sound hardware is not available
* A facility to switch between sine wave, square wave and triangular sawtooth

Languages that provide no facilities for utilizing sound hardware of any kind should be omitted.

[Assistant]
**Translation of**: Go

```
# 20240130 Raku programming solution

my ($kindS, $kind, $freq, $vol, $dur) = 'sine', |(0 xx *);

while $freq < 40 || $freq > 10000 {
   print "Enter frequency in Hz (40 to 10000) : ";
   $freq = prompt().Int;
}

while $vol < 1 || $vol > 50 {
   print "Enter volume in dB (1 to 50) : ";
   $vol = prompt().Int;
}

while $dur < 2 || $dur > 10 {
   print "Enter duration in seconds (2 to 10) : ";
   $dur = prompt().Int;
}

while $kind < 1 || $kind > 3 {
   print 'Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ';
   given $kind = prompt().Int {
      when $kind == 2 { $kindS = 'square'   }
      when $kind == 3 { $kindS = 'sawtooth' }
   }
}

my @args = "-n", "synth", $dur, $kindS, $freq, "vol", $vol, "dB";
run 'play', @args, :out('/dev/null'), :err('/dev/null');

```


[User]
**Audio Overlap Loop** is a program that produces an "echo chamber" effect by playing an audio file several times in an overlapping loop. A repetition level determines the number of times that the file is looped. For the purpose of this task, write a program that takes a parameter for the number of repetitions and plays the file *loop.wav* in an overlapping loop according to the number of repetitions.

Optionally take parameters for delay between repetitions, and decay (fractional volume reduction between consecutive repetitions).

[Assistant]
**Translation of**: Julia

```
# 20241230 Raku programming solution

my $soundfile = "notes.wav";
my $repetitions;

if @*ARGS.elems < 1 {
   say "Usage: give number of repetitions in echo effect as argument to the program."
} else {
   given $*KERNEL.cpu-cores { $repetitions = @*ARGS[0] < $_ ?? @*ARGS[0] !! $_ }
}

for 0.0, 0.1 ... (($repetitions - 1) * 0.1) -> $seconds {
   sleep $seconds;
   my $proc = Proc::Async.new('play', '--no-show-progress', $soundfile);
   $proc.start
}

```


[User]
Definition

An **autogram** is a sentence that describes itself in the sense of providing an inventory of its own characters. An essential feature is the use of full cardinal number names such as "one", "two", etc., in recording character counts.

Autograms are also called 'self-enumerating' or 'self-documenting' sentences. Whilst they usually just count letters of the alphabet, they can also count punctuation symbols as well.

Example

If punctuation is ignored, the following sentence is an autogram:

```
This sentence employs two a's, two c's, two d's, twenty-eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty-five s's, twenty-three t's, six v's, ten w's, two x's, five y's, and one z.

```

Task

Write a routine in your language to check whether or not a given sentence is an autogram and use it to test the above example (Sentence 1.) and also the following sentences:

2. This sentence employs two a's, two c's, two d's, twenty eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty five s's, twenty three t's, six v's, ten w's, two x's, five y's, and one z.

3. Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's, four c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three apostrophes, seven hyphens and, last but not least, a single !

4. This pangram contains four as, one b, two cs, one d, thirty es, six fs, five gs, seven hs, eleven is, one j, one k, two ls, two ms, eighteen ns, fifteen os, two ps, one q, five rs, twenty-seven ss, eighteen ts, two us, seven vs, eight ws, two xs, three ys, & one z.

5. This sentence contains one hundred and ninety-seven letters: four a's, one b, three c's, five d's, thirty-four e's, seven f's, one g, six h's, twelve i's, three l's, twenty-six n's, ten o's, ten r's, twenty-nine s's, nineteen t's, six u's, seven v's, four w's, four x's, five y's, and one z.

6. Thirteen e's, five f's, two g's, five h's, eight i's, two l's, three n's, six o's, six r's, twenty s's, twelve t's, three u's, four v's, six w's, four x's, two y's.

7. Fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's.

8. Sixteen e's, five f's, three g's, six h's, nine i's, five n's, four o's, six r's, eighteen s's, eight t's, three u's, three v's, two w's, four z's.

Punctuation should be ignored in all cases except for sentences number 3. and 7. For task 3 and 7, punctuation counts must be checked, and some ('comma', 'apostrophe', 'hyphen') punctuation may be represented in the autogram using the spelled out english names for the punctuation and the checker must respect the inconsistent use of apostrophes in the spellings of the counts (while still counting apostrophes accurately) and must accept 'single' as a synonym for 'one'.

Note that the only difference between sentences 1. and 2. is that there are no hyphens in the latter.

Assumptions

* Ignore capitalization.

* Never count spaces or full stops.

If it helps you may also make the following simplifying assumptions:

* No sentence will be such that there are more than 99 instances of any countable character.

* If punctuation is to be allowed for, only commas, hyphens, apostrophes and exclamation marks need be counted.

Reference

* Wikipedia: Autogram

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]
Slightly fragile, especially for non-letter character counts, but good enough for here.

Using Text::Wrap from the ecosystem. Install command: `zef install -v git://github.com/jkramer/p6-Text-Wrap.git`.

```
my %nums = :0zero, :1one, :2two, :3three, :4four, :5five, :6six, :7seven, :8eight, :9nine, :10ten, :11eleven,
    :12twelve, :13thirteen, :14fourteen, :15fifteen, :16sixteen, :17seventeen, :18eighteen, :19nineteen,
    :20twenty, :30thirty, :40forty, :50fifty, :60sixty, :70seventy, :80eighty, :90ninety, :100hundred, :1single;

sub whitespace  { $^a.subst(:g, /\s|'.'/, '') }
sub non-letters { $^a.subst(:g, /\W/, '') }

my @tests =
    (&non-letters, "This sentence employs two a's, two c's, two d's, twenty-eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty-five s's, twenty-three t's, six v's, ten w's, two x's, five y's, and one z."),
    (&non-letters, "This sentence employs two a's, two c's, two d's, twenty eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty five s's, twenty three t's, six v's, ten w's, two x's, five y's, and one z."),
    (&whitespace,  "Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's, four c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three apostrophes, seven hyphens and, last but not least, a single !"),
    (&non-letters, "This pangram contains four as, one b, two cs, one d, thirty es, six fs, five gs, seven hs, eleven is, one j, one k, two ls, two ms, eighteen ns, fifteen os, two ps, one q, five rs, twenty-seven ss, eighteen ts, two us, seven vs, eight ws, two xs, three ys, & one z."),
    (&non-letters, "This sentence contains one hundred and ninety-seven letters: four a's, one b, three c's, five d's, thirty-four e's, seven f's, one g, six h's, twelve i's, three l's, twenty-six n's, ten o's, ten r's, twenty-nine s's, nineteen t's, six u's, seven v's, four w's, four x's, five y's, and one z."),
    (&non-letters, "Thirteen e's, five f's, two g's, five h's, eight i's, two l's, three n's, six o's, six r's, twenty s's, twelve t's, three u's, four v's, six w's, four x's, two y's."),
    (&whitespace,  "Fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's."),
    (&non-letters, "Sixteen e's, five f's, three g's, six h's, nine i's, five n's, four o's, six r's, eighteen s's, eight t's, three u's, three v's, two w's, four z's.")
;

use Text::Wrap;

say '=' x 100;

for @tests ->  (&filter, $text) {

    # Original
    say wrap-text :100width, $text;

    say "\nFiltering out " ~ &filter.name ~ ':';

    # Semi-bogus and somewhat fragile names to numbers conversion.
    my $str = $text.lc;
    for %nums.kv -> $word, $number { $str ~~ s:g/ <|w> $word <|w> /$number/ }
    $str ~~ s:g/ (\d)<ws>['and'|'-']<ws>(\d)  /$0 $1/;
    $str ~~ s:g/ <|w>(\d ** 2)<ws>(\d ** 2) <|w> /{ $0 × 100 + $1}/;
    $str ~~ s:g/ ( [\d+<ws>]* \d+ ) /{[+] $0.split: ' '}/;

    # Build a hash of claimed characters.
    my %claim = flat $str.lc.match(:g, /\d+ <:ws> ['comma'|'apostrophe'|'hyphen'|.]/)».split(' ')»[1,0]».pairup;
    for <comma , hyphen - apostrophe '> #`['] -> $word, $symbol { %claim{$symbol} = %claim{$word}:delete if %claim{$word} }
    say "\nClaimed character counts:\n" ~ wrap-text :100width, %claim.sort( ~*.key ).map( { sprintf "%s\(%d)", .key, .value } ).join: ' ';

    # And of the actual character counts.
    my %count = &filter($text).lc.comb.Bag.hash;
    say "\nActual:\n" ~ wrap-text :100width, %count.sort( ~*.key ).map( { sprintf "%s\(%d)", .key, .value } ).join: ' ';

    # And compare them
    say "\nAutogram? " ~
    quietly (so all %count.map: { .value == %claim{.key} }) && (so all %claim.map: { .value == %count{.key} });

    say '=' x 100;
}

```

Output:

```
====================================================================================================
This sentence employs two a's, two c's, two d's, twenty-eight e's, five f's, three g's, eight h's,
eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty-five s's,
twenty-three t's, six v's, ten w's, two x's, five y's, and one z.

Filtering out non-letters:

Claimed character counts:
a(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)
y(5) z(1)

Actual:
a(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)
y(5) z(1)

Autogram? True
====================================================================================================
This sentence employs two a's, two c's, two d's, twenty eight e's, five f's, three g's, eight h's,
eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty five s's, twenty
three t's, six v's, ten w's, two x's, five y's, and one z.

Filtering out non-letters:

Claimed character counts:
a(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)
y(5) z(1)

Actual:
a(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)
y(5) z(1)

Autogram? True
====================================================================================================
Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's,
four c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine
l's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven
t's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three
apostrophes, seven hyphens and, last but not least, a single !

Filtering out whitespace:

Claimed character counts:
!(1) '(23) ,(27) -(7) a(10) b(3) c(4) d(4) e(46) f(16) g(4) h(13) i(15) k(2) l(9) m(4) n(25) o(24)
p(5) r(16) s(41) t(37) u(10) v(8) w(8) x(4) y(11)

Actual:
!(1) '(23) ,(27) -(7) a(10) b(3) c(4) d(4) e(46) f(16) g(4) h(13) i(15) k(2) l(9) m(4) n(25) o(24)
p(5) r(16) s(41) t(37) u(10) v(8) w(8) x(4) y(11)

Autogram? True
====================================================================================================
This pangram contains four as, one b, two cs, one d, thirty es, six fs, five gs, seven hs, eleven
is, one j, one k, two ls, two ms, eighteen ns, fifteen os, two ps, one q, five rs, twenty-seven ss,
eighteen ts, two us, seven vs, eight ws, two xs, three ys, & one z.

Filtering out non-letters:

Claimed character counts:
a(4) b(1) c(2) d(1) e(30) f(6) g(5) h(7) i(11) j(1) k(1) l(2) m(2) n(18) o(15) p(2) q(1) r(5) s(27)
t(18) u(2) v(7) w(8) x(2) y(3) z(1)

Actual:
a(4) b(1) c(2) d(1) e(30) f(6) g(5) h(7) i(11) j(1) k(1) l(2) m(2) n(18) o(15) p(2) q(1) r(5) s(27)
t(18) u(2) v(7) w(8) x(2) y(3) z(1)

Autogram? True
====================================================================================================
This sentence contains one hundred and ninety-seven letters: four a's, one b, three c's, five d's,
thirty-four e's, seven f's, one g, six h's, twelve i's, three l's, twenty-six n's, ten o's, ten r's,
twenty-nine s's, nineteen t's, six u's, seven v's, four w's, four x's, five y's, and one z.

Filtering out non-letters:

Claimed character counts:
a(4) b(1) c(3) d(5) e(34) f(7) g(1) h(6) i(12) l(3) n(26) o(10) r(10) s(29) t(19) u(6) v(7) w(4)
x(4) y(5) z(1)

Actual:
a(4) b(1) c(3) d(5) e(34) f(7) g(1) h(6) i(12) l(3) n(26) o(10) r(10) s(29) t(19) u(6) v(7) w(4)
x(4) y(5) z(1)

Autogram? True
====================================================================================================
Thirteen e's, five f's, two g's, five h's, eight i's, two l's, three n's, six o's, six r's, twenty
s's, twelve t's, three u's, four v's, six w's, four x's, two y's.

Filtering out non-letters:

Claimed character counts:
e(13) f(5) g(2) h(5) i(8) l(2) n(3) o(6) r(6) s(20) t(12) u(3) v(4) w(6) x(4) y(2)

Actual:
e(13) f(5) g(2) h(5) i(8) l(2) n(3) o(6) r(6) s(20) t(12) u(3) v(4) w(6) x(4) y(2)

Autogram? True
====================================================================================================
Fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's,
eight t's, four u's, three v's, two w's, three x's.

Filtering out whitespace:

Claimed character counts:
e(15) f(7) g(4) h(6) i(8) n(4) o(5) r(6) s(18) t(8) u(4) v(3) w(2) x(3)

Actual:
'(14) ,(13) e(15) f(7) g(4) h(6) i(8) n(4) o(5) r(6) s(18) t(8) u(4) v(3) w(2) x(3)

Autogram? False
====================================================================================================
Sixteen e's, five f's, three g's, six h's, nine i's, five n's, four o's, six r's, eighteen s's,
eight t's, three u's, three v's, two w's, four z's.

Filtering out non-letters:

Claimed character counts:
e(16) f(5) g(3) h(6) i(9) n(5) o(4) r(6) s(18) t(8) u(3) v(3) w(2) z(4)

Actual:
e(16) f(5) g(3) h(6) i(9) n(5) o(4) r(6) s(18) t(8) u(3) v(3) w(2) x(3) z(1)

Autogram? False
====================================================================================================
```


[User]
Let `f` be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence `1, f(1), f(f(1))...` will contain a *repetition*, a number that occurring for the second time in the sequence.

Task

Write a program or a script that estimates, for each `N`, the average length until the first such repetition.

Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.

This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.

Example of expected output:

```
 N    average    analytical    (error)
===  =========  ============  =========
  1     1.0000        1.0000  (  0.00%)
  2     1.4992        1.5000  (  0.05%)
  3     1.8784        1.8889  (  0.56%)
  4     2.2316        2.2188  (  0.58%)
  5     2.4982        2.5104  (  0.49%)
  6     2.7897        2.7747  (  0.54%)
  7     3.0153        3.0181  (  0.09%)
  8     3.2429        3.2450  (  0.07%)
  9     3.4536        3.4583  (  0.14%)
 10     3.6649        3.6602  (  0.13%)
 11     3.8091        3.8524  (  1.12%)
 12     3.9986        4.0361  (  0.93%)
 13     4.2074        4.2123  (  0.12%)
 14     4.3711        4.3820  (  0.25%)
 15     4.5275        4.5458  (  0.40%)
 16     4.6755        4.7043  (  0.61%)
 17     4.8877        4.8579  (  0.61%)
 18     4.9951        5.0071  (  0.24%)
 19     5.1312        5.1522  (  0.41%)
 20     5.2699        5.2936  (  0.45%)
```

[Assistant]
(formerly Perl 6)

```
constant MAX_N  = 20;
constant TRIALS = 100;

for 1 .. MAX_N -> $N {
    my $empiric = TRIALS R/ [+] find-loop(random-mapping $N).elems xx TRIALS;
    my $theoric = [+]
        map -> $k { $N ** ($k + 1) R/ [×] flat $k**2, $N - $k + 1 .. $N }, 1 .. $N;

    FIRST say " N    empiric      theoric      (error)";
    FIRST say "===  =========  ============  =========";

    printf "%3d  %9.4f  %12.4f    (%4.2f%%)\n",
            $N,  $empiric, $theoric, 100 × abs($theoric - $empiric) / $theoric;
}

sub random-mapping { hash .list Z=> .roll($_) given ^$^size }
sub find-loop { 0, | %^mapping{*} ...^ { (%){$_}++ } }

```

Example:

```
 N    empiric      theoric      (error)
===  =========  ============  =========
  1     1.0000        1.0000    (0.00%)
  2     1.5600        1.5000    (4.00%)
  3     1.7800        1.8889    (5.76%)
  4     2.1800        2.2188    (1.75%)
  5     2.6200        2.5104    (4.37%)
  6     2.8300        2.7747    (1.99%)
  7     3.1200        3.0181    (3.37%)
  8     3.1400        3.2450    (3.24%)
  9     3.4500        3.4583    (0.24%)
 10     3.6700        3.6602    (0.27%)
 11     3.8300        3.8524    (0.58%)
 12     4.3600        4.0361    (8.03%)
 13     3.9000        4.2123    (7.42%)
 14     4.4900        4.3820    (2.46%)
 15     4.9500        4.5458    (8.89%)
 16     4.9800        4.7043    (5.86%)
 17     4.9100        4.8579    (1.07%)
 18     4.9700        5.0071    (0.74%)
 19     5.1000        5.1522    (1.01%)
 20     5.2300        5.2936    (1.20%)
```


[User]
Task

Write a program to find the mean (arithmetic average) of a numeric vector.

In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.

See also

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

---

[Assistant]
(formerly Perl 6)

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

```
multi mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions
multi mean (@a) { ([+] @a) / @a }
```


[User]
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.

If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.

To calculate the mean angle of several angles:

1. Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.
2. Compute the mean of the complex numbers.
3. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.

(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)

You can alternatively use this formula:

:   Given the angles

    α

    1
    ,
    …
    ,

    α

    n
    {\displaystyle {\displaystyle \alpha \_{1},\dots ,\alpha \_{n}}}
     the mean is computed by

:   :   α
        ¯
        =
        atan2

        (

        1
        n
        ⋅

        ∑

        j
        =
        1

        n
        sin

        α

        j
        ,

        1
        n
        ⋅

        ∑

        j
        =
        1

        n
        cos

        α

        j
        )
        {\displaystyle {\displaystyle {\bar {\alpha }}=\operatorname {atan2} \left({\frac {1}{n}}\cdot \sum \_{j=1}^{n}\sin \alpha \_{j},{\frac {1}{n}}\cdot \sum \_{j=1}^{n}\cos \alpha \_{j}\right)}}

Task

1. write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle.
    (You should use a built-in function if you have one that does this for degrees or radians).
2. Use the function to compute the means of these lists of angles (in degrees):
   * [350, 10]
   * [90, 180, 270, 360]
   * [10, 20, 30]
3. Show your output here.

See also

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

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

This solution refuses to return an answer when the angles cancel out to a tiny magnitude.

```
# Of course, you can still use pi and 180.
sub deg2rad { $^d * tau / 360 }
sub rad2deg { $^r * 360 / tau }

sub phase ($c)  {
    my ($mag,$ang) = $c.polar;
    return NaN if $mag < 1e-16;
    $ang;
}

sub meanAngle { rad2deg phase [+] map { cis deg2rad $_ }, @^angles }

say meanAngle($_).fmt("%.2f\tis the mean angle of "), $_ for
    [350, 10],
    [90, 180, 270, 360],
    [10, 20, 30];

```

Output:

```
-0.00	is the mean angle of 350 10
NaN	is the mean angle of 90 180 270 360
20.00	is the mean angle of 10 20 30
```


[User]
Task

A particular activity of bats occurs at these times of the day:

:   23:00:17, 23:40:20, 00:12:45, 00:17:19

Using the idea that there are twenty-four hours in a day,
which is analogous to there being 360 degrees in a circle,
map times of day to and from angles;
and using the ideas of Averages/Mean angle
compute and show the average time of the nocturnal activity
to an accuracy of one second of time.

See also

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

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
sub tod2rad($_) { [+](.comb(/\d+/) Z* 3600,60,1) * tau / 86400 }

sub rad2tod ($r) {
    my $x = $r * 86400 / tau;
    (($x xx 3 Z/ 3600,60,1) Z% 24,60,60).fmt('%02d',':');
}

sub phase ($c) { $c.polar[1] }

sub mean-time (@t) { rad2tod phase [+] map { cis tod2rad $_ }, @t }

my @times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"];

say "{ mean-time(@times) } is the mean time of @times[]";

```

Output:

```
23:47:43 is the mean time of 23:00:17 23:40:20 00:12:45 00:17:19

```


[User]
Task

Write a program to find the   median   value of a vector of floating-point numbers.

The program need not handle the case where the vector is empty, but *must* handle the case where there are an even number of elements.   In that case, return the average of the two middle values.

There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle.

Sorting would take at least   O(*n* log*n*).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(*n* log*n*).   The best solution is to use the   selection algorithm   to find the median in   O(*n*)   time.

See also

Quickselect\_algorithm

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

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.08

```
sub median {
  my @a = sort @_;
  return (@a[(*-1) div 2] + @a[* div 2]) / 2;
}

```

Notes:

* The div operator does integer division. The / operator (rational number division) would work too, since the array subscript automatically coerces to Int, but using div is more explicit (i.e. clearer to readers) as well as faster, and thus recommended in cases like this.
* The \* inside the subscript stands for the array's length (see documentation).

In a slightly more compact way:

```
sub median { @_.sort[(*-1)/2, */2].sum / 2 }

```


[User]
Task

Write a program to find the mode value of a collection.

The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.

If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.

See also

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

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03.1

```
sub mode (*@a) {
    my %counts := @a.Bag;
    my $max = %counts.values.max;
    %counts.grep(*.value == $max).map(*.key);
}

# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];

```

Output:

```
6
(4 1)

```

Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)

```
sub mode (*@a) {
    @a.Bag                # count elements
      .classify(*.value)  # group elements with the same count
      .max(*.key)         # get group with the highest count
      .value.map(*.key);  # get elements in the group
}

say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];

```


[User]
Task

Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).

Show that

A
(

x

1
,
…
,

x

n
)
≥
G
(

x

1
,
…
,

x

n
)
≥
H
(

x

1
,
…
,

x

n
)
{\displaystyle {\displaystyle A(x\_{1},\ldots ,x\_{n})\geq G(x\_{1},\ldots ,x\_{n})\geq H(x\_{1},\ldots ,x\_{n})}}
 for this set of positive integers.

* The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:

:   A
    (

    x

    1
    ,
    …
    ,

    x

    n
    )
    =

    x

    1
    +
    ⋯
    +

    x

    n
    n
    {\displaystyle {\displaystyle A(x\_{1},\ldots ,x\_{n})={\frac {x\_{1}+\cdots +x\_{n}}{n}}}}

* The geometric mean is the

  n
  {\displaystyle {\displaystyle n}}
  th root of the product of the list:

:   G
    (

    x

    1
    ,
    …
    ,

    x

    n
    )
    =

    x

    1
    ⋯

    x

    n

    n
    {\displaystyle {\displaystyle G(x\_{1},\ldots ,x\_{n})={\sqrt[{n}]{x\_{1}\cdots x\_{n}}}}}

* The harmonic mean is

  n
  {\displaystyle {\displaystyle n}}
   divided by the sum of the reciprocal of each item in the list:

:   H
    (

    x

    1
    ,
    …
    ,

    x

    n
    )
    =

    n

    1

    x

    1
    +
    ⋯
    +

    1

    x

    n
    {\displaystyle {\displaystyle H(x\_{1},\ldots ,x\_{n})={\frac {n}{{\frac {1}{x\_{1}}}+\cdots +{\frac {1}{x\_{n}}}}}}}

See also

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

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
sub A { ([+] @_) / @_ }
sub G { ([*] @_) ** (1 / @_) }
sub H { @_ / [+] 1 X/ @_ }

say "A(1,...,10) = ", A(1..10);
say "G(1,...,10) = ", G(1..10);
say "H(1,...,10) = ", H(1..10);

```

Output:

```
A(1,...,10) = 5.5
G(1,...,10) = 4.52872868811677
H(1,...,10) = 3.41417152147406
```


[User]
Task

Compute the   Root mean square   of the numbers 1..10.

The   *root mean square*   is also known by its initials RMS (or rms), and as the **quadratic mean**.

The RMS is calculated as the mean of the squares of the numbers, square-rooted:

:   :   :   x

            r
            m
            s
            =

            x

            1

            2
            +

            x

            2

            2
            +
            ⋯
            +

            x

            n

            2
            n
            .
            {\displaystyle {\displaystyle x\_{\mathrm {rms} }={\sqrt {{{x\_{1}}^{2}+{x\_{2}}^{2}+\cdots +{x\_{n}}^{2}} \over n}}.}}

See also

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

---

[Assistant]
(formerly Perl 6)

```
sub rms(*@nums) { sqrt ([+] @nums X** 2) / @nums }

say rms 1..10;

```

Here's a slightly more concise version, albeit arguably less readable:

```
sub rms { sqrt @_ R/ [+] @_».² }

```


[User]
Computing the simple moving average of a series of numbers.

Task

Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.

Description

A simple moving average is a method for computing an average of a stream of numbers by only averaging the last   P   numbers from the stream,   where   P   is known as the period.

It can be implemented by calling an initialing routine with   P   as its argument,   I(P),   which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last   P   of them, lets call this   SMA().

The word   *stateful*   in the task description refers to the need for   SMA()   to remember certain information between calls to it:

* The period,   P
* An ordered container of at least the last   P   numbers from each of its individual calls.

*Stateful*   also means that successive calls to   I(),   the initializer,   should return separate routines that do   *not*   share saved state so they could be used on two independent streams of data.

Pseudo-code for an implementation of   SMA   is:

```
function SMA(number: N):
    stateful integer: P
    stateful list:    stream
    number:           average

    stream.append_last(N)
    if stream.length() > P:
        # Only average the last P elements of the stream
        stream.delete_first()
    if stream.length() == 0:
        average = 0
    else:
        average = sum( stream.values() ) / stream.length()
    return average

```

See also

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

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.08

```
sub sma-generator (Int $P where * > 0) {
    sub ($x) {
        state @a = 0 xx $P;
        @a.push($x).shift;
        @a.sum / $P;
    }
}

# Usage:
my &sma = sma-generator 3;

for 1, 2, 3, 2, 7 {
    printf "append $_ --> sma = %.2f  (with period 3)\n", sma $_;
}

```

Output:

```
append 1 --> sma = 0.33  (with period 3)
append 2 --> sma = 1.00  (with period 3)
append 3 --> sma = 2.00  (with period 3)
append 2 --> sma = 2.33  (with period 3)
append 7 --> sma = 4.00  (with period 3)

```


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

In computer science, an **AVL tree** is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log *n*) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.

AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log *n*) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants.

Task

Implement an AVL tree in the language of choice, and provide at least basic operations.

Related task

Red\_black\_tree\_sort

[Assistant]
(formerly Perl 6)
This code has been translated from the Java version on
<https://rosettacode.org>. Consequently, it should have the same
license: GNU Free Document License 1.2. In addition to the translated
code, other public methods have been added as shown by the asterisks
in the following list of all public methods:

* insert node
* delete node
* show all node keys
* show all node balances
* \*delete nodes by a list of node keys
* \*find and return node objects by key
* \*attach data per node
* \*return list of all node keys
* \*return list of all node objects

Note one of the interesting features of Raku is the ability to use characters
like the apostrophe (') and hyphen (-) in identifiers.

```
class AVL-Tree {
    has $.root is rw = 0;

    class Node {
        has $.key    is rw = '';
        has $.parent is rw = 0;
        has $.data   is rw = 0;
        has $.left   is rw = 0;
        has $.right  is rw = 0;
        has Int $.balance is rw = 0;
        has Int $.height  is rw = 0;
    }

    #=====================================================
    # public methods
    #=====================================================

    #| returns a node object or 0 if not found
    method find($key) {
        return 0 if !$.root;
        self!find: $key, $.root;
    }

    #| returns a list of tree keys
    method keys() {
        return () if !$.root;
        my @list;
        self!keys: $.root, @list;
        @list;
    }

    #| returns a list of tree nodes
    method nodes() {
        return () if !$.root;
        my @list;
        self!nodes: $.root, @list;
        @list;
    }

    #| insert a node key, optionally add data (the `parent` arg is for
    #| internal use only)
    method insert($key, :$data = 0, :$parent = 0,) {
        return $.root = Node.new: :$key, :$parent, :$data if !$.root;
        my $n = $.root;
        while True {
            return False if $n.key eq $key;
            my $parent = $n;
            my $goLeft = $n.key > $key;
            $n = $goLeft ?? $n.left !! $n.right;
            if !$n {
                if $goLeft {
                    $parent.left = Node.new: :$key, :$parent, :$data;
                }
                else {
                    $parent.right = Node.new: :$key, :$parent, :$data;
                }
                self!rebalance: $parent;
                last
            }
        }
        True
    }

    #| delete one or more nodes by key
    method delete(*@del-key) {
        return if !$.root;
        for @del-key -> $del-key {
            my $child = $.root;
            while $child {
                my $node = $child;
                $child = $del-key >= $node.key ?? $node.right !! $node.left;
                if $del-key eq $node.key {
                    self!delete: $node;
                    next;
                }
            }
        }
    }

    #| show a list of all nodes by key
    method show-keys {
        self!show-keys: $.root;
        say()
    }

    #| show a list of all nodes' balances (not normally needed)
    method show-balances {
        self!show-balances: $.root;
        say()
    }

    #=====================================================
    # private methods
    #=====================================================

    method !delete($node) {
        if !$node.left && !$node.right {
            if !$node.parent {
                $.root = 0;
            }
            else {
                my $parent = $node.parent;
                if $parent.left === $node {
                    $parent.left = 0;
                }
                else {
                    $parent.right = 0;
                }
                self!rebalance: $parent;
            }
            return
        }

        if $node.left {
            my $child = $node.left;
            while $child.right {
                $child = $child.right;
            }
            $node.key = $child.key;
            self!delete: $child;
        }
        else {
            my $child = $node.right;
            while $child.left {
                $child = $child.left;
            }
            $node.key = $child.key;
            self!delete: $child;
        }
    }

    method !rebalance($n is copy) {
        self!set-balance: $n;

        if $n.balance == -2 {
            if self!height($n.left.left) >= self!height($n.left.right) {
                $n = self!rotate-right: $n;
            }
            else {
                $n = self!rotate-left'right: $n;
            }
        }
        elsif $n.balance == 2 {
            if self!height($n.right.right) >= self!height($n.right.left) {
                $n = self!rotate-left: $n;
            }
            else {
                $n = self!rotate-right'left: $n;
            }
        }

        if $n.parent {
            self!rebalance: $n.parent;
        }
        else {
            $.root = $n;
        }
    }

    method !rotate-left($a) {

        my $b     = $a.right;
        $b.parent = $a.parent;

        $a.right = $b.left;

        if $a.right {
            $a.right.parent = $a;
        }

        $b.left   = $a;
        $a.parent = $b;

        if $b.parent {
            if $b.parent.right === $a {
                $b.parent.right = $b;
            }
            else {
                $b.parent.left = $b;
            }
        }

        self!set-balance: $a, $b;
        $b;
    }

    method !rotate-right($a) {

        my $b = $a.left;
        $b.parent = $a.parent;

        $a.left = $b.right;

        if $a.left {
            $a.left.parent = $a;
        }

        $b.right  = $a;
        $a.parent = $b;

        if $b.parent {
            if $b.parent.right === $a {
                $b.parent.right = $b;
            }
            else {
                $b.parent.left = $b;
            }
        }

        self!set-balance: $a, $b;

        $b;
    }

    method !rotate-left'right($n) {
        $n.left = self!rotate-left: $n.left;
        self!rotate-right: $n;
    }

    method !rotate-right'left($n) {
        $n.right = self!rotate-right: $n.right;
        self!rotate-left: $n;
    }

    method !height($n) {
        $n ?? $n.height !! -1;
    }

    method !set-balance(*@n) {
        for @n -> $n {
            self!reheight: $n;
            $n.balance = self!height($n.right) - self!height($n.left);
        }
    }

    method !show-balances($n) {
        if $n {
            self!show-balances: $n.left;
            printf "%s ", $n.balance;
            self!show-balances: $n.right;
        }
    }

    method !reheight($node) {
        if $node {
            $node.height = 1 + max self!height($node.left), self!height($node.right);
        }
    }

    method !show-keys($n) {
        if $n {
            self!show-keys: $n.left;
            printf "%s ", $n.key;
            self!show-keys: $n.right;
        }
    }

    method !nodes($n, @list) {
        if $n {
            self!nodes: $n.left, @list;
            @list.push: $n if $n;
            self!nodes: $n.right, @list;
        }
    }

    method !keys($n, @list) {
        if $n {
            self!keys: $n.left, @list;
            @list.push: $n.key if $n;
            self!keys: $n.right, @list;
        }
    }

    method !find($key, $n) {
        if $n {
            self!find: $key, $n.left;
            return $n if $n.key eq $key;
            self!find: $key, $n.right;
        }
    }
}

```


[User]
Task

Generate a B-spline curve with a list of 12 points and plot or save image.

Coordinates of control points:

```
   start=171,171
   1 185,111,
   2 202,109,
   3 202,189
   4 328,160
   5 208,254
   6 241,330
   7 164,252
   8 69,278
   9 139,208
   10 72,148
   end=168,172

```

Rules!!!!

Do not use third party libraries or functions

See also

* B-splines

[Assistant]
A minimal translation of this C program, by Bernhard R. Fischer.

```
# 20211112 Raku programming solution

use Cairo;

# class point_t { has Num ($.x,$.y) is rw } # get by with two element lists
class line_t  { has ($.A,$.B) is rw }

my (\WIDTH,  \HEIGHT,  \W_LINE,  \CURVE_F,  \DETACHED,          \OUTPUT  ) =
       400,      400,        2,      0.25,          0,  './b-spline.png' ;

my \cnt = #`(Number of points) ( my \pt = [
   [171, 171], [185, 111], [202, 109], [202, 189], [328, 160], [208, 254],
   [241, 330], [164, 252], [ 69, 278], [139, 208], [ 72, 148], [168, 172], ]
).elems;

sub angle(\g) { atan2(g.B.[1] - g.A.[1], g.B.[0] - g.A.[0]) }

sub control_points(\g, \l, @p1, @p2){

#`[ This function calculates the control points. It takes two lines g and l as
 * arguments but it takes three lines into account for calculation. This is
 * line g (P0/P1), line h (P1/P2), and line l (P2/P3). The control points being
 * calculated are actually those for the middle line h, this is from P1 to P2.
 * Line g is the predecessor and line l the successor of line h.
 * @param g Pointer to first line (P0 to P1)
 * @param l Pointer to third line (P2 to P3)
 * @param p1 Pointer to memory of first control point.
 * @param p2 Pointer to memory of second control point. ]

   my \h = $ = line_t.new;

   my \lgt = sqrt([+]([ g.B.[0]-l.A.[0], g.B.[1]-l.A.[1] ]>>²));#length of P1 to P2

   h.B = l.A.clone;  # end point of 1st tangent
   # start point of tangent at same distance as end point along 'g'
   h.A = g.B.[0] - lgt * cos(angle g) , g.B.[1] - lgt * sin(angle g);

   my $a = angle h ; # angle of tangent
   # 1st control point on tangent at distance 'lgt * CURVE_F'
   @p1 = g.B.[0] + lgt * cos($a) * CURVE_F,  g.B.[1] + lgt * sin($a) * CURVE_F;

   h.A = g.B.clone; # start point of 2nd tangent
   # end point of tangent at same distance as start point along 'l'
   h.B = l.A.[0] + lgt * cos(angle l) , l.A.[1] + lgt * sin(angle l);

   $a = angle h; # angle of tangent
   # 2nd control point on tangent at distance 'lgt * CURVE_F'
   @p2 = l.A.[0] - lgt * cos($a) * CURVE_F,  l.A.[1] - lgt * sin($a) * CURVE_F;
}

given Cairo::Image.create(Cairo::FORMAT_ARGB32, WIDTH, HEIGHT) {
   given Cairo::Context.new($_) {
      my line_t ($g,$l);
      my (@p1,@p2);

      .line_width = W_LINE;
      .move_to(pt[DETACHED - 1 + cnt].[0], pt[DETACHED - 1 + cnt].[1]);

      for DETACHED..^cnt -> \j {
         $g = line_t.new: A=>pt[(j + cnt - 2) % cnt], B=>pt[(j + cnt - 1) % cnt];
         $l = line_t.new: A=>pt[(j + cnt + 0) % cnt], B=>pt[(j + cnt + 1) % cnt];

         # Calculate controls points for points pt[j-1] and pt[j].
         control_points($g, $l, @p1, @p2);

         .curve_to(@p1[0], @p1[1], @p2[0], @p2[1], pt[j].[0], pt[j].[1]);
      }
      .stroke;
   };
   .write_png(OUTPUT) and die # C return
}

```

Output: (Offsite image file)


[User]
Charles Babbage

Charles Babbage's analytical engine.

Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:

What is the smallest positive integer whose square ends in the digits 269,696?

— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, *Electronic Computers*, second edition, 1970, p. 125.

He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.

Task

The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.

For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].

Motivation

The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.

[Assistant]
(formerly Perl 6)

This could certainly be written more concisely. Extra verbiage is included to make the process more clear.

```
# For all positive integers from 1 to Infinity
for 1 .. Inf -> $integer {

    # calculate the square of the integer
    my $square = $integer²;

    # print the integer and square and exit if the square modulo 1000000 is equal to 269696
    print "{$integer}² equals $square" and exit if $square mod 1000000 == 269696;
}

```

Output:

```
25264² equals 638269696
```

More concisely (but clear enough to allow Mr. Babbage to understand what's going on?):

```
.say and exit if $_²  % 1e6 == 269696 for ^∞;

```

Output:

```
25264
```

Notice that `exit` ends the process itself instead of ending just the loop, as `last` would. `exit` would arguably be easier to understand for Babbage though, so it may better fill the task requirement.