[User]
f
The **Babylonian spiral** is a sequence of points in the plane that are created so as to
continuously minimally increase in vector length and minimally bend in vector direction,
while always moving from point to point on strictly integral coordinates. Of the two criteria
of length and angle, the length has priority.

Examples

P(1) and P(2) are defined to be at (x = 0, y = 0) and (x = 0, y = 1). The first vector is
from P(1) to P(2). It is vertical and of length 1. Note that the square of that length is 1.

Next in sequence is the vector from P(2) to P(3). This should be the smallest distance to a
point with integral (x, y) which is longer than the last vector (that is, 1). It should also bend clockwise
more than zero radians, but otherwise to the least degree.

The point chosen for P(3) that fits criteria is (x = 1, y = 2). Note the length of the vector
from P(2) to P(3) is √2, which squared is 2. The lengths of the vectors thus determined can be given by a sorted
list of possible sums of two integer squares, including 0 as a square.

Task

Find and show the first 40 (x, y) coordinates of the Babylonian spiral.

Stretch task

Show in your program how to calculate and plot the first 10000 points in the sequence. Your result
should look similar to the graph shown at the OEIS:

See also

* OEIS:A256111 - squared distance to the origin of the n-th vertex on a Babylonian Spiral. * OEIS:A297346 - List of successive x-coordinates in the Babylonian Spiral. * OEIS:A297347 - List of successive y-coordinates in the Babylonian Spiral.

[Assistant]
**Translation of**: Wren

### Translation

```
sub babylonianSpiral (\nsteps) {
    my @squareCache = (0..nsteps).hyper.map: *²;
    my @dxys = [0, 0], [0, 1];
    my $dsq  = 1;

    for ^(nsteps-2) {
        my \Θ = atan2 |@dxys[*-1][1,0];
        my @candidates;

        until @candidates.elems {
            $dsq++;
            for @squareCache.kv -> \i, \a {
                last if a > $dsq/2;
                for reverse 0 .. $dsq.sqrt.ceiling -> \j {
                    last if $dsq > (a + my \b = @squareCache[j]);
                    next if $dsq != a + b;
                    @candidates.append: [i, j], [-i, j], [i, -j], [-i, -j],
                                        [j, i], [-j, i], [j, -i], [-j, -i]
                }
            }
        }
        @dxys.push: @candidates.min: { ( Θ - atan2 |.[1,0] ) % τ };
    }

    [\»+«] @dxys
}

# The task
say "The first $_ Babylonian spiral points are:\n",
(babylonianSpiral($_).map: { sprintf '(%3d,%4d)', @$_ }).batch(10).join("\n") given 40;

# Stretch
use SVG;

'babylonean-spiral-raku.svg'.IO.spurt: SVG.serialize(
    svg => [
        :width<100%>, :height<100%>,
        :rect[:width<100%>, :height<100%>, :style<fill:white;>],
        :polyline[ :points(flat babylonianSpiral(10000)),
          :style("stroke:red; stroke-width:6; fill:white;"),
          :transform("scale (.05, -.05) translate (1000,-10000)")
        ],
    ],
);

```

Output:

```
The first 40 Babylonian spiral points are:
(  0,   0) (  0,   1) (  1,   2) (  3,   2) (  5,   1) (  7,  -1) (  7,  -4) (  6,  -7) (  4, -10) (  0, -10)
( -4,  -9) ( -7,  -6) ( -9,  -2) ( -9,   3) ( -8,   8) ( -6,  13) ( -2,  17) (  3,  20) (  9,  20) ( 15,  19)
( 21,  17) ( 26,  13) ( 29,   7) ( 29,   0) ( 28,  -7) ( 24, -13) ( 17, -15) ( 10, -12) (  4,  -7) (  4,   1)
(  5,   9) (  7,  17) ( 13,  23) ( 21,  26) ( 28,  21) ( 32,  13) ( 32,   4) ( 31,  -5) ( 29, -14) ( 24, -22)
```

Stretch goal:

(offsite SVG image - 96 Kb) - babylonean-spiral-raku.svg

### Independent implementation

Exact same output; about one tenth the execution time.

```
my @next = { :x(1), :y(1), :2hyp },;

sub next-interval (Int $int) {
     @next.append: (0..$int).map: { %( :x($int), :y($_), :hyp($int² + .²) ) };
     @next = |@next.sort: *.<hyp>;
}

my @spiral = [\»+«] lazy gather {
    my $interval = 1;
    take [0,0];
    take my @tail = 0,1;
    loop {
        my \Θ = atan2 |@tail[1,0];
        my @this = @next.shift;
        @this.push: @next.shift while @next and @next[0]<hyp> == @this[0]<hyp>;
        my @candidates = @this.map: {
            my (\i, \j) = .<x y>;
            next-interval(++$interval) if $interval == i;
            |((i,j),(-i,j),(i,-j),(-i,-j),(j,i),(-j,i),(j,-i),(-j,-i))
        }
        take @tail = |@candidates.min: { ( Θ - atan2 |.[1,0] ) % τ };
    }
}

# The task
say "The first $_ Babylonian spiral points are:\n",
@spiral[^$_].map({ sprintf '(%3d,%4d)', |$_ }).batch(10).join: "\n" given 40;

# Stretch
use SVG;

'babylonean-spiral-raku.svg'.IO.spurt: SVG.serialize(
    svg => [
        :width<100%>, :height<100%>,
        :rect[:width<100%>, :height<100%>, :style<fill:white;>],
        :polyline[ :points(flat @spiral[^10000]),
          :style("stroke:red; stroke-width:6; fill:white;"),
          :transform("scale (.05, -.05) translate (1000,-10000)")
        ],
    ],
);

```

Same output:


[User]
Bacon's cipher is a method of steganography created by Francis Bacon.
This task is to implement a program for encryption and decryption of plaintext using the simple alphabet of the Baconian cipher or some other kind of representation of this alphabet (make anything signify anything).

The Baconian alphabet:

```
a   AAAAA   g     AABBA   n    ABBAA   t     BAABA
b   AAAAB   h     AABBB   o    ABBAB   u-v   BAABB
c   AAABA   i-j   ABAAA   p    ABBBA   w     BABAA
d   AAABB   k     ABAAB   q    ABBBB   x     BABAB
e   AABAA   l     ABABA   r    BAAAA   y     BABBA
f   AABAB   m     ABABB   s    BAAAB   z     BABBB

```

1. The Baconian alphabet may optionally be extended to encode all lower case characters individually and/or adding a few punctuation characters such as the space.
2. It is impractical to use the original change in font for the steganography. For this task you must provide an example that uses a change in the case of successive alphabetical characters instead. Other examples for the language are encouraged to explore alternative steganographic means.
3. Show an example plaintext message encoded and then decoded here on this page.

[Assistant]
(formerly Perl 6)

### alternative steganography algorithm

Not truly a Bacon Cipher as it doesn't encode using font variations. But fits with the spirit if not the exact definition.

**Works with**: Rakudo version 2015-11-20

```
my $secret = q:to/END/;
    This task is to implement a program for encryption and decryption
    of plaintext using the simple alphabet of the Baconian cipher or
    some other kind of representation of this alphabet (make anything
    signify anything). This example will work with anything in the
    ASCII range... even code! $r%_-^&*(){}+~ #=`/\';*1234567890"'
    END

my $text = q:to/END/;
    Bah. It isn't really practical to use typeface changes to encode
    information, it is too easy to tell that there is something going
    on and will attract attention. Font changes with enough regularity
    to encode mesages relatively efficiently would need to happen so
    often it would be obvious that there was some kind of manipulation
    going on. Steganographic encryption where it is obvious that there
    has been some tampering with the carrier is not going to be very
    effective. Not that any of these implementations would hold up to
    serious scrutiny anyway. Anyway, here's a semi-bogus implementation
    that hides information in white space. The message is hidden in this
    paragraph of text. Yes, really. It requires a fairly modern file
    viewer to display (not display?) the hidden message, but that isn't
    too unlikely any more. It may be stretching things to call this a
    Bacon cipher, but I think it falls within the spirit of the task,
    if not the exact definition.
    END
#'
my @enc = "", "";
my %dec = @enc.pairs.invert;

sub encode ($c) { @enc[($c.ord).fmt("%07b").comb].join('') }

sub hide ($msg is copy, $text) {
    $msg ~= @enc[0] x (0 - ($msg.chars % 8)).abs;
    my $head = $text.substr(0,$msg.chars div 8);
    my $tail = $text.substr($msg.chars div 8, *-1);
    ($head.comb «~» $msg.comb(/. ** 8/)).join('') ~ $tail;
}

sub reveal ($steg) {
    join '', map { :2(%dec{$_.comb}.join('')).chr },
    $steg.subst( /\w | <punct> | " " | "\n" /, '', :g).comb(/. ** 7/);
}

my $hidden = join '', map  { .&encode }, $secret.comb;

my $steganography = hide $hidden, $text;

say "Steganograpic message hidden in text:";
say $steganography;

say '*' x 70;

say "Hidden message revealed:";
say reveal $steganography;

```

Output:

```
Steganograpic message hidden in text:
Bah. It isn't really practical to use typeface changes to encode
information, it is too easy to tell that there is something going
on and will attract attention. Font changes with enough regularity
to encode mesages relatively efficiently would need to happen so
often it would be obvious that there was some kind of manipulation
going on. Steganographic encryption where it is obvious that there
has been some tampering with the carrier is not going to be very
effective. Not that any of these implementations would hold up to
serious scrutiny anyway. Anyway, here's a semi-bogus implementation
that hides information in white space. The message is hidden in this
paragraph of text. Yes, really. It requires a fairly modern file
viewer to display (not display?) the hidden message, but that isn't
too unlikely any more. It may be stretching things to call this a
Bacon cipher, but I think it falls within the spirit of the task,
if not the exact definition.
**********************************************************************
Hidden message revealed:
This task is to implement a program for encryption and decryption
of plaintext using the simple alphabet of the Baconian cipher or
some other kind of representation of this alphabet (make anything
signify anything). This example will work with anything in the
ASCII range... even code! $r%_-^&*(){}+~ #=`/\';*1234567890"'
```

### Bacon cipher solution

```
my @abc = 'a' .. 'z';
my @symb = ' ', |@abc;  # modified Baconian charset - space and full alphabet
# TODO original one with I=J U=V, nice for Latin

my %bacon = @symb Z=> (^@symb).map(*.base(2).fmt("%05s"));
my %nocab = %bacon.antipairs;

sub bacon ($s, $msg) {
  my @raw = $s.lc.comb;
  my @txt := @raw[ (^@raw).grep({@raw[$_] (elem) @abc}) ];
  for $msg.lc.comb Z @txt.batch(5) -> ($c-msg, @a) {
    for @a.kv -> $i, $c-str {
      (my $x := @a[$i]) = $x.uc if %bacon{$c-msg}.comb[$i].Int.Bool;
  } }
  @raw.join;
}

sub unbacon ($s) {
  my $chunks = ($s ~~ m:g/\w+/)>>.Str.join.comb(/.**5/);
  $chunks.map(*.comb.map({.uc eq $_})».Int».Str.join).map({%nocab{$_}}).join;
}

my $msg = "Omnes homines dignitate et iure liberi et pares nascuntur";

my $str = <Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.>;

my $baconed = bacon $str, $msg;
$baconed = $baconed.?naive-word-wrapper || $baconed;
# FIXME ^^^ makes dbl space after .
say "text:\n$baconed\n";
my $unbaconed = unbacon($baconed).trim.uc;
say "hidden message:\n$unbaconed";

```

Output:

```
text:
lOREM iPSuM dOLOr siT aMEt, cONsectetUr adiPISCiNG eLiT, seD dO EIusmOd
TEmpOR incididUnt uT laBorE ET dOLOre MagNA aLiqua.  ut ENiM ad miNiM
veniam, qUiS NoStrud exerCitATiOn ULlaMco lAbOris nisI Ut alIquIp ex Ea
coMmODo cOnsEquAt.  duis auTe IRuRe dolor iN reprehenDEriT in vOlUPtaTE
velit eSSE cilluM DolORe eu FUGiAt NuLLA pArIatUr.  ExCEptEur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.

hidden message:
OMNES HOMINES DIGNITATE ET IURE LIBERI ET PARES NASCUNTUR
```


[User]
**Task**:

* Generate a string with   **N**   opening brackets   **[**   and with   **N**   closing brackets   **]**,   in some arbitrary order.
* Determine whether the generated string is *balanced*; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.

Examples

```
   (empty)      OK
   []           OK
   [][]         OK
   [[][]]       OK
   ][         NOT OK
   ][][       NOT OK
   []][[]     NOT OK

```

[Assistant]
(formerly Perl 6)
There's More Than One Way To Do It.

### Depth counter

**Works with**: Rakudo version 2015.12

```
sub balanced($s) {
    my $l = 0;
    for $s.comb {
        when "]" {
            --$l;
            return False if $l < 0;
        }
        when "[" {
            ++$l;
        }
    }
    return $l == 0;
}

my $n = prompt "Number of brackets";
my $s = (<[ ]> xx $n).flat.pick(*).join;
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"
```

### FP oriented

Here's a more idiomatic solution using a hyperoperator to compare all the characters to a backslash (which is between the brackets in ASCII), a triangle reduction to return the running sum, a given to make that list the topic, and then a topicalized junction and a topicalized subscript to test the criteria for balance.

```
sub balanced($s) {
    .none < 0 and .[*-1] == 0
        given ([\+] '\\' «leg« $s.comb).cache;
}

my $n = prompt "Number of bracket pairs: ";
my $s = <[ ]>.roll($n*2).join;
say "$s { balanced($s) ?? "is" !! "is not" } well-balanced"
```

### String munging

Of course, a Perl 5 programmer might just remove as many inner balanced pairs as possible and then see what's left.

**Works with**: Rakudo version 2015.12

```
sub balanced($_ is copy) {
    Nil while s:g/'[]'//;
    $_ eq '';
}

my $n = prompt "Number of bracket pairs: ";
my $s = <[ ]>.roll($n*2).join;
say "$s is", ' not' x not balanced($s), " well-balanced";
```

### Parsing with a grammar

**Works with**: Rakudo version 2015.12

```
grammar BalBrack { token TOP { '[' <TOP>* ']' } }

my $n = prompt "Number of bracket pairs: ";
my $s = ('[' xx $n, ']' xx $n).flat.pick(*).join;
say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced";
```


[User]
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.

Examples

Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"

Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"

Task

Implement balanced ternary representation of integers with the following:

1. Support arbitrarily large integers, both positive and negative;
2. Provide ways to convert to and from text strings, using digits '+', '−' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
3. Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type *is* balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
4. Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do *not* convert to native integers first.
5. Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").

**Test case** With balanced ternaries *a* from string "+−0++0+", *b* from native integer −436, *c* "+−++−":

* write out *a*, *b* and *c* in decimal notation;
* calculate *a* × (*b* − *c*), write out the result in both ternary and decimal notations.

**Note:** The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2017.01

```
class BT {
    has @.coeff;

    my %co2bt = '-1' => '-', '0' => '0', '1' => '+';
    my %bt2co = %co2bt.invert;

    multi method new (Str $s) {
	self.bless(coeff => %bt2co{$s.flip.comb});
    }
    multi method new (Int $i where $i >= 0) {
	self.bless(coeff => carry $i.base(3).comb.reverse);
    }
    multi method new (Int $i where $i < 0) {
	self.new(-$i).neg;
    }

    method Str () { %co2bt{@!coeff}.join.flip }
    method Int () { [+] @!coeff Z* (1,3,9...*) }

    multi method neg () {
	self.new: coeff => carry self.coeff X* -1;
    }
}

sub carry (*@digits is copy) {
    loop (my $i = 0; $i < @digits; $i++) {
	while @digits[$i] < -1 { @digits[$i] += 3; @digits[$i+1]--; }
	while @digits[$i] > 1  { @digits[$i] -= 3; @digits[$i+1]++; }
    }
    pop @digits while @digits and not @digits[*-1];
    @digits;
}

multi prefix:<-> (BT $x) { $x.neg }

multi infix:<+> (BT $x, BT $y) {
    my ($b,$a) = sort +*.coeff, ($x, $y);
    BT.new: coeff => carry ($a.coeff Z+ |$b.coeff, |(0 xx $a.coeff - $b.coeff));
}

multi infix:<-> (BT $x, BT $y) { $x + $y.neg }

multi infix:<*> (BT $x, BT $y) {
    my @x = $x.coeff;
    my @y = $y.coeff;
    my @z = 0 xx @x+@y-1;
    my @safe;
    for @x -> $xd {
	@z = @z Z+ |(@y X* $xd), |(0 xx @z-@y);
	@safe.push: @z.shift;
    }
    BT.new: coeff => carry @safe, @z;
}

my $a = BT.new: "+-0++0+";
my $b = BT.new: -436;
my $c = BT.new: "+-++-";
my $x = $a * ( $b - $c );

say 'a == ', $a.Int;
say 'b == ', $b.Int;
say 'c == ', $c.Int;
say "a × (b − c) == ", ~$x, ' == ', $x.Int;

```

Output:

```
a == 523
b == -436
c == 65
a × (b − c) == ----0+--0++0 == -262023
```


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

The **Banker's algorithm** is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue.

Example input

Assuming that the system distinguishes between four types of resources, (A, B, C and D), the following is an example of how those resources could be distributed.

*Note that this example shows the system at an instant before a new request for resources arrives.   Also, the types and number of resources are abstracted.   Real systems, for example, would deal with much larger quantities of each resource.*

```
Total resources in system:
A B C D
6 5 7 6

```

```
Available system resources are:
A B C D
3 1 1 2

```

```
Processes (currently allocated resources):
   A B C D
P1 1 2 2 1
P2 1 0 3 3
P3 1 2 1 0

```

```
Processes (maximum resources):
   A B C D
P1 3 3 2 2
P2 1 2 3 4
P3 1 3 5 0

```

```
Need= maximum resources - currently allocated resources
Processes (need resources):
   A B C D
P1 2 1 0 1
P2 0 2 0 1
P3 0 1 4 0

```

[Assistant]
(formerly Perl 6)
Based on the Python3 solution by Shubham Singh found
here

```
my @avail = <3 1 1 2>;                        # Available instances of resource
my @maxm  = <3 3 2 2>, <1 2 3 4>, <1 3 5 0>;  # Maximum resources that can be allocated to processes
my @allot = <1 2 2 1>, <1 0 3 3>, <1 2 1 0>;  # Resources allocated to processes

# Function to find the system is in safe state or not
sub isSafe(\work is copy, \maxm, \allot) {
    my \P          = allot.elems;     # Number of processes
    my \Pool       = (^P).SetHash;    # Process pool
    my \R          = work.elems;      # Number of resources
    my \need       = maxm »-« allot;  # the need matrix
    my @safe-sequence;

    # While all processes are not finished or system is not in safe state
    my $count = 0;
    while $count < P {
        my $found = False;
        for Pool.keys -> \p {
            if all need[p] »≤« work {    # now process can be finished
                work »+=« allot[p;^R];   # Free the resources
                say 'available resources: ' ~ work;
                @safe-sequence.push: p;  # Add this process to safe sequence
                Pool{p}--;               # Remove this process from Pool
                $count += 1;
                $found = True
            }
        }
        # If we could not find a next process in safe sequence
        return False, "System is not in safe state." unless $found;
    }
    # If system is in safe state then safe sequence will be as below
    return True, "Safe sequence is: " ~ @safe-sequence
}

# Check if system is in a safe state
my ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;
say "Safe state? $safe-state";
say "Message:    $status-message";

```

Output:

```
available resources: 4 3 3 3
available resources: 5 3 6 6
available resources: 6 5 7 6
Safe state? True
Message:    Safe sequence is: 0 1 2
```


[User]
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).

Task

Create this fractal fern, using the following transformations:

* ƒ1   (chosen 1% of the time)

```
        xn + 1 = 0
        yn + 1 = 0.16 yn

```

* ƒ2   (chosen 85% of the time)

```
        xn + 1 = 0.85 xn + 0.04 yn
        yn + 1 = −0.04 xn + 0.85 yn + 1.6

```

* ƒ3   (chosen 7% of the time)

```
        xn + 1 = 0.2 xn − 0.26 yn
        yn + 1 = 0.23 xn + 0.22 yn + 1.6

```

* ƒ4   (chosen 7% of the time)

```
        xn + 1 = −0.15 xn + 0.28 yn
        yn + 1 = 0.26 xn + 0.24 yn + 0.44.

```

Starting position: x = 0, y = 0

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.03

**Translation of**: Perl

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

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

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

my ($x, $y) = (0, 0);

for ^2e5 {
    my $r = 100.rand;
    ($x, $y) = do given $r {
        when  $r <=  1 { (                     0,              0.16 * $y       ) }
        when  $r <=  8 { ( 0.20 * $x - 0.26 * $y,  0.23 * $x + 0.22 * $y + 1.60) }
        when  $r <= 15 { (-0.15 * $x + 0.28 * $y,  0.26 * $x + 0.24 * $y + 0.44) }
        default        { ( 0.85 * $x + 0.04 * $y, -0.04 * $x + 0.85 * $y + 1.60) }
    };
    $png.set(($w / 2 + $x * 60).Int, ($h - $y * 60).Int, 0, 255, 0);
}

$png.write: 'Barnsley-fern-perl6.png';

```


[User]
Task

Show in decimal notation all positive integers (less than **501**) which, when converted to hexadecimal notation, cannot be written without using at least one non-decimal digit ('a' to 'f').

[Assistant]
Yet another poorly specced, poorly named, trivial task.

How many integers in base 16 cannot be written without using a hexadecimal digit? All of them. Or none of them.

Base 16 is not hexadecimal. Hexadecimal is *an implementation* of base 16.

```
use Base::Any;
set-digits <⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ㉑ ㉒ ㉓ ㉔ ㉕>;
say (7**35).&to-base(16);

# ⑭㉒⑱⑩⑰⑰⑳⑮⑱⑳⑩⑳⑱㉒㉑⑰㉒⑫⑭⑲⑯⑩㉔⑮⑰

```

How many of those glyphs are decimal digits? And yet it **is** in base 16, albeit with non-standard digit glyphs. So they **all** can be written without using a hexadecimal digit.

But wait a minute; is 2 a hexadecimal digit? Why yes, yes it is. So *none* of them can be written in hexadecimal without using a hexadecimal digit.

Bah. Show which when written in base 16, contain a digit glyph with a value greater than 9:

```
put display :20cols, :fmt('%3d'), (^501).grep( { so any |.map: { .polymod(16 xx *) »>» 9 } } );

sub display ($list, :$cols = 10, :$fmt = '%6d', :$title = "{+$list} matching:\n" )   {
    cache $list;
    $title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}

```

Output:

```
301 matching:
 10  11  12  13  14  15  26  27  28  29  30  31  42  43  44  45  46  47  58  59
 60  61  62  63  74  75  76  77  78  79  90  91  92  93  94  95 106 107 108 109
110 111 122 123 124 125 126 127 138 139 140 141 142 143 154 155 156 157 158 159
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 266 267 268 269
270 271 282 283 284 285 286 287 298 299 300 301 302 303 314 315 316 317 318 319
330 331 332 333 334 335 346 347 348 349 350 351 362 363 364 365 366 367 378 379
380 381 382 383 394 395 396 397 398 399 410 411 412 413 414 415 416 417 418 419
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
500
```

But wait a minute. Let's take another look at the the task title. **Base-16 representation**. It isn't talking about Base 16 at all. It's talking about Base**-16**... so let's do it in base -16.

```
use Base::Any;

put display :20cols, :fmt('%3d'), (^501).grep( { .&to-base(-16).contains: /<[A..F]>/ } );

sub display ($list, :$cols = 10, :$fmt = '%6d', :$title = "{+$list} matching:\n" )   {
    cache $list;
    $title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}

```

Output:

```
306 matching:
 10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29
 30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49
 50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69
 70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
 90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109
110 111 122 123 124 125 126 127 138 139 140 141 142 143 154 155 156 157 158 159
170 171 172 173 174 175 186 187 188 189 190 191 202 203 204 205 206 207 218 219
220 221 222 223 234 235 236 237 238 239 250 251 252 253 254 255 266 267 268 269
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 378 379
380 381 382 383 394 395 396 397 398 399 410 411 412 413 414 415 426 427 428 429
430 431 442 443 444 445 446 447 458 459 460 461 462 463 474 475 476 477 478 479
490 491 492 493 494 495
```

Of course, if you are looking for the **count** of the hexadecimal numbers up to some threshold that only use "decimal" digits, it is silly and counter-productive to iterate through them and check ***each*** when you really only need to check ***one***.

```
use Lingua::EN::Numbers;

for 500
   ,10**8
   ,10**25
   ,10**35
   -> $threshold {
    my $limit = $threshold.base(16);
    my $i  = $limit.index: ['A'..'F'];
    quietly $limit = $limit.substr(0, $i) ~ ('9' x ($limit.chars - $i)) if $i.Str;

    for '  CAN  ', $limit,
        'CAN NOT', $threshold - $limit {
        printf( "Quantity of numbers up to %s that %s be expressed in hexadecimal without using any alphabetics: %*s\n",
         comma($threshold), $^a, comma($threshold).chars, comma($^c) )
    }

    say '';
}

```

Output:

```
Quantity of numbers up to 500 that   CAN   be expressed in hexadecimal without using any alphabetics: 199
Quantity of numbers up to 500 that CAN NOT be expressed in hexadecimal without using any alphabetics: 301

Quantity of numbers up to 100,000,000 that   CAN   be expressed in hexadecimal without using any alphabetics:   5,999,999
Quantity of numbers up to 100,000,000 that CAN NOT be expressed in hexadecimal without using any alphabetics:  94,000,001

Quantity of numbers up to 10,000,000,000,000,000,000,000,000 that   CAN   be expressed in hexadecimal without using any alphabetics:        845,951,614,014,849,999,999
Quantity of numbers up to 10,000,000,000,000,000,000,000,000 that CAN NOT be expressed in hexadecimal without using any alphabetics:  9,999,154,048,385,985,150,000,001

Quantity of numbers up to 100,000,000,000,000,000,000,000,000,000,000,000 that   CAN   be expressed in hexadecimal without using any alphabetics:         134,261,729,999,999,999,999,999,999,999
Quantity of numbers up to 100,000,000,000,000,000,000,000,000,000,000,000 that CAN NOT be expressed in hexadecimal without using any alphabetics:  99,999,865,738,270,000,000,000,000,000,000,001
```


[User]
The popular encoding of small and medium-sized checksums is base16, that is more compact than usual base10 and is human readable... For checksums resulting in *hash digests* bigger than ~100 bits, the base16 is too long: base58 is shorter and (when using good alphabet) preserves secure human readability. The most popular alphabet of base58 is the variant used in bitcoin address (see Bitcoin/address validation), so it is the "default base58 alphabet".

Write a program that takes a checksum (resultant hash digest) *integer binary* representation as argument, and converts (encode it) into base58 with the standard Bitcoin alphabet — which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:

:   :   :   * **O**   the uppercase letter "oh",
            * **I**    the uppercase letter "eye",
            * **l**    the lowercase letter "ell",   and
            * **0**   the digit zero.

The *reference algorithm* is at the Bitcoin's Base58Check page.

[Assistant]
(formerly Perl 6)

```
sub encode_Base58 ( Int $x ) {
    constant @codes = <
          1 2 3 4 5 6 7 8 9
        A B C D E F G H   J K L M N   P Q R S T U V W X Y Z
        a b c d e f g h i j k   m n o p q r s t u v w x y z
    >;

    return @codes[ $x.polymod( 58 xx * ) ].join.flip;
}

my @tests =
    25420294593250030202636073700053352635053786165627414518 => '6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM',
    0x61                    => '2g',
    0x626262                => 'a3gV',
    0x636363                => 'aPEr',
    0x73696d706c792061206c6f6e6720737472696e67 => '2cFupjhnEsSn59qHXstmK2ffpLv2',
    0x516b6fcd0f            => 'ABnLTmg',
    0xbf4f89001e670274dd    => '3SEo3LWLoPntC',
    0x572e4794              => '3EFU7m',
    0xecac89cad93923c02321  => 'EJDM8drfXA6uyA',
    0x10c8511e              => 'Rt5zm',
;
use Test;
for @tests {
    is encode_Base58(.key), .value, "{.key} encodes to {.value}";
}

```


[User]
See Base64 encode data.

Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file.

When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.11

```
my $e64 = '
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2
9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
';

my @base64map = flat 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';
my %base64 is default(0) = @base64map.pairs.invert;

sub base64-decode-slow ($enc) {
    my $buf = Buf.new;
    for $enc.subst(/\s/, '', :g).comb(4) -> $chunck {
        $buf.append: |(sprintf "%06d%06d%06d%06d", |$chunck.comb.map:
            {%base64{$_}.base(2)}).comb(8).map: {:2($_)};
    }
    $buf
}

say 'Slow:';
say base64-decode-slow($e64).decode('utf8');

# Of course, the above routine is slow and is only for demonstration purposes.
# For real code you should use a module, which is MUCH faster and heavily tested.
say "\nFast:";
use Base64::Native;
say base64-decode($e64).decode('utf8');

```

Output:

```
Slow:
To err is human, but to really foul things up you need a computer.
    -- Paul R. Ehrlich

Fast:
To err is human, but to really foul things up you need a computer.
    -- Paul R. Ehrlich
```


[User]
Convert an array of bytes or binary string to the base64-encoding of that string and output that value. Use the icon for Rosetta Code as the data to convert.

See also Base64 decode data.

[Assistant]
(formerly Perl 6)

```
sub MAIN {
    my $buf = slurp("./favicon.ico", :bin);
    say buf-to-Base64($buf);
}

my @base64map = flat 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';

sub buf-to-Base64($buf) {
    join '', gather for $buf.list -> $a, $b = [], $c = [] {
        my $triplet = ($a +< 16) +| ($b +< 8) +| $c;
        take @base64map[($triplet +> (6 * 3)) +& 0x3F];
        take @base64map[($triplet +> (6 * 2)) +& 0x3F];
        if $c.elems {
            take @base64map[($triplet +> (6 * 1)) +& 0x3F];
            take @base64map[($triplet +> (6 * 0)) +& 0x3F];
        }
        elsif $b.elems {
            take @base64map[($triplet +> (6 * 1)) +& 0x3F];
            take '=';
        }
        else { take '==' }
    }
}

```

Output:

```
AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAA...QAAAAEAAAABAAAAAQAAAAE=
```


[User]
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly **n** elements. Each element of the sequence **Bn** is the number of partitions of a set of size **n** where order of the elements and order of the partitions are non-significant. E.G.: **{a b}** is the same as **{b a}** and **{a} {b}** is the same as **{b} {a}**.

So

:   **B0 = 1** trivially. There is only one way to partition a set with zero elements. **{ }**

:   **B1 = 1** There is only one way to partition a set with one element. **{a}**

:   **B2 = 2** Two elements may be partitioned in two ways. **{a} {b}, {a b}**

:   **B3 = 5** Three elements may be partitioned in five ways **{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}**

:   and so on.

A simple way to find the Bell numbers is construct a **Bell triangle**, also known as an **Aitken's array** or **Peirce triangle**, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.

Task

Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the **first 15** and (if your language supports big Integers) **50th** elements of the sequence.

If you *do* use the Bell triangle method to generate the numbers, also show the **first ten rows** of the Bell triangle.

See also

:   * **OEIS:A000110 Bell or exponential numbers**
    * **OEIS:A011971 Aitken's array**

[Assistant]
(formerly Perl 6)

### via Aitken's array

**Works with**: Rakudo version 2019.03

```
 my @Aitkens-array = lazy [1], -> @b {
     my @c = @b.tail;
     @c.push: @b[$_] + @c[$_] for ^@b;
     @c
 } ... *;

 my @Bell-numbers = @Aitkens-array.map: { .head };

say "First fifteen and fiftieth Bell numbers:";
printf "%2d: %s\n", 1+$_, @Bell-numbers[$_] for flat ^15, 49;

say "\nFirst ten rows of Aitken's array:";
.say for @Aitkens-array[^10];

```

Output:

```
First fifteen and fiftieth Bell numbers:
 1: 1
 2: 1
 3: 2
 4: 5
 5: 15
 6: 52
 7: 203
 8: 877
 9: 4140
10: 21147
11: 115975
12: 678570
13: 4213597
14: 27644437
15: 190899322
50: 10726137154573358400342215518590002633917247281

First ten rows of Aitken's array:
[1]
[1 2]
[2 3 5]
[5 7 10 15]
[15 20 27 37 52]
[52 67 87 114 151 203]
[203 255 322 409 523 674 877]
[877 1080 1335 1657 2066 2589 3263 4140]
[4140 5017 6097 7432 9089 11155 13744 17007 21147]
[21147 25287 30304 36401 43833 52922 64077 77821 94828 115975]
```

### via Recurrence relation

**Works with**: Rakudo version 2019.03

```
sub binomial { [*] ($^n … 0) Z/ 1 .. $^p }

my @bell = 1, -> *@s { [+] @s »*« @s.keys.map: { binomial(@s-1, $_) }  } … *;

.say for @bell[^15], @bell[50 - 1];

```

Output:

```
(1 1 2 5 15 52 203 877 4140 21147 115975 678570 4213597 27644437 190899322)
10726137154573358400342215518590002633917247281
```

### via Stirling sums

**Works with**: Rakudo version 2019.03

```
my @Stirling_numbers_of_the_second_kind =
    (1,),
    { (0, |@^last) »+« (|(@^last »*« @^last.keys), 0) } … *
;
my @bell = @Stirling_numbers_of_the_second_kind.map: *.sum;

.say for @bell.head(15), @bell[50 - 1];

```

Output:

```
(1 1 2 5 15 52 203 877 4140 21147 115975 678570 4213597 27644437 190899322)
10726137154573358400342215518590002633917247281
```


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

**Benford's law**, also called the **first-digit law**, refers to the frequency distribution of digits in many (but not all) real-life sources of data.

In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.

Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.

This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.

A set of numbers is said to satisfy Benford's law if the leading digit

d
{\displaystyle {\displaystyle d}}
  (

d
∈
{
1
,
…
,
9
}
{\displaystyle {\displaystyle d\in \{1,\ldots ,9\}}}
) occurs with probability

:   :   :   :   P
                (
                d
                )
                =

                log

                10

                (
                d
                +
                1
                )
                −

                log

                10

                (
                d
                )
                =

                log

                10

                (

                1
                +

                1
                d
                )
                {\displaystyle {\displaystyle P(d)=\log \_{10}(d+1)-\log \_{10}(d)=\log \_{10}\left(1+{\frac {1}{d}}\right)}}

For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).

Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.

You can generate them or load them from a file; whichever is easiest.

Display your actual vs expected distribution.

*For extra credit:* Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.

See also:

* numberphile.com.
* A starting page on Wolfram Mathworld is Benfords Law .

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016-10-24

```
sub benford(@a) { bag +« @a».substr(0,1) }

sub show(%distribution) {
    printf "%9s %9s  %s\n", <Actual Expected Deviation>;
    for 1 .. 9 -> $digit {
        my $actual = %distribution{$digit} * 100 / [+] %distribution.values;
        my $expected = (1 + 1 / $digit).log(10) * 100;
        printf "%d: %5.2f%% | %5.2f%% | %.2f%%\n",
          $digit, $actual, $expected, abs($expected - $actual);
    }
}

multi MAIN($file) { show benford $file.IO.lines }
multi MAIN() { show benford ( 1, 1, 2, *+* ... * )[^1000] }

```

**Output:** First 1000 Fibonaccis

```
   Actual  Expected  Deviation
1: 30.10% | 30.10% | 0.00%
2: 17.70% | 17.61% | 0.09%
3: 12.50% | 12.49% | 0.01%
4:  9.60% |  9.69% | 0.09%
5:  8.00% |  7.92% | 0.08%
6:  6.70% |  6.69% | 0.01%
7:  5.60% |  5.80% | 0.20%
8:  5.30% |  5.12% | 0.18%
9:  4.50% |  4.58% | 0.08%
```

**Extra credit:** Square Kilometers of land under cultivation, by country / territory. First column from Wikipedia: Land use statistics by country.

```
   Actual  Expected  Deviation
1: 33.33% | 30.10% | 3.23%
2: 18.31% | 17.61% | 0.70%
3: 13.15% | 12.49% | 0.65%
4:  8.45% |  9.69% | 1.24%
5:  9.39% |  7.92% | 1.47%
6:  5.63% |  6.69% | 1.06%
7:  4.69% |  5.80% | 1.10%
8:  5.16% |  5.12% | 0.05%
9:  1.88% |  4.58% | 2.70%
```


[User]
The **Berlekamp–Massey algorithm** is an efficient algorithm for finding the shortest linear feedback shift register (LFSR) that generates a given sequence over a finite field. It determines the minimal polynomial of a linearly recurrent sequence, which is crucial in applications like error-correcting codes, cryptography, and sequence analysis.

Overview

Given a sequence of elements

s

0
,

s

1
,
…
,

s

n
−
1
{\displaystyle {\displaystyle s\_{0},s\_{1},\dots ,s\_{n-1}}}
 from a finite field, the Berlekamp–Massey algorithm computes the shortest LFSR, characterized by its connection polynomial

C
(
x
)
=
1
+

c

1
x
+

c

2

x

2
+
⋯
+

c

L

x

L
{\displaystyle {\displaystyle C(x)=1+c\_{1}x+c\_{2}x^{2}+\dots +c\_{L}x^{L}}}
, such that the sequence satisfies the recurrence relation:

:   s

    i
    +
    L
    =
    −

    ∑

    k
    =
    1

    L

    c

    k

    s

    i
    +
    L
    −
    k
    {\displaystyle {\displaystyle s\_{i+L}=-\sum \_{k=1}^{L}c\_{k}s\_{i+L-k}}}

for all valid indices. The degree

L
{\displaystyle {\displaystyle L}}
 of the polynomial is the *linear complexity* of the sequence, representing the length of the shortest LFSR.

History

The algorithm was independently developed by Elwyn Berlekamp in 1968 for decoding BCH codes and by James Massey in 1969 for cryptographic applications. It remains a cornerstone in coding theory and sequence analysis.

Algorithm Description

The Berlekamp–Massey algorithm iteratively constructs the connection polynomial by processing the input sequence element by element. It maintains a current polynomial

C
(
x
)
{\displaystyle {\displaystyle C(x)}}
 and updates it whenever a discrepancy is found between the predicted and actual sequence values. The key steps are:

1. Initialize

C
(
x
)
=
1
{\displaystyle {\displaystyle C(x)=1}}
, degree

L
=
0
{\displaystyle {\displaystyle L=0}}
, and a temporary polynomial

B
(
x
)
=
1
{\displaystyle {\displaystyle B(x)=1}}
.
2. For each sequence element

s

i
{\displaystyle {\displaystyle s\_{i}}}
:

```
  * Compute the discrepancy

            Δ
            =

              s

                i

            +

              ∑

                k
                =
                1

                L

              c

                k

              s

                i
                −
                k

    {\displaystyle {\displaystyle \Delta =s_{i}+\sum _{k=1}^{L}c_{k}s_{i-k}}}

.
  * If

            Δ
            ≠
            0

    {\displaystyle {\displaystyle \Delta \neq 0}}

:
    * Update

            C
            (
            x
            )
            ←
            C
            (
            x
            )
            −
            Δ
            x
            B
            (
            x
            )

    {\displaystyle {\displaystyle C(x)\leftarrow C(x)-\Delta xB(x)}}

.
    * If the discrepancy indicates a need for a longer LFSR (i.e.,

            2
            L
            ≤
            i

    {\displaystyle {\displaystyle 2L\leq i}}

), update

            L

    {\displaystyle {\displaystyle L}}

 and adjust

            B
            (
            x
            )

    {\displaystyle {\displaystyle B(x)}}

.

```

3. Output

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

L
{\displaystyle {\displaystyle L}}
.

The algorithm runs in

O
(

n

2
)
{\displaystyle {\displaystyle O(n^{2})}}
 time, where

n
{\displaystyle {\displaystyle n}}
 is the sequence length, and uses

O
(
n
)
{\displaystyle {\displaystyle O(n)}}
 space.

Applications

* **Error Correction**: Used in decoding Reed–Solomon codes and BCH codes.
* **Cryptography**: Analyzes the linear complexity of sequences in stream ciphers to assess security.
* **Sequence Analysis**: Identifies patterns in sequences for signal processing and data compression.

Example

For the binary sequence

0
,
0
,
1
,
1
,
0
,
1
,
0
{\displaystyle {\displaystyle 0,0,1,1,0,1,0}}
 over

G
F
(
2
)
{\displaystyle {\displaystyle GF(2)}}
, the algorithm yields the connection polynomial

C
(
x
)
=
1
+
x
+

x

3
{\displaystyle {\displaystyle C(x)=1+x+x^{3}}}
, indicating a linear complexity of 3.

[Assistant]
**Translation of**: Python

```
# 20250510 Raku programming solution

constant MOD = 2;

sub berlekamp_massey(@a) {
   my ($n, $w, $delta, @ans_coef, @lst) = @a.elems - 1, 0;
   for 1 .. $n -> $i {
      my $tmp = 0;
      for ^@ans_coef.elems -> $j {
         if $i - 1 - $j >= 1 {
            $tmp = ($tmp + @a[$i - 1 - $j] * @ans_coef[$j]) % MOD;
         }
      }
      my $discrepancy = (@a[$i] - $tmp + MOD) % MOD;
      next if $discrepancy == 0;
      if $w == 0 {
         @ans_coef = (0 xx $i);
         $w = $i;
         $delta = $discrepancy;
         next;
      }
      my @now = @ans_coef;
      my $mul = $discrepancy * expmod($delta, MOD - 2, MOD);
      my $needed_len = @lst.elems + $i - $w;
      if @ans_coef.elems < $needed_len {
         @ans_coef.append: (0 xx ($needed_len - @ans_coef.elems));
      }
      if $i - $w - 1 >= 0 {
         @ans_coef[$i - $w - 1] = (@ans_coef[$i - $w - 1] + $mul) % MOD;
      }
      for ^@lst.elems -> $j {
         my $idx = $i - $w + $j;
         if $idx < @ans_coef.elems {
            my $term_to_subtract = ($mul * @lst[$j]) % MOD;
            @ans_coef[$idx] = (@ans_coef[$idx] - $term_to_subtract + MOD) % MOD;
         }
      }
      if @ans_coef.elems > @now.elems {
         @lst = @now;
         $w = $i;
         $delta = $discrepancy;
      }
   }
   return @ans_coef.map: { ($^x + MOD) % MOD };
}

sub calculate_term($m, @coef, @h) {
   if $m < @h.elems                { return (@h[$m] + MOD) % MOD }
   if ( my $k = @coef.elems ) == 0 { return 0 }
   my @p_coeffs = (1, |@coef);
   sub poly_mul(@a, @b, $degree_k, @p_poly) {
      my @res = (0 xx (2 * $degree_k));
      for ^$degree_k X ^$degree_k -> ($i, $j) {
         next if @a[$i] == 0;
         @res[$i + $j] = (@res[$i + $j] + @a[$i] * @b[$j]) % MOD;
      }
      for ( 2 * $degree_k - 1 ... $degree_k ) -> $i {
         next if @res[$i] == 0;
         my $term = @res[$i];
         @res[$i] = 0;
         for 0 .. $degree_k -> $j {
            if ( my $idx = $i - $j ) >= 0 {
               @res[$idx] = (@res[$idx] + $term * @p_poly[$j]) % MOD;
            }
         }
      }
      return @res[0 ... ^$degree_k];
   }
   my @f = (1, |(0 xx ($k - 1)));
   my @g = $k == 1 ?? (@p_coeffs[1],) !! (0, 1, |(0 xx ($k - 2)));
   my $power = $m;
   while $power > 0 {
      unless $power %% 2 { @f = poly_mul(@f, @g, $k, @p_coeffs) }
      @g = poly_mul(@g, @g, $k, @p_coeffs);
      $power div= 2;
   }
   my $final_ans = 0;
   for ^$k -> \k {
      if k+1 < @h.elems { $final_ans = ($final_ans + @h[k+1] * @f[k]) % MOD }
   }
   return ($final_ans + MOD) % MOD;
}

sub solve {
   my @h_input = 0,0,1,1,0,1,0;
   my $n = @h_input.elems;
   my @h = 0, |@h_input;
   my @ans_coef = berlekamp_massey(@h);
   say @ans_coef.map({ ($^x + MOD) % MOD }).Str;
   my $m = 10;
   my $result = calculate_term($m, @ans_coef, @h);
   say ($result + MOD) % MOD;
}

solve();

```

You may Attempt This Online!


[User]
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis.

Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   *The National Institute of Standards and Technology convention*).

The   nth   Bernoulli number is expressed as   **B**n.

Task

:   * show the Bernoulli numbers   **B**0   through   **B**60.
    * suppress the output of values which are equal to zero.   (Other than   **B**1 , all   *odd*   Bernoulli numbers have a value of zero.)
    * express the Bernoulli numbers as fractions  (most are improper fractions).
    * the fractions should be reduced.
    * index each number in some way so that it can be discerned which Bernoulli number is being displayed.
    * align the solidi   (**/**)   if used  (extra credit).

An algorithm

The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows:

```
 for m from 0 by 1 to n do
    A[m] ← 1/(m+1)
    for j from m by -1 to 1 do
      A[j-1] ← j×(A[j-1] - A[j])
  return A[0] (which is Bn)

```

See also

* Sequence A027641 Numerator of Bernoulli number B\_n on The On-Line Encyclopedia of Integer Sequences.
* Sequence A027642 Denominator of Bernoulli number B\_n on The On-Line Encyclopedia of Integer Sequences.
* Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).
* Luschny's The Bernoulli Manifesto for a discussion on    **B1   =   -½**   versus   **+½**.

[Assistant]
(formerly Perl 6)

### Simple

First, a straighforward implementation of the naïve algorithm in the task description.

**Works with**: Rakudo version 2015.12

```
sub bernoulli($n) {
    my @a;
    for 0..$n -> $m {
        @a[$m] = FatRat.new(1, $m + 1);
        for reverse 1..$m -> $j {
          @a[$j - 1] = $j * (@a[$j - 1] - @a[$j]);
        }
    }
    return @a[0];
}

constant @bpairs = grep *.value.so, ($_ => bernoulli($_) for 0..60);

my $width = max @bpairs.map: *.value.numerator.chars;
my $form = "B(%2d) = \%{$width}d/%d\n";

printf $form, .key, .value.nude for @bpairs;

```

Output:

```
B( 0) =                                            1/1
B( 1) =                                            1/2
B( 2) =                                            1/6
B( 4) =                                           -1/30
B( 6) =                                            1/42
B( 8) =                                           -1/30
B(10) =                                            5/66
B(12) =                                         -691/2730
B(14) =                                            7/6
B(16) =                                        -3617/510
B(18) =                                        43867/798
B(20) =                                      -174611/330
B(22) =                                       854513/138
B(24) =                                   -236364091/2730
B(26) =                                      8553103/6
B(28) =                                 -23749461029/870
B(30) =                                8615841276005/14322
B(32) =                               -7709321041217/510
B(34) =                                2577687858367/6
B(36) =                        -26315271553053477373/1919190
B(38) =                             2929993913841559/6
B(40) =                       -261082718496449122051/13530
B(42) =                       1520097643918070802691/1806
B(44) =                     -27833269579301024235023/690
B(46) =                     596451111593912163277961/282
B(48) =                -5609403368997817686249127547/46410
B(50) =                  495057205241079648212477525/66
B(52) =              -801165718135489957347924991853/1590
B(54) =             29149963634884862421418123812691/798
B(56) =          -2479392929313226753685415739663229/870
B(58) =          84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730
```

### With memoization

Here is a much faster way, following the Perl solution that avoids recalculating previous values each time through the function. We do this in Raku by not defining it as a function at all, but by defining it as an infinite sequence that we can read however many values we like from (52, in this case, to get up to B(100)). In this solution we've also avoided subscripting operations; rather we use a sequence operator (...) iterated over the list of the previous solution to find the next solution. We reverse the array in this case to make reference to the previous value in the list more natural, which means we take the last value of the list rather than the first value, and do so conditionally to avoid 0 values.

**Works with**: Rakudo version 2015.12

```
constant bernoulli = gather {
    my @a;
    for 0..* -> $m {
        @a = FatRat.new(1, $m + 1),
                -> $prev {
                    my $j = @a.elems;
                    $j * (@a.shift - $prev);
                } ... { not @a.elems }
        take $m => @a[*-1] if @a[*-1];
    }
}

constant @bpairs = bernoulli[^52];

my $width = max @bpairs.map: *.value.numerator.chars;
my $form = "B(%d)\t= \%{$width}d/%d\n";

printf $form, .key, .value.nude for @bpairs;

```

Output:

```
B(0)	=                                                                                1/1
B(1)	=                                                                                1/2
B(2)	=                                                                                1/6
B(4)	=                                                                                -1/30
B(6)	=                                                                                1/42
B(8)	=                                                                                -1/30
B(10)	=                                                                                5/66
B(12)	=                                                                                -691/2730
B(14)	=                                                                                7/6
B(16)	=                                                                                -3617/510
B(18)	=                                                                                43867/798
B(20)	=                                                                              -174611/330
B(22)	=                                                                               854513/138
B(24)	=                                                                           -236364091/2730
B(26)	=                                                                              8553103/6
B(28)	=                                                                         -23749461029/870
B(30)	=                                                                        8615841276005/14322
B(32)	=                                                                       -7709321041217/510
B(34)	=                                                                        2577687858367/6
B(36)	=                                                                -26315271553053477373/1919190
B(38)	=                                                                     2929993913841559/6
B(40)	=                                                               -261082718496449122051/13530
B(42)	=                                                               1520097643918070802691/1806
B(44)	=                                                             -27833269579301024235023/690
B(46)	=                                                             596451111593912163277961/282
B(48)	=                                                        -5609403368997817686249127547/46410
B(50)	=                                                          495057205241079648212477525/66
B(52)	=                                                      -801165718135489957347924991853/1590
B(54)	=                                                     29149963634884862421418123812691/798
B(56)	=                                                  -2479392929313226753685415739663229/870
B(58)	=                                                  84483613348880041862046775994036021/354
B(60)	=                                         -1215233140483755572040304994079820246041491/56786730
B(62)	=                                               12300585434086858541953039857403386151/6
B(64)	=                                          -106783830147866529886385444979142647942017/510
B(66)	=                                       1472600022126335654051619428551932342241899101/64722
B(68)	=                                        -78773130858718728141909149208474606244347001/30
B(70)	=                                    1505381347333367003803076567377857208511438160235/4686
B(72)	=                             -5827954961669944110438277244641067365282488301844260429/140100870
B(74)	=                                   34152417289221168014330073731472635186688307783087/6
B(76)	=                               -24655088825935372707687196040585199904365267828865801/30
B(78)	=                            414846365575400828295179035549542073492199375372400483487/3318
B(80)	=                       -4603784299479457646935574969019046849794257872751288919656867/230010
B(82)	=                        1677014149185145836823154509786269900207736027570253414881613/498
B(84)	=                 -2024576195935290360231131160111731009989917391198090877281083932477/3404310
B(86)	=                      660714619417678653573847847426261496277830686653388931761996983/6
B(88)	=              -1311426488674017507995511424019311843345750275572028644296919890574047/61410
B(90)	=            1179057279021082799884123351249215083775254949669647116231545215727922535/272118
B(92)	=           -1295585948207537527989427828538576749659341483719435143023316326829946247/1410
B(94)	=            1220813806579744469607301679413201203958508415202696621436215105284649447/6
B(96)	=   -211600449597266513097597728109824233673043954389060234150638733420050668349987259/4501770
B(98)	=        67908260672905495624051117546403605607342195728504487509073961249992947058239/6
B(100)	= -94598037819122125295227433069493721872702841533066936133385696204311395415197247711/33330
```

### Functional

And if you're a pure enough FP programmer to dislike destroying and reconstructing the array each time, here's the same algorithm without side effects. We use zip with the pair constructor => to keep values associated with their indices. This provides sufficient local information that we can define our own binary operator "bop" to reduce between each two terms, using the "triangle" form (called "scan" in Haskell) to return the intermediate results that will be important to compute the next Bernoulli number.

**Works with**: Rakudo version 2016.12

```
sub infix:<bop>(\prev, \this) {
    this.key => this.key * (this.value - prev.value)
}

sub next-bernoulli ( (:key($pm), :value(@pa)) ) {
    $pm + 1 => [
        map *.value,
        [\bop] ($pm + 2 ... 1) Z=> FatRat.new(1, $pm + 2), |@pa
    ]
}

constant bernoulli =
    grep *.value,
    map { .key => .value[*-1] },
    (0 => [FatRat.new(1,1)], &next-bernoulli ... *)
;

constant @bpairs = bernoulli[^52];

my $width = max @bpairs.map: *.value.numerator.chars;
my $form = "B(%d)\t= \%{$width}d/%d\n";

printf $form, .key, .value.nude for @bpairs;

```

Same output as memoization example


[User]
The

n
+
1
{\displaystyle {\displaystyle n+1}}
 Bernstein basis polynomials of degree

n
{\displaystyle {\displaystyle n}}
 are defined as

:   b

    k
    ,
    n
    (
    t
    )
    =

    (

    n
    k

    )

    t

    k

    (

    1
    −
    t
    )

    n
    −
    k
    ,

    k
    =
    0
    ,
    …
    ,
    n
    {\displaystyle {\displaystyle b\_{k,n}(t)={\binom {n}{k}}t^{k}\left(1-t\right)^{n-k},\quad k=0,\ldots ,n}}

Any real polynomial can written as a linear combination of such Bernstein basis polynomials. Let us call the coefficients in such linear combinations *Bernstein coefficients*.

The goal of this task is to write subprograms for working with degree-2 and degree-3 Bernstein coefficients. A programmer is likely to have to deal with such representations. For example, OpenType fonts store glyph outline data as as either degree-2 or degree-3 Bernstein coefficients.

The task is as follows:

1. Write a subprogram (which we will call *Subprogram (1)*) to transform the ordinary monomial coefficients of a real polynomial, of degree 2 or less, to Bernstein coefficients for the degree-2 basis.
2. Write *Subprogram (2)* to evaluate, at a given point, a real polynomial written in degree-2 Bernstein coefficients. For this use de Casteljau's algorithm.
3. Write *Subprogram (3)* to transform the monomial coefficients of a real polynomial, of degree 3 or less, to Bernstein coefficients for degree 3.
4. Write *Subprogram (4)* to evaluate, at a given point, a real polynomial written in degree-3 Bernstein coefficients. Use de Casteljau's algorithm.
5. Write *Subprogram (5)* to transform Bernstein coefficients for degree 2 to Bernstein coefficients for degree 3.
6. For the following polynomials, use *Subprogram (1)* to find Bernstein coefficients for the degree-2 basis:

   p
   (
   x
   )
   =
   1
   {\displaystyle {\displaystyle p(x)=1}}
   ,

   q
   (
   x
   )
   =
   1
   +
   2
   x
   +
   3

   x

   2
   {\displaystyle {\displaystyle q(x)=1+2x+3x^{2}}}
   . Display the results.
7. Use *Subprogram (2)* to evaluate

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

   q
   (
   x
   )
   {\displaystyle {\displaystyle q(x)}}
    at

   x
   =
   0.25
   {\displaystyle {\displaystyle x=0.25}}
    and at

   x
   =
   7.50
   {\displaystyle {\displaystyle x=7.50}}
   . Display the results. Optionally also evaluate the polynomials in the monomial basis and display the results. (For the monomial basis it is best to use a Horner scheme.)
8. Use *Subprogram (3)* to find degree-3 Bernstein coefficients for

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

   q
   (
   x
   )
   {\displaystyle {\displaystyle q(x)}}
   , and additionally also for

   r
   (
   x
   )
   =
   1
   +
   2
   x
   +
   3

   x

   2
   +
   4

   x

   3
   {\displaystyle {\displaystyle r(x)=1+2x+3x^{2}+4x^{3}}}
   . Display the results.
9. Use *Subprogram (4)* to evaluate

   p
   (
   x
   )
   {\displaystyle {\displaystyle p(x)}}
   ,

   q
   (
   x
   )
   {\displaystyle {\displaystyle q(x)}}
   , and

   r
   (
   x
   )
   {\displaystyle {\displaystyle r(x)}}
    at

   x
   =
   0.25
   {\displaystyle {\displaystyle x=0.25}}
    and

   x
   =
   7.50
   {\displaystyle {\displaystyle x=7.50}}
   . Display the results. Optionally also evaluate them in the monomial basis and display the results. (You may have done that already for

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

   q
   (
   x
   )
   {\displaystyle {\displaystyle q(x)}}
   .)
10. Use *Subprogram (5)* to get degree-3 Bernstein coefficients for

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

    q
    (
    x
    )
    {\displaystyle {\displaystyle q(x)}}
     from their degree-2 Bernstein coefficients. Display the results.

ALGOL 60 and Python implementations are provided as initial examples. The latter does the optional monomial-basis evaluations.

You can use the following algorithms. They are written in unambiguous Algol 60 reference language instead of a made up pseudo-language. The ALGOL 60 example was necessary to check my work, but these reference versions are in the actual standard language designed for the printing of algorithms.

```
procedure tobern2 (a0, a1, a2, b0, b1, b2);
 value a0, a1, a2; comment pass by value;
 real a0, a1, a2;
 real b0, b1, b2;
comment Subprogram (1): transform monomial coefficients a0, a1, a2 to Bernstein coefficients b0, b1, b2;
begin
 b0 := a0;
 b1 := a0 + ((1/2) × a1);
 b2 := a0 + a1 + a2
end tobern2;

```

```
real procedure evalbern2 (b0, b1, b2, t);
 value b0, b1, b2, t;
 real b0, b1, b2, t;
comment Subprogram (2): evaluate, at t, the polynomial with Bernstein coefficients b0, b1, b2. Use de Casteljau’s algorithm;
begin
 real s, b01, b12, b012;
 s := 1 - t;
 b01 := (s × b0) + (t × b1);
 b12 := (s × b1) + (t × b2);
 b012 := (s × b01) + (t × b12);
 evalbern2 := b012
end evalbern2;

```

```
procedure tobern3 (a0, a1, a2, a3, b0, b1, b2, b3);
 value a0, a1, a2, a3;
 real a0, a1, a2, a3;
 real b0, b1, b2, b3;
comment Subprogram (3): transform monomial coefficients a0, a1, a2, a3 to Bernstein coefficients b0, b1, b2, b3;
begin
 b0 := a0;
 b1 := a0 + ((1/3) × a1);
 b2 := a0 + ((2/3) × a1) + ((1/3) × a2);
 b3 := a0 + a1 + a2 + a3
end tobern3;

```

```
real procedure evalbern3 (b0, b1, b2, b3, t);
 value b0, b1, b2, b3, t;
 real b0, b1, b2, b3, t;
comment Subprogram (4): evaluate, at t, the polynomial with Bernstein coefficients b0, b1, b2, b3. Use de Casteljau's algorithm;
begin
 real s, b01, b12, b23, b012, b123, b0123;
 s := 1 - t;
 b01 := (s × b0) + (t × b1);
 b12 := (s × b1) + (t × b2);
 b23 := (s × b2) + (t × b3);
 b012 := (s × b01) + (t × b12);
 b123 := (s × b12) + (t × b23);
 b0123 := (s × b012) + (t × b123);
 evalbern3 := b0123
end evalbern3;

```

```
procedure bern2to3 (q0, q1, q2, c0, c1, c2, c3);
 value q0, q1, q2;
 real q0, q1, q2;
 real c0, c1, c2, c3;
comment Subprogram (5): transform the quadratic Bernstein coefficients q0, q1, q2 to the cubic Bernstein coefficients c0, c1, c2, c3;
begin
 c0 := q0;
 c1 := ((1/3) × q0) + ((2/3) × q1);
 c2 := ((2/3) × q1) + ((1/3) × q2);
 c3 := q2
end bern2to3;

```

[Assistant]
**Translation of**: Wren

```
# 20230601 Raku programming solution

sub toBern2 { [ @_[0], @_[0]+@_[1]/2, @_[0..2].sum ] }

sub toBern3 (@a) { @a[0], @a[0]+@a[1]/3, @a[0]+@a[1]*2/3+@a[2]/3, @a[0..3].sum }

sub evalBern-N (@b, $t) { # uses de Casteljau's algorithm
   my ($s, @bern) = 1 - $t, @b.Slip;
   while ( @bern.elems > 2 ) {
      @bern = @bern.rotor(2 => -1).map: { $s * .[0] + $t * .[1] };
   }
   return $s * @bern[0] + $t * @bern[1]
}

sub evaluations (@m, @b, $x) {
   my $m = ([o] map { $_ + $x * * }, @m)(0); # Horner's rule
   return "p({$x.fmt: '%.2f'}) = { evalBern-N @b, $x } (mono $m)";
}

sub bern2to3 (@a) { @a[0], @a[0]/3+@a[1]*2/3, @a[1]*2/3+@a[2]/3, @a[2] }

my (@pm,@qm,@rm) := ([1, 0, 0], [1, 2, 3], [1, 2, 3, 4]);

say "Subprogram(1) examples:";

my (@pb2,@qb2) := (@pm,@qm).map: { toBern2 $_ };
say "mono [{.[0]}] --> bern [{.[1]}]" for (@pm,@pb2,@qm,@qb2).rotor: 2;

say "\nSubprogram(2) examples:";

for (@pm,@pb2,@qm,@qb2).rotor(2) X (0.25,7.5) -> [[@m,@b], $x] {
   say evaluations @m, @b, $x
}

say "\nSubprogram(3) examples:";

.push(0) for (@pm,@qm);
my (@pb3,@qb3,@rb3) := (@pm,@qm,@rm).map: { toBern3 $_ };
say "mono [{.[0]}] --> bern [{.[1]}]" for (@pm,@pb3,@qm,@qb3,@rm,@rb3).rotor: 2;

say "\nSubprogram(4) examples:";

for (@pm,@pb3,@qm,@qb3,@rm,@rb3).rotor(2) X (0.25,7.5) -> [[@m,@b], $x] {
   say evaluations @m, @b, $x
}

say "\nSubprogram(5) examples:";

my (@pc,@qc) := (@pb2,@qb2).map: { bern2to3 $_ };
say  "mono [{.[1]}] --> bern [{.[0]}]" for (@pc,@pb2,@qc,@qb2).rotor: 2;

```

Output:

```
Subprogram(1) examples:
mono [1 0 0] --> bern [1 1 1]
mono [1 2 3] --> bern [1 2 6]

Subprogram(2) examples:
p(0.25) = 1 (mono 1)
p(7.50) = 1 (mono 1)
p(0.25) = 1.6875 (mono 1.6875)
p(7.50) = 184.75 (mono 184.75)

Subprogram(3) examples:
mono [1 0 0 0] --> bern [1 1 1 1]
mono [1 2 3 0] --> bern [1 1.666667 3.333333 6]
mono [1 2 3 4] --> bern [1 1.666667 3.333333 10]

Subprogram(4) examples:
p(0.25) = 1 (mono 1)
p(7.50) = 1 (mono 1)
p(0.25) = 1.6875 (mono 1.6875)
p(7.50) = 184.75 (mono 184.75)
p(0.25) = 1.75 (mono 1.75)
p(7.50) = 1872.25 (mono 1872.25)

Subprogram(5) examples:
mono [1 1 1] --> bern [1 1 1 1]
mono [1 2 6] --> bern [1 1.666667 3.333333 6]
```

You may Attempt This Online!


[User]
Task

Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.

A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.

Display the result as follows:

```
original string, shuffled string, (score)

```

The score gives the number of positions whose character value did *not* change.

Example

```
tree, eetr, (0)

```

Test cases

```
abracadabra
seesaw
elk
grrrrrr
up
a

```

Related tasks

* Anagrams/Deranged anagrams
* Permutations/Derangements

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)

**Translation of**: Sidef

```
sub best-shuffle(Str $orig) {
    my @s = $orig.comb;
    my @t = @s.pick(*);

    for flat ^@s X ^@s -> \i,\j {
        if i != j and @t[i] ne @s[j] and @t[j] ne @s[i] {
            @t[i,j] = @t[j,i] and last
        }
    }

    my $count = 0;
    for @t.kv -> $k,$v {
        ++$count if $v eq @s[$k]
    }

    @t.join, $count;
}

printf "%s, %s, (%d)\n", $_, best-shuffle $_  for <abracadabra seesaw elk grrrrrr up a>;

```

Output:

```
abracadabra, raacarabadb, (0)
seesaw, wssaee, (0)
elk, lke, (0)
grrrrrr, rrrgrrr, (5)
up, pu, (0)
a, a, (1)
```


[User]
Description

The Bifid cipher is a polygraphic substitution cipher which was invented by Félix Delastelle in around 1901. It uses a 5 x 5 Polybius square combined with transposition and fractionation to encrypt a message. Any 5 x 5 Polybius square can be used but, as it only has 25 cells and there are 26 letters of the (English) alphabet, one cell needs to represent two letters - I and J being a common choice.

Operation

Suppose we want to encrypt the message "ATTACKATDAWN".

We use this archetypal Polybius square where I and J share the same position.

```
x/y 1 2 3 4 5
-------------
1 | A B C D E
2 | F G H I K
3 | L M N O P
4 | Q R S T U
5 | V W X Y Z

```

The message is first converted to its x, y coordinates, but they are written vertically beneath.

```
A T T A C K A T D A W N
1 4 4 1 1 2 1 4 1 1 5 3
1 4 4 1 3 5 1 4 4 1 2 3

```

They are then arranged in a row.

```
1 4 4 1 1 2 1 4 1 1 5 3 1 4 4 1 3 5 1 4 4 1 2 3

```

Finally, they are divided up into pairs which are used to look up the encrypted letters in the square.

```
14 41 12 14 11 53 14 41 35 14 41 23
D  Q  B  D  A  X  D  Q  P  D  Q  H

```

The encrypted message is therefore "DQBDAXDQPDQH".

Decryption can be achieved by simply reversing these steps.

Task

Write routines in your language to encrypt and descrypt a message using the Bifid cipher.

Use them to verify (including subsequent decryption):

1. The above example.

2. The example in the Wikipedia article using the message and Polybius square therein.

3. The above example but using the Polybius square in the Wikipedia article to illustrate that it doesn't matter which square you use as long, of course, as the same one is used for both encryption and decryption.

In addition, encrypt and decrypt the message "The invasion will start on the first of January" using any Polybius square you like. Convert the message to upper case and ignore spaces.

Bonus

Suggest a way in which the cipher could be modified so that ALL 26 letters can be uniquely encrypted.

Related task

Playfair cipher

[Assistant]
Technically incorrect as the third part doesn't "Convert ... to upper case and ignore spaces".

```
sub polybius ($text) {
    my $n = $text.chars.sqrt.narrow;
    $text.comb.kv.map: { $^v => ($^k % $n, $k div $n).join: ' ' }
}

sub encrypt ($message, %poly) {
    %poly.invert.hash{(flat reverse [Z] %poly{$message.comb}».words).batch(2)».reverse».join: ' '}.join
}

sub decrypt ($message, %poly) {
   %poly.invert.hash{reverse [Z] (reverse flat %poly{$message.comb}».words».reverse).batch($message.chars)}.join
}

for 'ABCDEFGHIKLMNOPQRSTUVWXYZ', 'ATTACKATDAWN',
    'BGWKZQPNDSIOAXEFCLUMTHYVR', 'FLEEATONCE',
    (flat '_', '.', 'A'..'Z', 'a'..'z', 0..9).pick(*).join, 'The invasion will start on the first of January 2023.'.subst(/' '/, '_', :g)
 -> $polybius, $message {
    my %polybius = polybius $polybius;
    say "\nUsing polybius:\n\t" ~ $polybius.comb.batch($polybius.chars.sqrt.narrow).join: "\n\t";
    say "\n  Message : $message";
    say "Encrypted : " ~ my $encrypted = encrypt $message, %polybius;
    say "Decrypted : " ~ decrypt $encrypted, %polybius;
}

```

Output:

```
Using polybius:
	A B C D E
	F G H I K
	L M N O P
	Q R S T U
	V W X Y Z

  Message : ATTACKATDAWN
Encrypted : DQBDAXDQPDQH
Decrypted : ATTACKATDAWN

Using polybius:
	B G W K Z
	Q P N D S
	I O A X E
	F C L U M
	T H Y V R

  Message : FLEEATONCE
Encrypted : UAEOLWRINS
Decrypted : FLEEATONCE

Using polybius:
	H c F T N 5 f i
	_ U k R B Z V W
	3 G e v s w j x
	q S 2 8 y Q . O
	m 0 E d h D r u
	M p 7 Y 4 A 9 a
	t X l I 6 g b z
	J P n 1 K L C o

  Message : The_invasion_will_start_on_the_first_of_January_2023.
Encrypted : NGiw3okfXj4XoVE_NjWcLK4Sy28EivKo3aeNiti3N3z6HCHno6Fkf
Decrypted : The_invasion_will_start_on_the_first_of_January_2023.
```


[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.

Bilinear interpolation is linear interpolation in 2 dimensions, and is typically used for image scaling and for 2D finite element analysis.

Task

Open an image file, enlarge it by 60% using bilinear interpolation, then either display the result or save the result to a file.

[Assistant]
(formerly Perl 6)

```
#!/usr/bin/env perl6

use v6;
use GD::Raw;

# Reference:
# https://github.com/dagurval/perl6-gd-raw

my $fh1 = fopen('./Lenna100.jpg', "rb") or die;
my $img1 = gdImageCreateFromJpeg($fh1);

my $fh2 = fopen('./Lenna100-larger.jpg',"wb") or die;

my $img1X = gdImageSX($img1);
my $img1Y = gdImageSY($img1);

my $NewX = $img1X * 1.6;
my $NewY = $img1Y * 1.6;

gdImageSetInterpolationMethod($img1, +GD_BILINEAR_FIXED);

my $img2 = gdImageScale($img1, $NewX.ceiling, $NewY.ceiling);

gdImageJpeg($img2,$fh2,-1);

gdImageDestroy($img1);
gdImageDestroy($img2);

fclose($fh1);
fclose($fh2);

```

Output:

```
file Lenna100*
Lenna100.jpg:        JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 512x512, frames 3
Lenna100-larger.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality", baseline, precision 8, 820x820, frames 3
```


[User]
You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.

(Assuming zero-based indexing)

```
   bin[0] counts how many inputs are < limit[0]
   bin[1] counts how many inputs are >= limit[0] and < limit[1]
   ..
   bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
   bin[n] counts how many inputs are >= limit[n-1]

```

Task

The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will *print the limit of each bin*
together with the count of items that fell in the range*.*

Assume the numbers to bin are too large to practically sort.

Task examples

Part 1: Bin using the following limits the given input data

```
   limits  = [23, 37, 43, 53, 67, 83]
   data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
           16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]

```

Part 2: Bin using the following limits the given input data

```
   limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
   data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
           416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
           655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
           346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
           345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,
           854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,
           787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
           698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
           605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
           466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749]

```

Show output here, on this page.

[Assistant]
```
sub bin_it ( @limits, @data ) {
    my @ranges = ( -Inf, |@limits, Inf ).rotor( 2 => -1 ).map: { .[0] ..^ .[1] };
    my @binned = @data.classify(-> $d { @ranges.grep(-> $r { $d ~~ $r }) });
    my %counts = @binned.map: { .key => .value.elems };
    return @ranges.map: { $_ => ( %counts{$_} // 0 ) };
}
sub bin_format ( @bins ) {
    return @bins.map: { .key.gist.fmt('%9s => ') ~ .value.fmt('%2d') };
}

my @tests =
    {
        limits => (23, 37, 43, 53, 67, 83),
        data   => (95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55),
    },
    {
        limits => (14, 18, 249, 312, 389, 392, 513, 591, 634, 720),
        data   => (
            445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
            655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
            345,110,720,917,313,845,426,  9,457,628,410,723,354,895,881,953,677,137,397, 97,854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157,  5,316,395,
            787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
            605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918,  8,374,101,684,727,749
        ),
    },
;
for @tests -> ( :@limits, :@data ) {
    my @bins = bin_it( @limits, @data );
    .say for bin_format(@bins);
    say '';
}

```

Output:

```
-Inf..^23 => 11
  23..^37 =>  4
  37..^43 =>  2
  43..^53 =>  6
  53..^67 =>  9
  67..^83 =>  5
 83..^Inf => 13

-Inf..^14 =>  3
  14..^18 =>  0
 18..^249 => 44
249..^312 => 10
312..^389 => 16
389..^392 =>  2
392..^513 => 28
513..^591 => 16
591..^634 =>  6
634..^720 => 16
720..^Inf => 59

```


[User]
Binary-Coded Decimal (or BCD for short) is a method of representing decimal numbers by storing what appears to be a decimal number but is actually stored as hexadecimal. Many CISC CPUs (e.g. X86 Assembly have special hardware routines for displaying these kinds of numbers.) On low-level hardware, such as 7-segment displays, binary-coded decimal is very important for outputting data in a format the end user can understand.

Task

Use your language's built-in BCD functions, OR create your own conversion function, that converts an addition of hexadecimal numbers to binary-coded decimal. You should get the following results with these test cases:

* 0x19 + 1 = 0x20
* 0x30 - 1 = 0x29
* 0x99 + 1 = 0x100

Bonus Points

Demonstrate the above test cases in both "packed BCD" (two digits per byte) and "unpacked BCD" (one digit per byte).

[Assistant]
**Translation of**: Rust

```
# 20220930 Raku programming solution

class Bcd64 { has uint64 $.bits }

multi infix:<⊞> (Bcd64 \p, Bcd64 \q) {
   my $t1 = p.bits + 0x0666_6666_6666_6666;
   my $t2 = ( $t1 + q.bits ) % uint64.Range.max ;
   my $t3 = $t1 +^ q.bits;
   my $t4 = +^($t2 +^ $t3) +& 0x1111_1111_1111_1110;
   my $t5 = ($t4 +> 2) +| ($t4 +> 3);
   Bcd64.new: bits => ($t2 - $t5)
}

multi prefix:<⊟> (Bcd64 \p) {
   my $t1 = uint64.Range.max + 1 - p.bits ;
   my $t2 = ( $t1 + 0xFFFF_FFFF_FFFF_FFFF ) % uint64.Range.max;
   my $t3 = $t2 +^ 1;
   my $t4 = +^($t2 +^ $t3) +& 0x1111_1111_1111_1110;
   my $t5 = ($t4 +> 2) +| ($t4 +> 3);
   Bcd64.new: bits => ($t1 - $t5)
}

multi infix:<⊟> (Bcd64 \p, Bcd64 \q) { p ⊞ ( ⊟q ) }

my ($one,$n19,$n30,$n99) = (0x01,0x19,0x30,0x99).map: { Bcd64.new: bits=>$_ };

{ .bits.base(16).say } for ($n19 ⊞ $one,$n30 ⊟ $one,$n99 ⊞ $one);

```

Output:

```
20
29
100

```


[User]
Task

Create and display the sequence of binary digits for a given   non-negative integer.

```
   The decimal value      5   should produce an output of               101
   The decimal value     50   should produce an output of            110010
   The decimal value   9000   should produce an output of    10001100101000

```

The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used.

The output produced should consist just of the binary digits of each number followed by a   *newline*.

There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
say .fmt("%b") for 5, 50, 9000;
```

```
101
110010
10001100101000

```

Alternatively:

```
say .base(2) for 5, 50, 9000;
```

```
101
110010
10001100101000
```


[User]
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.

As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.

As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.

Task

Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.

There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.

All of the following code examples use an "inclusive" upper bound (i.e. `high = N-1` initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. `high = N` initially) by making the following simple changes (which simply increase `high` by 1):

* change `high = N-1` to `high = N`
* change `high = mid-1` to `high = mid`
* (for recursive algorithm) change `if (high < low)` to `if (high <= low)`
* (for iterative algorithm) change `while (low <= high)` to `while (low < high)`

Traditional algorithm

The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array).

**Recursive Pseudocode**:

```
  // initially called with low = 0, high = N-1
  BinarySearch(A[0..N-1], value, low, high) {
      // invariants: value > A[i] for all i < low
                     value < A[i] for all i > high
      if (high < low)
          return not_found // value would be inserted at index "low"
      mid = (low + high) / 2
      if (A[mid] > value)
          return BinarySearch(A, value, low, mid-1)
      else if (A[mid] < value)
          return BinarySearch(A, value, mid+1, high)
      else
          return mid
  }

```

**Iterative Pseudocode**:

```
  BinarySearch(A[0..N-1], value) {
      low = 0
      high = N - 1
      while (low <= high) {
          // invariants: value > A[i] for all i < low
                         value < A[i] for all i > high
          mid = (low + high) / 2
          if (A[mid] > value)
              high = mid - 1
          else if (A[mid] < value)
              low = mid + 1
          else
              return mid
      }
      return not_found // value would be inserted at index "low"
  }

```

Leftmost insertion point

The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.

**Recursive Pseudocode**:

```
  // initially called with low = 0, high = N - 1
  BinarySearch_Left(A[0..N-1], value, low, high) {
      // invariants: value > A[i] for all i < low
                     value <= A[i] for all i > high
      if (high < low)
          return low
      mid = (low + high) / 2
      if (A[mid] >= value)
          return BinarySearch_Left(A, value, low, mid-1)
      else
          return BinarySearch_Left(A, value, mid+1, high)
  }

```

**Iterative Pseudocode**:

```
  BinarySearch_Left(A[0..N-1], value) {
      low = 0
      high = N - 1
      while (low <= high) {
          // invariants: value > A[i] for all i < low
                         value <= A[i] for all i > high
          mid = (low + high) / 2
          if (A[mid] >= value)
              high = mid - 1
          else
              low = mid + 1
      }
      return low
  }

```

Rightmost insertion point

The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.

**Recursive Pseudocode**:

```
  // initially called with low = 0, high = N - 1
  BinarySearch_Right(A[0..N-1], value, low, high) {
      // invariants: value >= A[i] for all i < low
                     value < A[i] for all i > high
      if (high < low)
          return low
      mid = (low + high) / 2
      if (A[mid] > value)
          return BinarySearch_Right(A, value, low, mid-1)
      else
          return BinarySearch_Right(A, value, mid+1, high)
  }

```

**Iterative Pseudocode**:

```
  BinarySearch_Right(A[0..N-1], value) {
      low = 0
      high = N - 1
      while (low <= high) {
          // invariants: value >= A[i] for all i < low
                         value < A[i] for all i > high
          mid = (low + high) / 2
          if (A[mid] > value)
              high = mid - 1
          else
              low = mid + 1
      }
      return low
  }

```

Extra credit

Make sure it does not have overflow bugs.

The line in the pseudo-code above to calculate the mean of two integers:

```
mid = (low + high) / 2
```

could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and `low + high` overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.

One way to fix it is to manually add half the range to the low number:

```
mid = low + (high - low) / 2
```

Even though this is mathematically equivalent to the above, it is not susceptible to overflow.

Another way for signed integers, possibly faster, is the following:

```
mid = (low + high) >>> 1
```

where  `>>>`  is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.

Related task
:   * Guess the number/With Feedback (Player)

See also
:   * wp:Binary search algorithm
    * Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.

[Assistant]
(formerly Perl 6)
With either of the below implementations of `binary_search`, one could write a function to search any object that does `Positional` this way:

```
sub search (@a, $x --> Int) {
    binary_search { $x cmp @a[$^i] }, 0, @a.end
}
```

**Iterative**

**Works with**: Rakudo version 2015.12

```
sub binary_search (&p, Int $lo is copy, Int $hi is copy --> Int) {
    until $lo > $hi {
        my Int $mid = ($lo + $hi) div 2;
        given p $mid {
            when -1 { $hi = $mid - 1; }
            when  1 { $lo = $mid + 1; }
            default { return $mid;    }
        }
    }
    fail;
}
```

**Recursive**

**Translation of**: Haskell

**Works with**: Rakudo version 2015.12

```
sub binary_search (&p, Int $lo, Int $hi --> Int) {
    $lo <= $hi or fail;
    my Int $mid = ($lo + $hi) div 2;
    given p $mid {
        when -1 { binary_search &p, $lo,      $mid - 1 }
        when  1 { binary_search &p, $mid + 1, $hi      }
        default { $mid                                 }
    }
}
```


[User]
Many languages have powerful and useful (**binary safe**) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.

This task is about creating functions to handle *binary* strings (strings made of arbitrary bytes, i.e. *byte strings* according to Wikipedia) for those languages that don't have built-in support for them.

If your language of choice does have this built-in support, show a possible alternative implementation for the *functions* or *abilities* already provided by the language.

In particular the functions you need to create are:

* String creation and destruction (when needed and if there's no garbage collection or similar mechanism)
* String assignment
* String comparison
* String cloning and copying
* Check if a string is empty
* Append a byte to a string
* Extract a substring from a string
* Replace every occurrence of a byte (or a string) in a string with another string
* Join strings

Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
# Raku is perfectly fine with NUL *characters* in strings:
my Str $s = 'nema' ~ 0.chr ~ 'problema!';
say $s;

# However, Raku makes a clear distinction between strings
# (i.e. sequences of characters), like your name, or …
my Str $str = "My God, it's full of chars!";
# … and sequences of bytes (called Bufs), for example a PNG image, or …
my Buf $buf = Buf.new(255, 0, 1, 2, 3);
say $buf;

# Strs can be encoded into Blobs …
my Blob $this = 'round-trip'.encode('ascii');
# … and Blobs can be decoded into Strs …
my Str $that = $this.decode('ascii');

# So it's all there. Nevertheless, let's solve this task explicitly
# in order to see some nice language features:

# We define a class …
class ByteStr {
    # … that keeps an array of bytes, and we delegate some
    # straight-forward stuff directly to this attribute:
    # (Note: "has byte @.bytes" would be nicer, but that is
    # not yet implemented in Rakudo.)
    has Int @.bytes handles(< Bool elems gist push >);

    # A handful of methods …
    method clone() {
        self.new(:@.bytes);
    }

    method substr(Int $pos, Int $length) {
        self.new(:bytes(@.bytes[$pos .. $pos + $length - 1]));
    }

    method replace(*@substitutions) {
        my %h = @substitutions;
        @.bytes.=map: { %h{$_} // $_ }
    }
}

# A couple of operators for our new type:
multi infix:<cmp>(ByteStr $x, ByteStr $y) { $x.bytes.join cmp $y.bytes.join }
multi infix:<~>  (ByteStr $x, ByteStr $y) { ByteStr.new(:bytes(|$x.bytes, |$y.bytes)) }

# create some byte strings (destruction not needed due to garbage collection)
my ByteStr $b0 = ByteStr.new;
my ByteStr $b1 = ByteStr.new(:bytes( |'foo'.ords, 0, 10, |'bar'.ords ));

# assignment ($b1 and $b2 contain the same ByteStr object afterwards):
my ByteStr $b2 = $b1;

# comparing:
say 'b0 cmp b1 = ', $b0 cmp $b1;
say 'b1 cmp b2 = ', $b1 cmp $b2;

# cloning:
my $clone = $b1.clone;
$b1.replace('o'.ord => 0);
say 'b1 = ', $b1;
say 'b2 = ', $b2;
say 'clone = ', $clone;

# to check for (non-)emptiness we evaluate the ByteStr in boolean context:
say 'b0 is ', $b0 ?? 'not empty' !! 'empty';
say 'b1 is ', $b1 ?? 'not empty' !! 'empty';

# appending a byte:
$b1.push: 123;
say 'appended = ', $b1;

# extracting a substring:
my $sub = $b1.substr(2, 4);
say 'substr = ', $sub;

# replacing a byte:
$b2.replace(102 => 103);
say 'replaced = ', $b2;

# joining:
my ByteStr $b3 = $b1 ~ $sub;
say 'joined = ', $b3;
```

Output:

Note: The ␀ represents a NUL byte.

```
nema␀problema!
Buf:0x<ff 00 01 02 03>
round-trip
b0 cmp b1 = Less
b1 cmp b2 = Same
b1 = [102 0 0 0 10 98 97 114]
b2 = [102 0 0 0 10 98 97 114]
clone = [102 111 111 0 10 98 97 114]
b0 is empty
b1 is not empty
appended = [102 0 0 0 10 98 97 114 123]
substr = [0 0 10 98]
replaced = [103 0 0 0 10 98 97 114 123]
joined = [103 0 0 0 10 98 97 114 123 0 0 10 98]
```