[User]
Task

Show  the ASCII character set  from values   **32**   to   **127**   (decimal)   in a table format.

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)

Alternately, and perhaps more usefully, output as a wiki-table rather than ASCII art. Hover mouse over the glyph to get the name.

```
sub glyph ($_) {
    when * < 33 { (0x2400 + $_).chr } # display symbol names for invisible glyphs
    when 127    { '␡' }
    default     { .chr }
}

say '{|class="wikitable" style="text-align:center;background-color:hsl(39, 90%, 95%)"';

for (^128).rotor(16) -> @row {
    say '|-';
    printf(q[|%d<br>0x%02X<br><big><big title="%s">%s</big></big>] ~ "\n",
      $_, $_, .&glyph.uniname.subst('SYMBOL FOR ', ''),
      .&glyph.subst('|', '<nowiki>|</nowiki>')) for @row;
}

say '|}';

```

Output:

|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 0x00 ␀ | 1 0x01 ␁ | 2 0x02 ␂ | 3 0x03 ␃ | 4 0x04 ␄ | 5 0x05 ␅ | 6 0x06 ␆ | 7 0x07 ␇ | 8 0x08 ␈ | 9 0x09 ␉ | 10 0x0A ␊ | 11 0x0B ␋ | 12 0x0C ␌ | 13 0x0D ␍ | 14 0x0E ␎ | 15 0x0F ␏ |
| 16 0x10 ␐ | 17 0x11 ␑ | 18 0x12 ␒ | 19 0x13 ␓ | 20 0x14 ␔ | 21 0x15 ␕ | 22 0x16 ␖ | 23 0x17 ␗ | 24 0x18 ␘ | 25 0x19 ␙ | 26 0x1A ␚ | 27 0x1B ␛ | 28 0x1C ␜ | 29 0x1D ␝ | 30 0x1E ␞ | 31 0x1F ␟ |
| 32 0x20 ␠ | 33 0x21 ! | 34 0x22 " | 35 0x23 # | 36 0x24 $ | 37 0x25 % | 38 0x26 & | 39 0x27 ' | 40 0x28 ( | 41 0x29 ) | 42 0x2A \* | 43 0x2B + | 44 0x2C , | 45 0x2D - | 46 0x2E . | 47 0x2F / |
| 48 0x30 0 | 49 0x31 1 | 50 0x32 2 | 51 0x33 3 | 52 0x34 4 | 53 0x35 5 | 54 0x36 6 | 55 0x37 7 | 56 0x38 8 | 57 0x39 9 | 58 0x3A : | 59 0x3B ; | 60 0x3C < | 61 0x3D = | 62 0x3E > | 63 0x3F ? |
| 64 0x40 @ | 65 0x41 A | 66 0x42 B | 67 0x43 C | 68 0x44 D | 69 0x45 E | 70 0x46 F | 71 0x47 G | 72 0x48 H | 73 0x49 I | 74 0x4A J | 75 0x4B K | 76 0x4C L | 77 0x4D M | 78 0x4E N | 79 0x4F O |
| 80 0x50 P | 81 0x51 Q | 82 0x52 R | 83 0x53 S | 84 0x54 T | 85 0x55 U | 86 0x56 V | 87 0x57 W | 88 0x58 X | 89 0x59 Y | 90 0x5A Z | 91 0x5B [ | 92 0x5C \ | 93 0x5D ] | 94 0x5E ^ | 95 0x5F \_ |
| 96 0x60 ` | 97 0x61 a | 98 0x62 b | 99 0x63 c | 100 0x64 d | 101 0x65 e | 102 0x66 f | 103 0x67 g | 104 0x68 h | 105 0x69 i | 106 0x6A j | 107 0x6B k | 108 0x6C l | 109 0x6D m | 110 0x6E n | 111 0x6F o |
| 112 0x70 p | 113 0x71 q | 114 0x72 r | 115 0x73 s | 116 0x74 t | 117 0x75 u | 118 0x76 v | 119 0x77 w | 120 0x78 x | 121 0x79 y | 122 0x7A z | 123 0x7B { | 124 0x7C | | 125 0x7D } | 126 0x7E ~ | 127 0x7F ␡ |


[User]
Task

Show here (on this page) the decimal numbers formed by:

:   :   (**n**   **1'**s   appended by the digit   **3**)   and then square the result,     where    **0   <=   n   <   8**

See also

* oeis:A151997

[Assistant]
In an attempt to stave of terminal ennui, Find the first 8 where a(n) is semiprime.

```
say "$_, {.²}" for (^∞).map({ ( 1 x $_ ~ 3)} ).grep({ .is-prime })[^8]

```

Output:

```
3, 9
13, 169
113, 12769
11113, 123498769
111111113, 12345679432098769
11111111113, 123456790165432098769
111111111111111111111113, 12345679012345679012346098765432098765432098769
111111111111111111111111111111111111111111111111111111111111111111111111111111111113, 12345679012345679012345679012345679012345679012345679012345679012345679012345679012765432098765432098765432098765432098765432098765432098765432098765432098765432098769
```


[User]
Task

Choose popular date libraries used by your language and show the   epoch   those libraries use.

A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.

For consistency's sake, show the date in UTC time where possible.

Related task

* Date format

[Assistant]
(formerly Perl 6)

```
say DateTime.new(0)

```

Output:

```
1970-01-01T00:00:00Z

```


[User]
Task

Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  **3**.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.02

```
use SVG;

role Lindenmayer {
    has %.rules;
    method succ {
        self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
    }
}

my $arrow = 'X' but Lindenmayer( { X => 'YF+XF+Y', Y => 'XF-YF-X' } );

$arrow++ xx 7;

my $w = 800;
my $h = ($w * 3**.5 / 2).round(1);

my $scale = 6;
my @points = (400, 15);
my $dir = pi/3;

for $arrow.comb {
    state ($x, $y) = @points[0,1];
    state $d = $dir;
    when 'F' { @points.append: ($x += $scale * $d.cos).round(1), ($y += $scale * $d.sin).round(1) }
    when '+' { $d += $dir }
    when '-' { $d -= $dir }
    default { }
}

my $out = './sierpinski-arrowhead-curve-perl6.svg'.IO;

$out.spurt:  SVG.serialize(
    svg => [
        :width($w), :height($h),
        :rect[:width<100%>, :height<100%>, :fill<black>],
        :polyline[ :points(@points.join: ','), :fill<black>, :style<stroke:#FF4EA9> ],
    ],
);

```

See: Sierpinski-arrowhead-curve-perl6.svg (offsite SVG image)


[User]
Task

Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   **N**.

For example, the Sierpinski carpet of order   **3**   should look like this:

```
###########################
# ## ## ## ## ## ## ## ## #
###########################
###   ######   ######   ###
# #   # ## #   # ## #   # #
###   ######   ######   ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
#########         #########
# ## ## #         # ## ## #
#########         #########
###   ###         ###   ###
# #   # #         # #   # #
###   ###         ###   ###
#########         #########
# ## ## #         # ## ## #
#########         #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
###   ######   ######   ###
# #   # ## #   # ## #   # #
###   ######   ######   ###
###########################
# ## ## ## ## ## ## ## ## #
###########################

```

The use of the   #   character is not rigidly required for ASCII art.

The important requirement is the placement of whitespace and non-whitespace characters.

Related task

* Sierpinski triangle

[Assistant]
(formerly Perl 6)

**Translation of**: Tcl

```
sub carpet
{
    (['#'], -> @c {
       [
        |@c.map({$_ x 3}),
        |@c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}),
        |@c.map({$_ x 3})
       ]
    } ... *).map: { .join("\n") };
}

say carpet[3];

# Same as above, structured as an array bound to a sequence, with a separate sub for clarity.
sub weave ( @c ) {
   [
    |@c.map({ $_ x 3 }),
    |@c.map({ $_ ~ .trans( '#' => ' ' ) ~ $_ }),
    |@c.map({ $_ x 3 })
   ]
}

my @carpet = ( ['#'], &weave ... * ).map: { .join: "\n" };

say @carpet[3];

# Output of both versions matches task example.
```


[User]
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.

See also

* Sierpinski pentagon

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018-10

5th order pentaflake

```
constant $sides = 5;
constant order  = 5;
constant $dim   = 250;
constant scaling-factor = ( 3 - 5**.5 ) / 2;
my @orders = ((1 - scaling-factor) * $dim) «*» scaling-factor «**» (^order);

my $fh = open('sierpinski_pentagon.svg', :w);

$fh.say: qq|<svg height="{$dim*2}" width="{$dim*2}" style="fill:blue" version="1.1" xmlns="http://www.w3.org/2000/svg">|;

my @vertices = map { cis( $_ * τ / $sides ) }, ^$sides;

for 0 ..^ $sides ** order -> $i {
   my $vector = [+] @vertices[$i.base($sides).fmt("%{order}d").comb] «*» @orders;
   $fh.say: pgon ((@orders[*-1] * (1 - scaling-factor)) «*» @vertices «+» $vector)».reals».fmt("%0.3f");
};

sub pgon (@q) { qq|<polygon points="{@q}" transform="translate({$dim},{$dim}) rotate(-18)"/>| }

$fh.say: '</svg>';
$fh.close;

```


[User]
Task

Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.02

```
use SVG;

role Lindenmayer {
    has %.rules;
    method succ {
        self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
    }
}

my $sierpinski = 'X' but Lindenmayer( { X => 'XF-F+F-XF+F+XF-F+F-X' } );

$sierpinski++ xx 5;

my $dim = 600;
my $scale = 6;

my @points = (-80, 298);

for $sierpinski.comb {
    state ($x, $y) = @points[0,1];
    state $d = $scale + 0i;
    when 'F' { @points.append: ($x += $d.re).round(1), ($y += $d.im).round(1) }
    when /< + - >/ { $d *= "{$_}1i" }
    default { }
}

my @t = @points.tail(2).clone;

my $out = './sierpinski-square-curve-perl6.svg'.IO;

$out.spurt: SVG.serialize(
    svg => [
        :width($dim), :height($dim),
        :rect[:width<100%>, :height<100%>, :fill<black>],
        :polyline[
          :points((@points, map {(@t »+=» $_).clone}, ($scale,0), (0,$scale), (-$scale,0)).join: ','),
          :fill<black>, :transform("rotate(45, 300, 300)"), :style<stroke:#61D4FF>,
        ],
        :polyline[
          :points(@points.map( -> $x,$y { $x, $dim - $y + 1 }).join: ','),
          :fill<black>, :transform("rotate(45, 300, 300)"), :style<stroke:#61D4FF>,
        ],
    ],
);

```

See: Sierpinski-square-curve-perl6.svg (offsite SVG image)


[User]
Task

Produce an ASCII representation of a Sierpinski triangle of order   **N**.

Example

The Sierpinski triangle of order   **4**   should look like this:

```
                       *
                      * *
                     *   *
                    * * * *
                   *       *
                  * *     * *
                 *   *   *   *
                * * * * * * * *
               *               *
              * *             * *
             *   *           *   *
            * * * *         * * * *
           *       *       *       *
          * *     * *     * *     * *
         *   *   *   *   *   *   *   *
        * * * * * * * * * * * * * * * *

```

Related tasks

* Sierpinski triangle/Graphical for graphics images of this pattern.
* Sierpinski carpet

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

```
sub sierpinski ($n) {
    my @down  = '*';
    my $space = ' ';
    for ^$n {
        @down = |("$space$_$space" for @down), |("$_ $_" for @down);
        $space x= 2;
    }
    return @down;
}

.say for sierpinski 4;
```


[User]
Produce a graphical representation of a Sierpinski triangle of order N in any orientation.

An example of Sierpinski's triangle (order = 8) looks like this:

[Assistant]
(formerly Perl 6)

This is a recursive solution. It is not really practical for more than 8 levels of recursion, but anything more than 7 is barely visible anyway.

```
my $levels = 8;
my $side   = 512;
my $height = get_height($side);

sub get_height ($side) { $side * 3.sqrt / 2 }

sub triangle ( $x1, $y1, $x2, $y2, $x3, $y3, $fill?, $animate? ) {
    my $svg;
    $svg ~= qq{<polygon points="$x1,$y1 $x2,$y2 $x3,$y3"};
    $svg ~= qq{ style="fill: $fill; stroke-width: 0;"} if $fill;
    $svg ~= $animate
        ?? qq{>\n  <animate attributeType="CSS" attributeName="opacity"\n  values="1;0;1" keyTimes="0;.5;1" dur="20s" repeatCount="indefinite" />\n</polygon>}
        !! ' />';
    return $svg;
}

sub fractal ( $x1, $y1, $x2, $y2, $x3, $y3, $r is copy ) {
    my $svg;
    $svg ~= triangle( $x1, $y1, $x2, $y2, $x3, $y3 );
    return $svg unless --$r;
    my $side = abs($x3 - $x2) / 2;
    my $height = get_height($side);
    $svg ~= fractal( $x1, $y1-$height*2, $x1-$side/2, $y1-3*$height, $x1+$side/2, $y1-3*$height, $r);
    $svg ~= fractal( $x2, $y1, $x2-$side/2, $y1-$height, $x2+$side/2, $y1-$height, $r);
    $svg ~= fractal( $x3, $y1, $x3-$side/2, $y1-$height, $x3+$side/2, $y1-$height, $r);
}

my $fh = open('sierpinski_triangle.svg', :w) orelse .die;
$fh.print: qq:to/EOD/,
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
  <radialGradient id="basegradient" cx="50%" cy="65%" r="50%" fx="50%" fy="65%">
    <stop offset="10%" stop-color="#ff0" />
    <stop offset="60%" stop-color="#f00" />
    <stop offset="99%" stop-color="#00f" />
  </radialGradient>
</defs>
EOD

triangle( $side/2, 0, 0, $height, $side, $height, 'url(#basegradient)' ),
triangle( $side/2, 0, 0, $height, $side, $height, '#000', 'animate' ),
'<g style="fill: #fff; stroke-width: 0;">',
fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ),
'</g></svg>';

```


[User]
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.

The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.

Task

Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.

That means especially that you shouldn't optimize by using pre-computed *wheels*, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.

If there's an easy way to add such a wheel based optimization, implement it as an alternative version.

Note

* It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.

Related tasks

* Emirp primes
* count in factors
* prime decomposition
* factors of an integer
* extensible prime generator
* primality by trial division
* factors of a Mersenne number
* trial factoring of a Mersenne number
* partition an integer X into N primes
* sequence of primes by Trial Division

[Assistant]
(formerly Perl 6)

```
sub sieve( Int $limit ) {
    my @is-prime = False, False, slip True xx $limit - 1;

    gather for @is-prime.kv -> $number, $is-prime {
        if $is-prime {
            take $number;
            loop (my $s = $number**2; $s <= $limit; $s += $number) {
                @is-prime[$s] = False;
            }
        }
    }
}

(sieve 100).join(",").say;
```

### A set-based approach

More or less the same as the first Python example:

```
sub eratsieve($n) {
    # Requires n(1 - 1/(log(n-1))) storage
    my $multiples = set();
    gather for 2..$n -> $i {
        unless $i (&) $multiples { # is subset
            take $i;
            $multiples (+)= set($i**2, *+$i ... (* > $n)); # union
        }
    }
}

say flat eratsieve(100);
```

This gives:

```
 (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)

```

### Using a chain of filters

|  |
| --- |
| This example is **incorrect**. Please fix the code and remove this message.  ***Details:*** This version uses modulo (division) testing and so is a trial division algorithm, not a sieve of Eratosthenes. |

*Note: while this is "incorrect" by a strict interpretation of the rules, it is being left as an interesting example*

```
sub primes ( UInt $n ) {
    gather {
        # create an iterator from 2 to $n (inclusive)
        my $iterator := (2..$n).iterator;

        loop {
            # If it passed all of the filters it must be prime
            my $prime := $iterator.pull-one;
            # unless it is actually the end of the sequence
            last if $prime =:= IterationEnd;

            take $prime; # add the prime to the `gather` sequence

            # filter out the factors of the current prime
            $iterator := Seq.new($iterator).grep(* % $prime).iterator;
            # (2..*).grep(* % 2).grep(* % 3).grep(* % 5).grep(* % 7)…
        }
    }
}

put primes( 100 );
```

Which prints

```
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

```


[User]
The Sieve of Pritchard is an algorithm for finding the prime numbers up to a given limit N, published in 1981. It considers many fewer composite numbers than the Sieve of Eratosthenes (and has a better asymptotic time complexity). However, unlike the latter, it cannot be modified to greatly reduce its space requirement, making it unsuitable for very large limits.

Conceptually, it works by building a wheel representing the repeating pattern of numbers not divisible by one of the first k primes, increasing k until the square of the k'th prime is at least N. Since wheels grow very quickly, the algorithm restricts attention to the initial portions of wheels up to N. (Small examples of the wheels constructed by the Sieve of Pritchard are used in the "wheel-based optimizations" mentioned in the Eratosthenes task.)

For example, the second-order wheel has circumference 6 (the product of the first two primes, 2 and 3) and is marked only at the numbers between 1 and 6 that are not multiples of 2 or 3, namely 1 and 5. As this wheel is rolled along the number line, it will pick up only numbers of the form 6k+1 or 6k+5 (that is, n where n mod 6 is in {1,5}). By the time it stops at 30 (2x3x5) it has added only 8 of the numbers between 6 and 30 as candidates for primality. Those that are multiples of 5 (only 2: 1\*5 and 5\*5) are obtained by multiplying the members of the second-order wheel. Removing them gives the next wheel, and so on.

This YouTube video presents the execution of the algorithm for N=150 in a format that permits single-stepping forward and backward through the run. In that implementation, the wheel is represented by a sparse global array s such that for each member w of the wheel, s[w] contains the next member of the wheel; along with a similar "previous member" value, this allows numbers to be removed in a constant number of operations. But the simple abstract algorithm is based on an ordered set, and there is plenty of scope for different implementations.

Task

Write a program/subprogram that uses the Sieve of Pritchard algorithm to find all primes up to a specified limit. Show the result of running it with a limit of 150.

Related tasks

* Sieve of Eratosthenes
* Emirp primes
* count in factors
* prime decomposition
* factors of an integer
* extensible prime generator
* primality by trial division
* factors of a Mersenne number
* trial factoring of a Mersenne number
* partition an integer X into N primes
* sequence of primes by Trial Division

[Assistant]
First, a direct translation of the implementation in the YouTube video:

```
unit sub MAIN($limit = 150);

my $maxS = 1;
my $length = 2;
my $p = 3;
my @s = ();

while $p*$p <= $limit {
  if $length < $limit {
    extend-to [$p*$length, $limit].min;
  }
  delete-multiples-of($p);
  $p = next(1);
}
if $length < $limit {
  extend-to $limit;
}

# Done, build the list of actual primes from the array
$p = 3;
my @primes = 2, |gather while $p <= $limit {
  take $p;
  $p = next($p);
};
say @primes;

exit;

sub extend-to($n) {
  my $w = 1;
  my $x = $length + 1;
  while $x <= $n {
     append $x;
     $w = next($w);
     $x = $length + $w;
  }
  $length = $n;
  if $length == $limit {
    append $limit+2;
  }
}

sub delete-multiples-of($p) {
  my $f = $p;
  while $p*$f <= $length {
    $f = next($f);
  }
  while $f > 1 {
    $f = prev($f);
    delete($p*$f);
  }
}

sub append($w) {
  @s[$maxS-1] = $w;
  @s[$w-2] = $maxS;
  $maxS = $w;
}

sub next($w) { @s[$w-1]; }
sub prev($w) { @s[$w-2]; }

sub delete($pf) {
  my $temp1 = @s[$pf-2];
  my $temp2 = @s[$pf-1];
  @s[$temp1-1] = $temp2;
  @s[($temp2-2)%@s] = $temp1;
}

```

Output:

```
[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149
```

Then a slightly more Raku-ish implementation based on the description in the Wikipedia article:

```
unit sub MAIN($limit = 150);

class Wheel {
  has $.members is rw;
  has $.length is rw;
  method extend(*@limits) {
    my @members = $.members.keys;
    for @members -> $w {
      my $n = $w + $.length;
      while $n <= @limits.all {
        $.members.set($n);
        $n += $.length;
      }
    }
    $.length = @limits.min;
  }
}

# start with W₀=({1},1)
my $wheel = Wheel.new: :members(SetHash(1)), :length(1);
my $prime = 2;
my @primes = ();

while $prime * $prime <= $limit {
  if $wheel.length < $limit {
    $wheel.extend($prime*$wheel.length, $limit);
  }
  for $wheel.members.keys.sort(-*) -> $w {
    $wheel.members.unset($prime * $w);
  }
  @primes.push: $prime;
  $prime = $prime == 2 ?? 3 !! $wheel.members.keys.grep(*>1).sort[0];
}

if $wheel.length < $limit {
  $wheel.extend($limit);
}
@primes.append:  $wheel.members.keys.grep: * != 1;
say @primes.sort;

```

The only difference in the output is that the result of `.sort` is a list rather than an array, so it's printed in parentheses instead of square brackets:

Output:

```
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149)
```


[User]
Signum: Sign of an integer - represent the sign of an integer using a value from a set of 3 or 4 integers.

Task

Create a function that takes a signed integer *x*, and returns another signed integer as follows:

* if *x*<0, return -1,
* if *x*>0, return 1 (positive 1),
* if *x*=0, return 0.

If the integer representation used supports a signed zero, then the function should preserve the sign of the zero. That is,

* if *x*=-0, return -0,
* if *x*=+0, return +0.

Example

:   :   | input | output |
        | --- | --- |
        | -10 | -1 |
        | 42 | 1 |
        | 0 | 0 |

Additional example for integer types with a signed zero (uncommon)

:   :   | input | output |
        | --- | --- |
        | -0 | -0 |

[Assistant]
Raku has IEEE 754 floating point numbers as part of it's numeric spectrum, so understands -0 as a concept, but does not make any attempt to keep negative zeros. Once a number is interpreted numerically, it is automatically "narrowed" to it's most compact form for display.

```
say +($_ <=> 0), ": $_" for 1, -5, 2⁷⁶, -7⁴⁴, π, Inf, -Inf, 0, -0;

```

Output:

```
1: 1
-1: -5
1: 75557863725914323419136
-1: -15286700631942576193765185769276826401
1: 3.141592653589793
1: Inf
-1: -Inf
0: 0
0: 0

```


[User]
Task

Write a simple tool to track a small set of data.

The tool should have a command-line interface to enter at least two different values.

The entered data should be stored in a structured format and saved to disk.

It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.

You should track the following details:

* A description of the item. (e.g., title, name)
* A category or tag (genre, topic, relationship such as “friend” or “family”)
* A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually
* Other optional fields

The command should support the following Command-line arguments to run:

* Add a new entry
* Print the latest entry
* Print the latest entry for each category
* Print all entries sorted by a date

The category may be realized as a tag or as structure (by making all entries in that category subitems)

The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:

:   :   :   * JSON
            * S-Expressions
            * YAML
            * others

Related task

* Take notes on the command line

[Assistant]
(formerly Perl 6)
A generic client/server JSON database.
**server.raku:**

```
#!/usr/bin/env raku
use JSON::Fast ;
sub MAIN( :$server='0.0.0.0', :$port=3333, :$dbfile='db' ) {
    my %db;
    my %index;
    my $dbdata = slurp "$dbfile.json" ;
    my $indexdata = slurp "{$dbfile}_index.json" ;
    %db = from-json($dbdata) if $dbdata ;
    %index = from-json($indexdata) if $indexdata ;
  react {
    whenever IO::Socket::Async.listen( $server , $port ) -> $conn {
        whenever $conn.Supply.lines -> $line {
            my %response = 'status' => '' ;
            my $msg = from-json $line ;
            say $msg.perl ;
            given $msg<function> {
                when 'set' {
                    %db{ $msg<topic> } = $msg<message> ;
                    %response<status> = 'ok' ;
                    %index<last_> = $msg<topic> ;
                    for %index<keys_>.keys -> $key {
                        if $msg<message>{$key} {
                            %index<lastkey_>{ $key }{ $msg<message>{$key} } = $msg<topic> ;
                            %index<idx_>{ $key }{ $msg<message>{$key} }{ $msg<topic> } = 1 ;
                        }
                    }
                    spurt "$dbfile.json", to-json(%db);
                    spurt "{$dbfile}_index.json", to-json(%index);
                }
                when 'get' {
                    %response<topic> = $msg<topic> ;
                    %response<message> = %db{ $msg<topic> } ;
                    %response<status> = 'ok' ;
                }
                when 'dump' {
                    %response{'data'} = %db ;
                    %response<status> = 'ok' ;
                }
                when 'dumpindex' {
                    %response{'data'} = %index ;
                    %response<status> = 'ok' ;
                }
                when 'delete' {
                    %db{ $msg<topic> }:delete;
                    %response<status> = 'ok' ;
                    spurt "$dbfile.json", to-json(%db);
                    reindex();
                }
                when 'addindex' {
                    %response<status> = 'ok' ;
                    %index<keys_>{ $msg<key>} =1 ;
                    reindex();
                }
                when 'reportlast' {
                    %response{'data'} = %db{%index<last_>} ;
                    %response<status> = 'ok' ;
                }
                when 'reportlastindex' {
                    %response<key> = $msg<key> ;
                    for %index<lastkey_>{$msg<key>}.keys -> $value {
                        #%response{'data'}.push: %db{ %index<lastkey_>{ $msg<key>  }{ $value } } ;
                        %response{'data'}{$value} = %db{ %index<lastkey_>{ $msg<key>  }{ $value } } ;
                    }
                    %response<status> = 'ok' ;
                }
                when 'reportindex' {
                    %response<status> = 'ok' ;
                    for %index<idx_>{$msg<key>}.keys.sort -> $value  {
                        for %index<idx_>{ $msg<key> }{ $value }.keys.sort -> $topic {
                            %response<data>.push:  %db{ $topic }  ;
                            #%response<data>{$value} = %db{ $topic }  ;
                        }
                    }
                }
                when 'commit' {
                    spurt "$dbfile.json", to-json(%db);
                    spurt "{$dbfile}_index.json", to-json(%index);
                    %response<status> = 'ok' ;
                }
                default {
                    %response<status> = 'error';
                    %response<error> = 'no function or not supported';
                }
            }
            $conn.print( to-json(%response, :!pretty) ~ "\n" ) ;
            LAST { $conn.close ; }
            QUIT { default { $conn.close ; say "oh no, $_";}}
            CATCH { default { say .^name, ': ', .Str ,  " handled in $?LINE";}}
        }
    }
  }
    sub reindex {
        %index<idx_>:delete;
        for %db.keys -> $topic {
            my $msg = %db{$topic} ;
            for %index<keys_>.keys -> $key {
                if $msg{$key} {
                    %index<idx_>{ $key }{ $msg{$key} }{ $topic } = 1 ;
                }
            }
        }
        spurt "{$dbfile}_index.json", to-json(%index) ;
    }
}

```

**client.raku:**

```
#!/usr/bin/env raku
use JSON::Fast ;
multi MAIN('set', $topic,  $message='', :$server='localhost', :$port='3333', :$json='') {
    my %msg = function => 'set' , topic=> $topic , message=> $message ;
    %msg{"message"} = from-json( $json ) if $json ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('add', $topic,  $json, :$server='localhost', :$port='3333' ) {
    my %msg = function => 'set' , topic=> $topic;
    %msg{"message"} = from-json( $json ) if $json ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('get', $topic, :$server='localhost', :$port='3333') {
    my %msg = function => 'get' , topic=> $topic ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('delete', $topic, :$server='localhost', :$port='3333') {
    my %msg = function => 'delete' , topic=> $topic ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('dump', :$server='localhost', :$port='3333') {
    my %msg = function => 'dump'  ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('addindex', $key, :$server='localhost', :$port='3333') {
    my %msg = function => 'addindex', key => $key  ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('reportindex', $key, :$server='localhost', :$port='3333') {
    my %msg = function => 'reportindex', key => $key  ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('reportlastindex', $key, :$server='localhost', :$port='3333') {
    my %msg = function => 'reportlastindex', key => $key  ;
    sendmsg( %msg , $server, $port) ;
}
multi MAIN('reportlast', :$server='localhost', :$port='3333') {
    my %msg = function => 'reportlast' ;
    sendmsg( %msg , $server, $port) ;
}
sub sendmsg( %msg , $server, $port){
    my $conn = await IO::Socket::Async.connect( $server , $port );
    $conn.print: to-json( %msg,:!pretty)~"\n";
    react {
        whenever $conn.Supply -> $data {
            print $data;
            $conn.close;
        }
    }
}

```

Example:

```
./client.raku addindex constructor
./client.raku addindex date

./client.raku add 2007 '{"date":"2007-11-04","constructor":"Ducati","name":"Casey Stoner"}'
./client.raku add 2008 '{"date":"2008-10-26","constructor":"Yamaha","name":"Valentino Rossi"}'
./client.raku add 2009 '{"date":"2009-11-08","constructor":"Yamaha","name":"Valentino Rossi"}'
./client.raku add 2010 '{"date":"2010-11-17","constructor":"Yamaha","name":"Jorge Lorenzo"}'
./client.raku add 2011 '{"date":"2011-11-06","constructor":"Honda","name":"Casey Stoner"}'
./client.raku add 2012 '{"date":"2012-11-11","constructor":"Yamaha","name":"Jorge Lorenzo"}'
./client.raku add 2013 '{"date":"2013-11-10","constructor":"Honda","name":"Marc Márquez"}'
./client.raku add 2014 '{"date":"2014-11-09","constructor":"Honda","name":"Marc Márquez"}'
./client.raku add 2015 '{"date":"2015-11-08","constructor":"Yamaha","name":"Jorge Lorenzo"}'
./client.raku add 2016 '{"date":"2016-11-13","constructor":"Honda","name":"Marc Márquez"}'
./client.raku add 2017 '{"date":"2017-11-12","constructor":"Honda","name":"Marc Márquez"}'

./client.raku reportlast
./client.raku reportlastindex constructor
./client.raku reportindex date
```


[User]
The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.

For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.

Task
:   :   * Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as depicted. Optionally make it lovely by adding details such as, for example, doors and windows.

:   :   * Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.

:   :   * Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed.

[Assistant]
```
# 20250303 Raku programming solution

use Cairo;

sub house(Cairo::Context $cr, $x, $y, $size) {
   $cr.save;
   $cr.rgb(1.0, 1.0, 1.0);

   $cr.rectangle($x, $y, $size, $size);
   $cr.stroke;

   $cr.move_to($x + $size / 2, $y - $size / 2);
   $cr.line_to($x, $y);
   $cr.line_to($x + $size, $y);
   $cr.close_path;
   $cr.stroke;

   $cr.restore;
}

sub barchart(Cairo::Context $cr, @data, $x is copy, $y, $size) {
   $cr.save;
   $cr.rgb(1.0, 1.0, 1.0);

   my $maxdata = @data.max || 1;
   my $bar-width = $size / (@data.elems || 1);
   my $bar-spacing = $bar-width * 0.1;

   for @data -> $n {
      my $bar-height = ($n / $maxdata) * $size;
      $cr.rectangle($x, $y - $bar-height, $bar-width - $bar-spacing, $bar-height);
      $cr.stroke;
      $x += $bar-width;
   }

   $cr.restore;
}

sub testturtle($width = 400, $height = 600) {
   my $image = Cairo::Image.create(Cairo::FORMAT_ARGB32, $width, $height);
   my $cr = Cairo::Context.new($image);

   $cr.rgb(0.0, 0.0, 0.0);
   $cr.paint;

   $cr.line_width = 2.0;

   barchart($cr, [15, 10, 50, 35, 20], $width * 0.6, $height, $width / 3);
   house($cr, $width / 4, $height / 3, $width / 3);

   $image.write_png('turtle-raku.png');
}

testturtle();

```


[User]
Task

Create a window that has:

:   :   1. a label that says   "There have been no clicks yet"
        2. a button that says   "click me"

Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.

[Assistant]
(formerly Perl 6)

**Library:** GTK

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

my GTK::Simple::App $app .= new(title => 'Simple Windowed Application');

$app.size-request(350, 100);

$app.set-content(
    GTK::Simple::VBox.new(
        my $label  = GTK::Simple::Label.new( text  => 'There have been no clicks yet'),
        my $button = GTK::Simple::Button.new(label => 'click me'),
    )
);

$app.border-width = 40;

$button.clicked.tap: {
    state $clicks += 1;
    $label.text = "There has been $clicks click{ 's' if $clicks != 1 }";
}

$app.run;

```


[User]
Task

Send simulated keystrokes to a GUI window, or terminal.

You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.12

Use libxdo bindings to send text / keystrokes to any application that will accept keystrokes from X11.

```
use X11::libxdo;

my $xdo = Xdo.new;

my $active = $xdo.get-active-window;

my $command = $*VM.config<os> eq 'darwin' ?? 'open' !! 'xdg-open';

shell "$command https://www.google.com";

sleep 1;

my $match = rx[^'Google '];

say my $w = $xdo.search(:name($match))<ID>;

sleep .25;

if $w {
    $xdo.activate-window($w);
    say "Window name: ", $xdo.get-window-name( $w );
    $xdo.type($w, 'Raku language');
    sleep .25;
    $xdo.send-sequence($w, 'Tab');
    sleep .5;
    $xdo.send-sequence($w, 'Tab');
    sleep .5;
    $xdo.send-sequence($w, 'Tab');
    sleep .5;
    $xdo.send-sequence($w, 'Return');
}

```


[User] Simulate the click of a mouse button by the user. Specify if the target GUI may be externally created.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.12

Using bindings to libxdo so any window managed by an X11 display server can receive mouse events.

```
use X11::libxdo;
my $xdo = Xdo.new;

my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );

sleep .25;

for ^$dw -> $mx {
    my $my = (($mx / $dh * τ).sin * 500).abs.Int + 200;
    $xdo.move-mouse( $mx, $my, 0 );
    my ($x, $y, $window-id, $screen) = $xdo.get-mouse-info;
    my $name = (try $xdo.get-window-name($window-id) if $window-id)
       // 'No name set';

    my $line = "Mouse location: x=$x : y=$y\nWindow under mouse:\nWindow ID: " ~
       $window-id ~ "\nWindow name: " ~ $name ~ "\nScreen #: $screen";

    print "\e[H\e[J", $line;
    sleep .001;
}

say '';

#`[ There are several available routines controlling mouse position and button events.

.move-mouse( $x, $y, $screen ) # Move the mouse to a specific location.

.move-mouse-relative( $delta-x, $delta-y ) # Move the mouse relative to it's current position.

.move-mouse-relative-to-window( $x, $y, $window ) # Move the mouse to a specific location relative to the top-left corner of a window.

.get-mouse-location() # Get the current mouse location (coordinates and screen ID number).

.get-mouse-info() # Get all mouse location-related data.

.wait-for-mouse-to-move-from( $origin-x, $origin-y ) # Wait for the mouse to move from a location.

.wait-for-mouse-to-move-to( $dest-x, $dest-y ) # Wait for the mouse to move to a location.

.mouse-button-down( $window, $button ) # Send a mouse press (aka mouse down) for a given button at the current mouse location.

.mouse-button-up( $window, $button ) # Send a mouse release (aka mouse up) for a given button at the current mouse location.

.mouse-button-click( $window, $button ) # Send a click for a specific mouse button at the current mouse location.

.mouse-button-multiple( $window, $button, $repeat = 2, $delay? ) # Send a one or more clicks of a specific mouse button at the current mouse location.
]

```


[User]
Quoted from the Wikipedia page : **Simulated annealing (SA)** is a probabilistic technique for approximating the global optimum of a given function. Simulated annealing interprets slow cooling as a slow decrease in the probability of temporarily accepting worse solutions as it explores the solution space.

**Pseudo code** from Wikipedia

```
Notations :
  T : temperature. Decreases to 0.
  s : a system state
  E(s) : Energy at s. The function we want to minimize
  ∆E : variation of E, from state s to state s_next
  P(∆E , T) : Probability to move from s to s_next.
  	if  ( ∆E < 0 ) P = 1
  	      else P = exp ( - ∆E / T) . Decreases as T →  0

Pseudo-code:
    Let s = s0  -- initial state
    For k = 0 through kmax (exclusive):
        T ← temperature(k , kmax)
        Pick a random neighbour state , s_next ← neighbour(s)
        ∆E ← E(s) - E(s_next)
        If P(∆E , T) ≥ random(0, 1), move to the new state:
            s ← s_next
    Output: the final state s

```

**Problem statement**

We want to apply SA to the travelling salesman problem. There are 100 cities, numbered 0 to 99, located on a plane, at integer coordinates i,j : 0 <= i,j < 10 . The city at (i,j) has number 10\*i + j. The cities are **all** connected : the graph is complete : you can go from one city to any other city in one step.

The salesman wants to start from city 0, visit all cities, each one time, and go back to city 0. The travel cost between two cities is the euclidian distance between them. The total travel cost is the total path length.

A path **s** is a sequence (0 a b ...z 0) where (a b ..z) is a permutation of the numbers (1 2 .. 99). The path length = E(s) is the sum d(0,a) + d(a,b) + ... + d(z,0) , where d(u,v) is the distance between two cities. Naturally, we want to minimize E(s).

Definition : The neighbours of a city are the closest cities at distance 1 horizontally/vertically, or √2 diagonally. A corner city (0,9,90,99) has 3 neighbours. A center city has 8 neighbours.

```
Distances between cities
d ( 0, 7) → 7
d ( 0, 99) → 12.7279
d ( 23, 78) → 7.0711
d ( 33, 44) → 1.4142 // sqrt(2)

```

**Task**

Apply SA to the travelling salesman problem, using the following set of parameters/functions :

* kT = 1 (Multiplication by kT is a placeholder, representing computing temperature as a function of 1-k/kmax):
* temperature (k, kmax) = kT \* (1 - k/kmax)
* neighbour (s) : Pick a random city u > 0 . Pick a random neighbour city v > 0 of u , among u's 8 (max) neighbours on the grid. Swap u and v in s . This gives the new state *s\_next*.
* kmax = 1000\_000
* s0 = a random permutation

For k = 0 to kmax by step kmax/10 , display k, T, E(s). Display the final state s\_final, and E(s\_final).

You will see that the Energy may grow to a local optimum, before decreasing to a global optimum.

**Illustrated example**
Temperature charts

**Numerical example**

```
kT = 1
E(s0) = 529.9158

k:  0         T:  1       Es:  529.9158
k:  100000    T:  0.9     Es:  201.1726
k:  200000    T:  0.8     Es:  178.1723
k:  300000    T:  0.7     Es:  154.7069
k:  400000    T:  0.6     Es:  158.1412 <== local optimum
k:  500000    T:  0.5     Es:  133.856
k:  600000    T:  0.4     Es:  129.5684
k:  700000    T:  0.3     Es:  112.6919
k:  800000    T:  0.2     Es:  105.799
k:  900000    T:  0.1     Es:  102.8284
k:  1000000   T:  0       Es:  102.2426

E(s_final) =    102.2426
Path  s_final =   ( 0 10 11 21 31 20 30 40 50 60 70 80 90 91 81 71 73 83 84 74 64 54 55 65 75 76 66
 67 77 78 68 58 48 47 57 56 46 36 37 27 26 16 15 5 6 7 17 18 8 9 19 29 28 38 39 49 59 69
79 89 99 98 88 87 97 96 86 85 95 94 93 92 82 72 62 61 51 41 42 52 63 53 43 32 22 12 13
23 33 34 44 45 35 25 24 14 4 3 2 1 0)

```

**Extra credit**

Tune the parameters kT, kmax, or use different temperature() and/or neighbour() functions to demonstrate a quicker convergence, or a better optimum.

[Assistant]
(formerly Perl 6)

**Translation of**: Go

```
# simulation setup
my \cities = 100;  # number of cities
my \kmax   = 1e6;  # iterations to run
my \kT     = 1;    # initial 'temperature'

die 'City count must be a perfect square.' if cities.sqrt != cities.sqrt.Int;

# locations of (up to) 8 neighbors, with grid size derived from number of cities
my \gs = cities.sqrt;
my \neighbors = [1, -1, gs, -gs, gs-1, gs+1, -(gs+1), -(gs-1)];

# matrix of distances between cities
my \D = [;];
for 0 ..^ cities² -> \j {
    my (\ab, \cd)       = (j/cities, j%cities)».Int;
    my (\a, \b, \c, \d) = (ab/gs, ab%gs, cd/gs, cd%gs)».Int;
    D[ab;cd] = sqrt (a - c)² + (b - d)²
}

sub T(\k, \kmax, \kT)      { (1 - k/kmax) × kT }                                 # temperature function, decreases to 0
sub P(\ΔE, \k, \kmax, \kT) { exp( -ΔE / T(k, kmax, kT)) }                        # probability to move from s to s_next
sub Es(\path)              { sum (D[ path[$_]; path[$_+1] ] for 0 ..^ +path-1) } # energy at s, to be minimized

# variation of E, from state s to state s_next
sub delta-E(\s, \u, \v) {
    my (\a,   \b,  \c,  \d) = D[s[u-1];s[u]], D[s[u+1];s[u]], D[s[v-1];s[v]], D[s[v+1];s[v]];
    my (\na, \nb, \nc, \nd) = D[s[u-1];s[v]], D[s[u+1];s[v]], D[s[v-1];s[u]], D[s[v+1];s[u]];
    if    v == u+1 { return (na + nd) - (a + d) }
    elsif u == v+1 { return (nc + nb) - (c + b) }
    else           { return (na + nb + nc + nd) - (a + b + c + d) }
}

# E(s0), initial state
my \s = @ = flat 0, (1 ..^ cities).pick(*), 0;
my \E-min-global = my \E-min = $ = Es(s);

for 0 ..^ kmax -> \k {
    printf "k:%8u  T:%4.1f  Es: %3.1f\n" , k, T(k, kmax, kT), Es(s)
            if k % (kmax/10) == 0;

    # valid candidate cities (exist, adjacent)
    my \cv = neighbors[(^8).roll] + s[ my \u = 1 + (^(cities-1)).roll ];
    next if cv ≤ 0 or cv ≥ cities or D[s[u];cv] > sqrt(2);

    my \v  = s[cv];
    my \ΔE = delta-E(s, u, v);
    if ΔE < 0 or P(ΔE, k, kmax, kT) ≥ rand { # always move if negative
        (s[u], s[v]) = (s[v], s[u]);
        E-min += ΔE;
        E-min-global = E-min if E-min < E-min-global;
    }
}

say "\nE(s_final): " ~ E-min-global.fmt('%.1f');
say "Path:\n" ~ s».fmt('%2d').rotor(20,:partial).join: "\n";

```

Output:

```
k:       0  T: 1.0  Es: 522.0
k:  100000  T: 0.9  Es: 185.3
k:  200000  T: 0.8  Es: 166.1
k:  300000  T: 0.7  Es: 174.7
k:  400000  T: 0.6  Es: 146.9
k:  500000  T: 0.5  Es: 140.2
k:  600000  T: 0.4  Es: 127.5
k:  700000  T: 0.3  Es: 115.9
k:  800000  T: 0.2  Es: 111.9
k:  900000  T: 0.1  Es: 109.4

E(s_final): 109.4
Path:
 0 10 20 30 40 50 60 84 85 86 96 97 87 88 98 99 89 79 78 77
67 68 69 59 58 57 56 66 76 95 94 93 92 91 90 80 70 81 82 83
73 72 71 62 63 64 74 75 65 55 54 53 52 61 51 41 31 21 22 32
42 43 44 45 46 35 34 24 23 33 25 15 16 26 36 47 37 27 17 18
28 38 48 49 39 29 19  9  8  7  6  5  4 14 13 12 11  2  3  1
 0
```


[User]
Task

Generate a sine wave:

:   :   1. you choose the frequency of the wave
        2. generate a sine wave for 5 seconds
        3. play sound

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.04.01

What a horribly underspecified task. Ah well, gives me lots of wiggle room to cheat in various ways.

```
my ($rows,$cols) = qx/stty size/.words;
my $v = floor $rows / 2;
print "\e[H\e[J", 'Generating sine wave of zero amplitude and zero frequency for 5 seconds...',
  "\e[$v;0H", '_' x $cols;
sleep 5;
say "\e[H\e[J", 'No?, ok how about this:';

use SVG;
my $filename = 'sine.svg';
my $out = open($filename, :w) orelse .die;
$out.say: SVG.serialize(
    svg => [
        width => 400, height => 150, style => 'stroke:rgb(0,0,255)',
        :rect[:width<100%>, :height<100%>, :fill<white>],
        :path[ :fill<none>, :d('M0,25 C36.42,25,63.58,125,100,125 M100,125 C136.42,125,163.58,25,200,25 M200,25 C236.42,25,263.58,125,300,125 M300,125 C336.42,125,363.58,25,400,25') ],
    ],
);
close $out;
say "Sine wave generated to {$filename.IO.absolute}, better open it quickly...";
sleep 5;
unlink $filename;
say 'Oops, too late.';
say 'Still no? Ok how about:';
shell 'play -n -c1 synth 5.0 sin %-12';

```


[User]
A Global Singleton is a class of which only one instance exists within a program.

Any attempt to use non-static members of the class involves performing operations on this one instance.

[Assistant]
(formerly Perl 6)

```
class Singleton {
    # We create a lexical variable in the class block that holds our single instance.
    my Singleton $instance = Singleton.bless; # You can add initialization arguments here.
    method new {!!!} # Singleton.new dies.
    method instance { $instance; }
}

```


[User]
Define the data structure for a singly-linked list element. Said element should contain a data member capable of holding a numeric value, and the link to the next element should be mutable.

See also

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

[Assistant]
(formerly Perl 6)

#### With Pair

A Pair (constructed with the `=>` operator) can be treated as a cons cell, and thus used to build a linked lists:

```
my $elem = 42 => $nextelem;

```

However, because this is not the primary purpose of the Pair type, it suffers from the following limitations:

* The naming of Pair's accessor methods is not idiomatic for this use case (`.key` for the cell's value, and `.value` for the link to the next cell).
* A Pair (unlike an Array) does not automatically wrap its keys/values in item containers – so each cell of the list will be immutable once created, making element insertion/deletion impossible (except inserting at the front).
* It provides no built-in convenience methods for iterating/modifying/transforming such a list.

#### With custom type

For more flexibility, one would create a custom type:

```
class Cell {
    has      $.value is rw;
    has Cell $.next  is rw;

    # ...convenience methods here...
}

sub cons ($value, $next) { Cell.new(:$value, :$next) }

my $list = cons 10, (cons 20, (cons 30, Nil));

```


[User]
Using the link element defined in Singly-Linked List (element), define a method to insert an element into a singly-linked list following a given element.

Using this method, insert an element C into a list comprised of elements A->B, following element A.

See also

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

[Assistant]
(formerly Perl 6)

Extending class Cell from Singly-linked\_list/Element\_definition#Raku:

```
    method insert ($value) {
        $.next = Cell.new(:$value, :$.next)
    }

```


[User]
Task

Define a method to remove an element from a singly-linked list and demonstrate its use.

You may wish to use the link element defined in Singly-Linked List (element) for the purposes of this task.

See also

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

[Assistant]
(formerly Perl 6)

Extending class Cell from Singly-linked\_list/Element\_definition#Raku:

```
    method delete ($value --> Cell) {
        my $prev = Nil;
        my $cell = self;
        my $new-head = self;

        while $cell {
            my $next = $cell.next;
            if $cell.value == $value {
                $prev.next = $next if $prev;
                $cell.next = Nil;
                $new-head = $next if $cell === $new-head;
            }
            else {
                $prev = $cell;
            }
            $cell = $next;
        }

        return $new-head;
    }

```

Usage:

```
my $list = cons 10, (cons 20, (cons 10, (cons 30, Nil)));

$list = $list.delete(10);

```


[User]
:   I don't even know how to reverse a linked-list, and I don't even know what that is. -- a YouTuber.

Reverse a linked list. Obviously you can do it by turning it into a normal list and back, but feel free to use a smarter, possibly more efficient way.

[Assistant]
Extending code from the Singly-linked\_list/Element\_definition#Raku Task

```
# 20240220 Raku programming solution

class Cell { has ($.value, $.next) is rw;

   method reverse {
      my ($list, $prev) = self, Nil;
      while $list.defined {
         my $next = $list.next;
         $list.next = $prev;
         ($list, $prev) = ($next, $list)
      }
      return $prev;
   }

   method gist {
      my $cell = self;
      return ( gather while $cell.defined {
         take $cell.value andthen $cell = $cell.next;
      } ).Str
   }
}

sub cons ($value, $next = Nil) { Cell.new(:$value, :$next) }

my $list = cons 10, (cons 20, (cons 30, (cons 40, Nil)));

say $list = $list.reverse;
say $list = $list.reverse;

```

Output:

```
40 30 20 10
10 20 30 40
```

You may Attempt This Online!


[User]
Traverse from the beginning of a singly-linked list to the end.

See also

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

[Assistant]
(formerly Perl 6)

### With Pair

Built-in list processing in Raku is not specifically based on singly-linked lists,
but works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the Pair type to build what is essentially a Lisp-style cons list, and in fact, the => pair constructor is right associative for precisely that reason.
We traverse such a list here using a 3-part loop:

```
my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;

loop (my $l = $list; $l; $l.=value) {
    say $l.key;
}

```

Output:

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

It would be pretty easy to make such lists iterable as normal Raku lists,
if anyone really cared to...

Well, shoot, let's just go ahead and do it.
We'll pretend the Pair type is really a list type.
(And we show how you turn an ordinary list into a cons list using a reduction.
Note how the [=>] reduction is also right associative,
just like the base operator.)

```
use MONKEY-TYPING;
augment class Pair {
    method traverse () {
        gather loop (my $l = self; $l; $l.=value) {
            take $l.key;
        }
    }
}

my $list = [=>] 'Ⅰ' .. 'Ⅻ', Mu;
say ~$list.traverse;

```

Output:

```
Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ
```

### With custom type

Extending class Cell from Singly-linked\_list/Element\_definition#Raku:

```
    method Seq {
        self, *.next ...^ !*
    }

```

Usage:

```
my $list = (cons 10, (cons 20, (cons 30, Nil)));

for $list.Seq -> $cell {
    say $cell.value;
}

```

Output:

```
10
20
30
```


[User]
A
{\displaystyle {\displaystyle A}}
 is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by

X

−
1
A
X
{\displaystyle {\displaystyle X^{-1}AX}}
.
The eigenvectors in

X
{\displaystyle {\displaystyle X}}
 have three big problems: They are usually not orthogonal, there
are not always enough eigenvectors, and

A
x
{\displaystyle {\displaystyle Ax}}
 =

λ
x
{\displaystyle {\displaystyle \lambda x}}
 requires

A
{\displaystyle {\displaystyle A}}
 to be a square matrix. The
singular vectors of

A
{\displaystyle {\displaystyle A}}
 solve all those problems in a perfect way.

The Singular Value Decomposition (SVD)

According to the web page above, for any rectangular matrix

A
{\displaystyle {\displaystyle A}}
, we can decomposite it as

A
=
U
Σ

V

T
{\displaystyle {\displaystyle A=U\Sigma V^{T}}}

**Task Description**

Firstly, input two numbers "m" and "n".

Then, input a square/rectangular matrix

A

m
×
n
{\displaystyle {\displaystyle A^{m\times n}}}
.

Finally, output

U
,

Σ
,

V
{\displaystyle {\displaystyle U,~\Sigma ,\ V}}
 with respect to

A
{\displaystyle {\displaystyle A}}
.

**Example**

**Sample Input**

```
2 2
3 0
4 5

```

From the input above we can know that

A
{\displaystyle {\displaystyle A}}
 is a 2 by 2 matrix.

**Sample Output**

```

0.31622776601683794 -0.9486832980505138
0.9486832980505138 0.31622776601683794

6.708203932499369 0
0 2.23606797749979

0.7071067811865475 -0.7071067811865475
0.7071067811865475 0.7071067811865475

```

The output may vary depending your choice of the data types.

**Remark**

1. It’s encouraged to implement the algorithm by yourself while using libraries is still acceptible.

2. The algorithm should be applicable for general case(

m
×
n
{\displaystyle {\displaystyle m\times n}}
).

[Assistant]
```
# 20230108 Raku programming solution

use Math::Libgsl::Matrix;
use Math::Libgsl::LinearAlgebra;

my @M = <3 0>, <4 5>;
my Math::Libgsl::Matrix \M .= new: @M.elems, @M.first.elems;
(^M.size1)>>.&{ M.set-row: $_, @M[$_;*] }

my (\V,\S) = SV-decomp M;

say "U factor: "        and say (^M.size1)>>.&{ M.get-row($_)>>.fmt: '%.10g' }
say "singular values: " and say (^S.size )>>.&{     S.get($_)>>.fmt: '%.10g' }
say "Vt factor: "       and say (^V.size1)>>.&{ V.get-row($_)>>.fmt: '%.10g' }

```

Output:

```
U factor:
([-0.316227766 -0.9486832981] [-0.9486832981 0.316227766])
singular values:
((6.708203932) (2.236067977))
Vt factor:
([-0.7071067812 -0.7071067812] [-0.7071067812 0.7071067812])
```


[User]
The **Sisyphus sequence** is an infinite sequence of positive integers that was devised in 2022 by Eric Angelini and Carole Dubois.

The first term is 1. Subsequent terms are found by applying the following rule:

* If the previous term was even, then halve it.

* If the previous term was odd, then add the smallest prime number that has not yet been added.

1 is odd and so the second term is: 1 + 2 = 3, because 2 is the smallest prime not yet added.

3 is odd and so the third term is: 3 + 3 = 6, because 3 is the smallest prime not yet added.

6 is even and so the fourth term is : 6 ÷ 2 = 3, and so on.

Task

Find and show on this page (in 10 lines of 10 terms), the first 100 terms of the sequence.

What are the **1,000**th, **10,000**th, **100,000**th and **1,000,000**th terms of the sequence and, in each case, what is the highest prime needed to reach them?

If it is difficult or impossible for your language or output device to meet all of these requirements, then just do what you reasonably can.

Stretch

What are the **10 millionth** and **100 millionth** terms and the highest prime needed to reach each one?

By the time the **100 millionth** term is reached, which number(s) **under 250**:

* Have not yet occurred in the sequence.

* Have occurred the most times and their number of occurrences.

Extreme stretch

What is the number of the first term to equal 36?

This was originally set as a challenge by Neil Sloane who was worried by its non-appearance and found by Russ Cox.

References

* OEIS sequence A350877: The Sisyphus sequence

[Assistant]
```
use Math::Primesieve;
use Lingua::EN::Numbers;

my ($exp1, $exp2, $limit1, $limit2)  = 3, 8, 100, 250;
my ($n, $s0, $s1, $p, @S1, %S) =  1, 1, Any, Any, 1;
my $iterator = Math::Primesieve::iterator.new;
my @Nth = ($exp1..$exp2)».exp(10);
my $S2 = BagHash.new;

repeat {
    $n++;
    $s1 = $s0 %% 2 ?? $s0 div 2 !! $s0 + ($p = $iterator.next);
    @S1.push: $s1 if  $n ≤ $limit1;
    $S2.add:  $s1 if $s1 ≤ $limit2;
    %S{$n}{'value', 'prime'} = $s1, $p if $n ∈ @Nth;
    $s0 = $s1;
} until $n == @Nth[*-1];

say "The first $limit1 members of the Sisyphus sequence are:";
say @S1.batch(10)».fmt('%4d').join("\n") ~ "\n";
printf "%12sth member is: %13s with prime: %11s\n", ($_, %S{$_}{'value'}, %S{$_}{'prime'})».&comma for @Nth;
say "\nNumbers under $limit2 that do not occur in the first {comma @Nth[*-1]} terms:";
say (1..$limit2).grep: * ∉ $S2.keys;
say "\nNumbers under $limit2 that occur the most ({$S2.values.max} times) in the first {comma @Nth[*-1]} terms:";
say $S2.keys.grep({ $S2{$_} == $S2.values.max}).sort;

```

Output:

```
The first 100 members of the Sisyphus sequence are:
   1    3    6    3    8    4    2    1    8    4
   2    1   12    6    3   16    8    4    2    1
  18    9   28   14    7   30   15   44   22   11
  42   21   58   29   70   35   78   39   86   43
  96   48   24   12    6    3   62   31   92   46
  23   90   45  116   58   29  102   51  130   65
 148   74   37  126   63  160   80   40   20   10
   5  106   53  156   78   39  146   73  182   91
 204  102   51  178   89  220  110   55  192   96
  48   24   12    6    3  142   71  220  110   55

       1,000th member is:           990 with prime:       2,273
      10,000th member is:        24,975 with prime:      30,713
     100,000th member is:       265,781 with prime:     392,111
   1,000,000th member is:     8,820,834 with prime:   4,761,697
  10,000,000th member is:    41,369,713 with prime:  55,900,829
 100,000,000th member is: 1,179,614,168 with prime: 640,692,323

Numbers under 250 that do not occur in the first 100,000,000 terms:
36 72 97 107 115 127 144 167 194 211 214 230 232

Numbers under 250 that occur the most (7 times) in the first 100,000,000 terms:
7 14 28

```


[User]
Task

Write a program that does the following in this order:

* Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
* Print "Sleeping..."
* Sleep the main thread for the given amount of time.
* Print "Awake!"
* End.

Related task

* Nautical bell

[Assistant]
(formerly Perl 6)

The sleep function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).

```
my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
say "Sleeping...";
sleep $sec;
say "Awake!";

```

Note that 1.2096 is a rational number in Raku, not floating point, so precision can be maintained even when dealing with very small powers of ten.


[User]
Background on the task

In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.

If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.

Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.

Task

Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.

[Assistant]
```
sub sleeping-beauty ($trials) {
    my $gotheadsonwaking = 0;
    my $wakenings = 0;
    ^$trials .map: {
        given <Heads Tails>.roll {
            ++$wakenings;
            when 'Heads' { ++$gotheadsonwaking }
            when 'Tails' { ++$wakenings }
        }
    }
    say "Wakenings over $trials experiments: ", $wakenings;
    $gotheadsonwaking / $wakenings
}

say "Results of experiment:  Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000);

```

Output:

```
Wakenings over 1000000 experiments: 1500040
Results of experiment:  Sleeping Beauty should estimate a credence of: 0.333298
```


[User]
The **smallest enclosing circle problem** (aka **minimum covering circle problem**, **bounding circle problem**) is a mathematical problem of computing the smallest circle that contains all of a given set of points in the Euclidean plane.

Initially it was proposed by the English mathematician James Joseph Sylvester in 1857.

Task

Find circle of smallest radius containing all of given points.

* Circle is defined by it's center and radius;
* Points are defined by their coordinates in n-dimensional space;
* Circle (sphere) contains point when *distance between point and circle center <= circle radius*.

[Assistant]
**Translation of**: Go

```
class P { has ($.x, $.y) is rw;                # Point
   method gist { "({$.x~", "~$.y})" }
}

class C { has (P $.c, Numeric $.r);            # Circle
   method gist { "Center = " ~$.c.gist ~ " and Radius = $.r\n" }

   # tests whether a circle contains the point 'p'
   method contains(P \p --> Bool) { distSq($.c, p) ≤ $.r² }

   # tests whether a circle contains a slice of point
   method encloses(@ps --> Bool) { [and] @ps.map: { $.contains($_) } }
}

sub infix:<−> (P \a, P \b) { a.x - b.x, a.y - b.y } # note: Unicode 'minus'

# returns the square of the distance between two points
sub distSq (P \a, P \b) { [+] (a − b)»² }

sub getCenter (\bx, \by, \cx, \cy --> P) {
   my (\b,\c,\d) = bx²+by², cx²+cy², bx*cy - by*cx;
   P.new: x => (cy*b - by*c) / (2 * d), y => (bx*c - cx*b) / (2 * d)
} # returns the center of a circle defined by 3 points

sub circleFrom3 (P \a, P \b, P \c --> C)  {
   my \k = $ = getCenter |(b − a), |(c − a);
   k.x, k.y Z[+=] a.x, a.y;
   C.new: c => k, r => distSq(k, a).sqrt
} # returns a unique circle that intersects 3 points

sub circleFrom2 (P \a, P \b --> C ) {
   my \center = P.new: x => ((a.x + b.x) / 2), y => ((a.y + b.y) / 2) ;
   C.new: c => center, r => (distSq(a, b).sqrt / 2)
} # returns smallest circle that intersects 2 points

sub secTrivial( @rs --> C ) {
   given @rs {
      when * == 0 { return C.new: c => (P.new: x => 0, y => 0), r => 0 }
      when * == 1 { return C.new: c => @rs[0], r => 0 }
      when * == 2 { return circleFrom2 |@rs }
      when * == 3 { #`{ no-op } }
      when *  > 3 { die "There shouldn't be more than 3 points." }
   }
   for 0, 1 X 1, 2 -> ( \i, \j ) {
      return $_ if .encloses(@rs) given circleFrom2 |@rs[i,j]
   }
   circleFrom3 |@rs
} # returns smallest enclosing circle for n ≤ 3

sub Welzl-helper( @ps is copy, @rs is copy , \n --> C ) {
   return secTrivial(@rs) if n == 0 or @rs == 3;
   my \p = @ps.shift;
   return $_ if .contains(p) given Welzl-helper @ps, @rs, n-1;
   Welzl-helper @ps, @rs.append(p), n-1
} # helper function for Welzl method

# applies the Welzl algorithm to find the SEC
sub welzl(@ps --> C) { Welzl-helper @ps.pick(*), [], @ps }

my @tests = (
   [ (0,0), (0,1), (1,0) ],
   [ (5,-2), (-3,-2), (-2,5), (1,6), (0,2) ]
).map: {
   @_.map: { P.new: x => $_[0], y => $_[1] }
}

say "Solution for smallest circle enclosing {$_.gist} :\n", welzl $_ for @tests;

```

Output:

```
Solution for smallest circle enclosing ((0, 0) (0, 1) (1, 0)) :
Center = (0.5, 0.5) and Radius = 0.7071067811865476

Solution for smallest circle enclosing ((5, -2) (-3, -2) (-2, 5) (1, 6) (0, 2)) :
Center = (1, 1) and Radius = 5
```


[User]
Task

Task description is taken from Project Euler

(https://projecteuler.net/problem=5)

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Related

* Least common multiple

[Assistant]
Exercise with some larger values as well.

```
say "$_: ", [lcm] 2..$_ for <10 20 200 2000>

```

Output:

```
10: 2520
20: 232792560
200: 337293588832926264639465766794841407432394382785157234228847021917234018060677390066992000
2000: 151117794877444315307536308337572822173736308853579339903227904473000476322347234655122160866668946941993951014270933512030194957221371956828843521568082173786251242333157830450435623211664308500316844478617809101158220672108895053508829266120497031742749376045929890296052805527212315382805219353316270742572401962035464878235703759464796806075131056520079836955770415021318508272982103736658633390411347759000563271226062182345964184167346918225243856348794013355418404695826256911622054015423611375261945905974225257659010379414787547681984112941581325198396634685659217861208771400322507388161967513719166366839894214040787733471287845629833993885413462225294548785581641804620417256563685280586511301918399010451347815776570842790738545306707750937624267501103840324470083425714138183905657667736579430274197734179172691637931540695631396056193786415805463680000
```


[User]
Generate the sequence of numbers **a(k)**, where each **k** is the smallest positive integer such that **k + 2m** is composite for every positive integer **m** less than **k**.

For example

Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails.

Is 7 + 21 (9) prime? False

Is 7 + 22 (11) prime? True

So 7 is not an element of this sequence.

It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite.

Task

Find and display, here on this page, the first **5** elements of this sequence.

See also

OEIS:A033919 - Odd k for which k+2^m is composite for all m < k

[Assistant]
```
put (1..∞).hyper(:250batch).map(* × 2 + 1).grep( -> $k { !(1 ..^ $k).first: ($k + 1 +< *).is-prime } )[^5]

```

Output:

```
773 2131 2491 4471 5101
```


[User]
Task

Smallest positive integer   **k**   such that the decimal expansion of   **kk**   contains   **n**,   where   **n  <  51**

[Assistant]
```
sub smallest ( $n ) {
    state  @powers = '', |map { $_ ** $_ }, 1 .. *;

    return @powers.first: :k, *.contains($n);
}

.say for (^51).map(&smallest).batch(10)».fmt('%2d');

```

Output:

```
( 9  1  3  5  2  4  4  3  7  9)
(10 11  5 19 22 26  8 17 16 19)
( 9  8 13  7 17  4 17  3 11 18)
(13  5 23 17 18  7 17 15  9 18)
(16 17  9  7 12 28  6 23  9 24)
(23)

```


[User]
Task

Show the smallest (non-negative integer) power of   **6**   whose decimal expansion contains   **n,**     where   **n   <   22**

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

my @po6 = ^Inf .map: *.exp: 6;

put join "\n", (flat ^22, 120).map: -> $n {
    sprintf "%3d: 6%-4s %s", $n, .&super, comma @po6[$_]
    given @po6.first: *.contains($n), :k
};

```

Output:

```
  0: 6⁹    10,077,696
  1: 6⁰    1
  2: 6³    216
  3: 6²    36
  4: 6⁶    46,656
  5: 6⁶    46,656
  6: 6¹    6
  7: 6⁵    7,776
  8: 6¹²   2,176,782,336
  9: 6⁴    1,296
 10: 6⁹    10,077,696
 11: 6¹⁶   2,821,109,907,456
 12: 6⁴    1,296
 13: 6¹³   13,060,694,016
 14: 6²⁸   6,140,942,214,464,815,497,216
 15: 6¹⁸   101,559,956,668,416
 16: 6³    216
 17: 6¹⁰   60,466,176
 18: 6¹⁵   470,184,984,576
 19: 6²¹   21,936,950,640,377,856
 20: 6²⁶   170,581,728,179,578,208,256
 21: 6³    216
120: 6¹⁴⁷  2,444,746,349,972,956,194,083,608,044,935,243,159,422,957,210,683,702,349,648,543,934,214,737,968,217,920,868,940,091,707,112,078,529,114,392,164,827,136
```


[User]
Task

Find the smallest  (decimal integer)  squares that begin with      **n**      for    0 < **n** < 50

[Assistant]
```
# 20210319 Raku programming solution

my @needles  = (1..49);
my @haystack = (1..*) Z× (1..*);
# my @haystack = ( 1, 4, -> \a, \b { 2*b - a + 2 } ... * );
# my @haystack = ( 1, { (++$)² } ... * );
for @needles -> \needle {
   for @haystack -> \hay {
      { say needle, " => ", hay and last } if hay.starts-with: needle
   }
}

```

Output:

```
1 => 1
2 => 25
3 => 36
4 => 4
5 => 529
6 => 64
7 => 729
8 => 81
9 => 9
10 => 100
11 => 1156
12 => 121
13 => 1369
14 => 144
15 => 1521
16 => 16
17 => 1764
18 => 1849
19 => 196
20 => 2025
21 => 2116
22 => 225
23 => 2304
24 => 2401
25 => 25
26 => 2601
27 => 2704
28 => 289
29 => 2916
30 => 3025
31 => 3136
32 => 324
33 => 3364
34 => 3481
35 => 35344
36 => 36
37 => 3721
38 => 3844
39 => 3969
40 => 400
41 => 41209
42 => 4225
43 => 4356
44 => 441
45 => 45369
46 => 4624
47 => 4761
48 => 484
49 => 49

```

As the desired range is so small, there is not much gained by caching the squares. Less efficient, but less verbose:

```
say $_ => ^Inf .map(*²).first: *.starts-with: $_ for 1..49;

```

Same output.


[User]
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.

For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.

Task

* Show the first 25 SPDS primes.
* Show the hundredth SPDS prime.

See also

* OEIS A019546: Primes whose digits are primes.
* https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences

[Assistant]
(formerly Perl 6)

**Library:** ntheory

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

# Implemented as a lazy, extendable list
my $spds = grep { .&is_prime }, flat [2,3,5,7], [23,27,33,37,53,57,73,77], -> $p
  { state $o++; my $oom = 10**(1+$o); [ flat (2,3,5,7).map: -> $l { (|$p).map: $l×$oom + * } ] } … *;

say 'Smarandache prime-digitals:';
printf "%22s: %s\n", ordinal(1+$_).tclc, comma $spds[$_] for flat ^25, 99, 999, 9999, 99999;

```

Output:

```
Smarandache prime-digitals:
                 First: 2
                Second: 3
                 Third: 5
                Fourth: 7
                 Fifth: 23
                 Sixth: 37
               Seventh: 53
                Eighth: 73
                 Ninth: 223
                 Tenth: 227
              Eleventh: 233
               Twelfth: 257
            Thirteenth: 277
            Fourteenth: 337
             Fifteenth: 353
             Sixteenth: 373
           Seventeenth: 523
            Eighteenth: 557
            Nineteenth: 577
             Twentieth: 727
          Twenty-first: 733
         Twenty-second: 757
          Twenty-third: 773
         Twenty-fourth: 2,237
          Twenty-fifth: 2,273
         One hundredth: 33,223
        One thousandth: 3,273,527
        Ten thousandth: 273,322,727
One hundred thousandth: 23,325,232,253
```


[User]
Definitions

A **Smarandache-Wellin number** (S-W number for short) is an integer that in a given base is the concatenation of the first n prime numbers written in that base. A base of 10 will be assumed for this task.

A **Derived S-W number** (not an 'official' term) is an integer formed from a S-W number by working out the number of times each of the digits 0 to 9 occurs in that number, concatenating those frequencies in the same order (i.e. frequency of '0' first, frequency of '1' second etc) and removing any leading zeros.

Examples

'23571113' is the sixth S-W number formed by concatenating the first 6 primes: 2, 3, 5, 7, 11 and 13.

The corresponding Derived S-W number is '312010100' because '1' occurs 3 times, '3' occurs twice and '2', '5' and '7' all occur once.

Task

* Find and show the first three S-W numbers which are prime.

* Find and show the first three Derived S-W numbers which are prime.

Stretch (requires 'big integer' support)

Find and show the index in the sequence (starting from 1), the total number of digits and the last prime used to form the fourth, fifth, sixth, seventh and (optionally) the eighth S-W numbers which are prime or probably prime with reasonable certainty. It is unknown whether there are any more but, if you fancy searching for one, good luck! You can start from an index of 22,077.

Also find and show up to the first twenty Derived S-W numbers which are prime and their index in the sequence.

References

* Wikipedia: Smarandache-Wellin number
* OEIS:A019518 - Smarandache-Wellin numbers
* OEIS:A069151 - Smarandache-Wellin primes

[Assistant]
The first seven Smarandache-Wellin primes are found in a few seconds on my system. The eighth adds over five minutes to the run time.

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

my @primes = (^∞).grep: &is-prime;

my @Smarandache-Wellin = [\~] @primes;

sink @Smarandache-Wellin[1500]; # pre-reify for concurrency

sub derived ($n) { my %digits = $n.comb.Bag; (0..9).map({ %digits{$_} // 0 }).join }

sub abbr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '…' ~ .substr(*-20) ~ " ({.chars} digits)" }

say "Smarandache-Wellin primes:";
say ordinal-digit(++$,:u).fmt("%4s") ~ $_ for (^∞).hyper(:4batch).map({
    next unless (my $sw = @Smarandache-Wellin[$_]).is-prime;
    sprintf ": Index: %4d, Last prime: %5d, %s", $_, @primes[$_], $sw.&abbr
})[^8];

say "\nSmarandache-Wellin derived primes:";
say ordinal-digit(++$,:u).fmt("%4s") ~ $_ for (^∞).hyper(:8batch).map({
    next unless (my $sw = @Smarandache-Wellin[$_].&derived).is-prime;
    sprintf ": Index: %4d, %s", $_, $sw
})[^20];

```

Output:

```
Smarandache-Wellin primes:
 1ˢᵗ: Index:    0, Last prime:     2, 2
 2ⁿᵈ: Index:    1, Last prime:     3, 23
 3ʳᵈ: Index:    3, Last prime:     7, 2357
 4ᵗʰ: Index:  127, Last prime:   719, 23571113171923293137…73677683691701709719 (355 digits)
 5ᵗʰ: Index:  173, Last prime:  1033, 23571113171923293137…10131019102110311033 (499 digits)
 6ᵗʰ: Index:  341, Last prime:  2297, 23571113171923293137…22732281228722932297 (1171 digits)
 7ᵗʰ: Index:  434, Last prime:  3037, 23571113171923293137…30013011301930233037 (1543 digits)
 8ᵗʰ: Index: 1428, Last prime: 11927, 23571113171923293137…11903119091192311927 (5719 digits)

Smarandache-Wellin derived primes:
 1ˢᵗ: Index:   31, 4194123321127
 2ⁿᵈ: Index:   71, 547233879626521
 3ʳᵈ: Index:   72, 547233979727521
 4ᵗʰ: Index:  133, 13672766322929571043
 5ᵗʰ: Index:  224, 3916856106393739943689
 6ᵗʰ: Index:  302, 462696313560586013558131
 7ᵗʰ: Index:  308, 532727113760586013758133
 8ᵗʰ: Index:  362, 6430314317473636515467149
 9ᵗʰ: Index:  461, 8734722823685889120488197
10ᵗʰ: Index:  489, 9035923128899919621189209
11ᵗʰ: Index:  494, 9036023329699969621389211
12ᵗʰ: Index:  521, 9337023533410210710923191219
13ᵗʰ: Index:  537, 94374237357103109113243102223
14ᵗʰ: Index:  623, 117416265406198131121272110263
15ᵗʰ: Index:  720, 141459282456260193137317129313
16ᵗʰ: Index:  737, 144466284461264224139325131317
17ᵗʰ: Index:  789, 156483290479273277162351153339
18ᵗʰ: Index:  851, 164518312512286294233375158359
19ᵗʰ: Index: 1086, 208614364610327343341589284471
20ᵗʰ: Index: 1187, 229667386663354357356628334581
```


[User]
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.

By definition, all primes are *excluded* as they (naturally) satisfy this condition!

Smith numbers are also known as   *joke*   numbers.

Example

Using the number **166**
Find the prime factors of **166** which are: **2** x **83**
Then, take those two prime factors and sum all their decimal digits: **2 + 8 + 3** which is **13**
Then, take the decimal digits of **166** and add their decimal digits: **1 + 6 + 6** which is **13**
Therefore, the number **166** is a Smith number.

Task

Write a program to find all Smith numbers *below* 10000.

See also

* from Wikipedia:   [Smith number].
* from MathWorld:   [Smith number].
* from OEIS A6753:   [OEIS sequence A6753].
* from OEIS A104170:   [Number of Smith numbers below 10^n].
* from The Prime pages:   [Smith numbers].

[Assistant]
(formerly Perl 6)

```
constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;

multi factors ( 1 ) { 1 }
multi factors ( Int $remainder is copy ) {
  gather for @primes -> $factor {

    # if remainder < factor², we're done
    if $factor * $factor > $remainder {
      take $remainder if $remainder > 1;
      last;
    }

    # How many times can we divide by this prime?
    while $remainder %% $factor {
        take $factor;
        last if ($remainder div= $factor) === 1;
    }
  }
}
# Code above here is verbatim from RC:Count_in_factors#Raku

sub is_smith_number ( Int $n ) {
  (!$n.is-prime) and ( [+] $n.comb ) == ( [+] factors($n).join.comb );
}

my @s = grep &is_smith_number, 2 ..^ 10_000;
say "{@s.elems} Smith numbers below 10_000";
say 'First 10: ', @s[  ^10      ];
say 'Last  10: ', @s[ *-10 .. * ];

```

Output:

```
376 Smith numbers below 10_000
First 10: (4 22 27 58 85 94 121 166 202 265)
Last  10: (9843 9849 9861 9880 9895 9924 9942 9968 9975 9985)
```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Snake\_(video\_game). 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) |

Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source.

Task

Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.

Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.

The game ends when the snake attempts to eat himself.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.08

This is a variation of a demo script included in the examples folder for the Raku SDL2::Raw library bindings.

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

constant W = 1280;
constant H = 960;

constant FIELDW = W div 32;
constant FIELDH = H div 32;

SDL_Init(VIDEO);

my $window = SDL_CreateWindow(
    'Snake',
    SDL_WINDOWPOS_CENTERED_MASK,
    SDL_WINDOWPOS_CENTERED_MASK,
    W, H,
    OPENGL
);

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

my $snake_image = Cairo::Image.record(
    -> $_ {
        .save;
        .rectangle: 0, 0, 64, 64;
        .clip;
        .rgb: 0, 1, 0;
        .rectangle: 0, 0, 64, 64;
        .fill :preserve;
        .rgb: 0, 0, 0;
        .stroke;
        .restore;

        .save;
        .translate: 64, 0;
        .rectangle: 0, 0, 64, 64;
        .clip;
        .rgb: 1, 0, 0;
        .arc: 32, 32, 30, 0, 2 * pi;
        .fill :preserve;
        .rgb: 0, 0, 0;
        .stroke;
        .restore;
    }, 128, 128, Cairo::FORMAT_ARGB32);

my $snake_texture = SDL_CreateTexture(
    $render,
    %PIXELFORMAT<ARGB8888>,
    STATIC,
    128,
    128
);

SDL_UpdateTexture(
    $snake_texture,
    SDL_Rect.new(
        :x(0),
        :y(0),
        :w(128),
        :h(128)
    ),
    $snake_image.data,
    $snake_image.stride // 128 * 4
);

SDL_SetTextureBlendMode($snake_texture, 1);

SDL_SetRenderDrawBlendMode($render, 1);

my $snakepiece_srcrect = SDL_Rect.new(:w(64), :h(64));
my $nompiece_srcrect   = SDL_Rect.new(:w(64), :h(64), :x(64));

my $event = SDL_Event.new;

enum GAME_KEYS (
    K_UP    => 82,
    K_DOWN  => 81,
    K_LEFT  => 80,
    K_RIGHT => 79,
);

my Complex @snakepieces = 10+10i;
my Complex @noms;
my Complex $snakedir = 1+0i;
my $nomspawn   = 0;
my $snakespeed = 0.1;
my $snakestep  = 0;
my $nom        = 4;

my $last_frame_start = now;
main: loop {
    my $start = now;
    my $dt = $start - $last_frame_start // 0.00001;
    while SDL_PollEvent($event) {
        my $casted_event = SDL_CastEvent($event);
        given $casted_event {
            when *.type == QUIT    { last main }
            when *.type == KEYDOWN {
                if GAME_KEYS(.scancode) -> $comm {
                    given $comm {
                        when 'K_LEFT'  { $snakedir = -1+0i unless $snakedir ==  1+0i }
                        when 'K_RIGHT' { $snakedir =  1+0i unless $snakedir == -1+0i }
                        when 'K_UP'    { $snakedir =  0-1i unless $snakedir ==  0+1i }
                        when 'K_DOWN'  { $snakedir =  0+1i unless $snakedir ==  0-1i }
                    }
                }
            }
        }
    }

    if ($nomspawn -= $dt) < 0 {
        $nomspawn += 1;
        @noms.push: (^FIELDW).pick + (^FIELDH).pick * i unless @noms > 3;
        @noms.pop if @noms[*-1] == any(@snakepieces);
    }

    if ($snakestep -= $dt) < 0 {
        $snakestep += $snakespeed;

        @snakepieces.unshift: do given @snakepieces[0] {
            ($_.re + $snakedir.re) % FIELDW
            + (($_.im + $snakedir.im) % FIELDH) * i
        }

        if @snakepieces[2..*].first( * == @snakepieces[0], :k ) -> $idx {
            @snakepieces = @snakepieces[0..($idx + 1)];
        }

        @noms .= grep(
            { $^piece == @snakepieces[0] ?? ($nom += 1) && False !! True }
        );

        if $nom == 0 {
            @snakepieces.pop;
        } else {
            $nom = $nom - 1;
        }
    }

    for @snakepieces {
        SDL_SetTextureColorMod(
            $snake_texture,
            255,
            (cos((++$) / 2) * 100 + 155).round,
            255
        );

        SDL_RenderCopy(
            $render,
            $snake_texture,
            $snakepiece_srcrect,
            SDL_Rect.new(.re * 32, .im * 32, 32, 32)
        );
    }

    SDL_SetTextureColorMod($snake_texture, 255, 255, 255);

    for @noms {
        SDL_RenderCopy(
            $render,
            $snake_texture,
            $nompiece_srcrect,
            SDL_Rect.new(.re * 32, .im * 32, 32, 32)
        )
    }

    SDL_RenderPresent($render);
    SDL_SetRenderDrawColor($render, 0, 0, 0, 0);
    SDL_RenderClear($render);

    $last_frame_start = $start;
    sleep(1 / 50);
}

SDL_Quit();

```


[User]
Task

Create a Snakes and Ladders game where the computer plays against a human player.

This game is also known as   **Chutes and Ladders**.

For a board example you can use this image here: snakes & ledders.

(A **ledder** is the Old English word for a **ladder**.)

The way you'll represent the board and the players' tokens is totally up to you: graphics or ASCII graphics or even just text.

Happy coding.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.01

Snakes and ladders is entirely chance based, so human interaction is not really required. This version allows up to one human player against any number of computer players and asks for input... but doesn't really *need* or even *use* it. I didn't bother to implement a graphical interface.

```
        # board layout
my %snl =  4, 14,  9, 31, 17,  7, 20, 38, 28, 84, 40, 59, 51, 67, 54, 34,
          62, 19, 63, 81, 64, 60, 71, 91, 87, 24, 93, 73, 95, 75, 99, 78;

my @players = 1, 1, 1; # three players, starting on square 1
my $human = 1;         # player 1 is human. set to 0 for all computer players

loop {
    for ^@players -> $player {
        turn(@players[$player], $player + 1);
    }
    say '';
}

sub turn ($square is rw, $player) {
    if $player == $human {
        prompt "You are on square $square. Hit enter to roll the die.";
    }
    my $roll = (1..6).roll;
    my $turn = $square + $roll;
    printf "Player $player on square %2d rolls a $roll", $square;
    if $turn > 100 {
        say " but cannot move. Next players turn.";
        return $square;
    }
    if %snl{$turn} {
        $square = %snl{$turn};
        if $turn > $square {
            say ". Oops! Landed on a snake. Slither down to $square."
        } else {
            say ". Yay! Landed on a ladder. Climb up to $square."
        }
    } else {
        $square = $turn;
        say " and moves to square $square";
    }
    say "Player $player wins!" and exit if $square == 100;
    return $square;
}

```

Sample output:

```
You are on square 1. Hit enter to roll the die.
Player 1 on square  1 rolls a 1 and moves to square 2
Player 2 on square  1 rolls a 4 and moves to square 5
Player 3 on square  1 rolls a 1 and moves to square 2

You are on square 2. Hit enter to roll the die.
Player 1 on square  2 rolls a 1 and moves to square 3
Player 2 on square  5 rolls a 2 and moves to square 7
Player 3 on square  2 rolls a 3 and moves to square 5

You are on square 3. Hit enter to roll the die.
Player 1 on square  3 rolls a 4 and moves to square 7
Player 2 on square  7 rolls a 1 and moves to square 8
Player 3 on square  5 rolls a 2 and moves to square 7

You are on square 7. Hit enter to roll the die.
Player 1 on square  7 rolls a 2. Yay! Landed on a ladder. Climb up to 31.
Player 2 on square  8 rolls a 3 and moves to square 11
Player 3 on square  7 rolls a 2. Yay! Landed on a ladder. Climb up to 31.

  ... about 15 turns omitted ...

You are on square 90. Hit enter to roll the die.
Player 1 on square 90 rolls a 3. Oops! Landed on a snake. Slither down to 73.
Player 2 on square 55 rolls a 3 and moves to square 58
Player 3 on square 90 rolls a 4 and moves to square 94

You are on square 73. Hit enter to roll the die.
Player 1 on square 73 rolls a 6 and moves to square 79
Player 2 on square 58 rolls a 5. Yay! Landed on a ladder. Climb up to 81.
Player 3 on square 94 rolls a 3 and moves to square 97

You are on square 79. Hit enter to roll the die.
Player 1 on square 79 rolls a 3 and moves to square 82
Player 2 on square 81 rolls a 6. Oops! Landed on a snake. Slither down to 24.
Player 3 on square 97 rolls a 5 but cannot move. Next players turn.

You are on square 82. Hit enter to roll the die.
Player 1 on square 82 rolls a 5. Oops! Landed on a snake. Slither down to 24.
Player 2 on square 24 rolls a 6 and moves to square 30
Player 3 on square 97 rolls a 4 but cannot move. Next players turn.

You are on square 24. Hit enter to roll the die.
Player 1 on square 24 rolls a 4. Yay! Landed on a ladder. Climb up to 84.
Player 2 on square 30 rolls a 5 and moves to square 35
Player 3 on square 97 rolls a 4 but cannot move. Next players turn.

You are on square 84. Hit enter to roll the die.
Player 1 on square 84 rolls a 1 and moves to square 85
Player 2 on square 35 rolls a 2 and moves to square 37
Player 3 on square 97 rolls a 3 and moves to square 100
Player 3 wins!
```


[User]
In this task, the goal is to create a SOAP client which accesses functions defined at **http://example.com/soap/wsdl**, and calls the functions **soapFunc( )** and **anotherSoapFunc( )**.

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.

[Assistant]
(formerly Perl 6)

```
# Reference:
# https://github.com/retupmoca/P6-SOAP
# http://wiki.dreamfactory.com/DreamFactory/Tutorials/Temp_Conversion_SOAP_API

use v6;
use SOAP::Client;

my $request = SOAP::Client.new('http://www.w3schools.com/xml/tempconvert.asmx?WSDL') or die;

say $request.call('CelsiusToFahrenheit', Celsius => 100 ) or die;

say $request.call('FahrenheitToCelsius', Fahrenheit => 212 ) or die;

```

Output:

```
{CelsiusToFahrenheitResult => [212]}
{FahrenheitToCelsiusResult => [100]}

```


[User]
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.

Catching any exceptions or errors is not required.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.03

Will fail with a connect error if there is not a socket server of some kind available on the specified host and port.

```
my $host = '127.0.0.1';
my $port = 256;

my $client = IO::Socket::INET.new(:$host, :$port);
$client.print( 'hello socket world' );
$client.close;

```


[User]
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.

Sokoban levels are usually stored as a character array where

* *space* is an empty square
* # is a wall
* @ is the player
* $ is a box
* . is a goal
* + is the player on a goal
* \* is a box on a goal

```
#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######

```

Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (**l**eft, **u**p, **r**ight, **d**own) direction and capital LURD represents a push.

Please state if you use some other format for either the input or output, and why.

For more information, see the Sokoban wiki.

[Assistant]
(formerly Perl 6)

**Translation of**: Go

```
sub MAIN() {
    my $level = q:to//;
#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######

    say 'level:';
    print $level;
    say 'solution:';
    say solve($level);
}

class State {
    has Str $.board;
    has Str $.sol;
    has Int $.pos;

    method move(Int $delta --> Str) {
        my $new = $!board;
        if $new.substr($!pos,1) eq '@' {
            substr-rw($new,$!pos,1) = ' ';
        } else {
            substr-rw($new,$!pos,1) = '.';
        }
        my $pos := $!pos + $delta;
        if $new.substr($pos,1) eq ' ' {
            substr-rw($new,$pos,1) = '@';
        } else {
            substr-rw($new,$pos,1) = '+';
        }
        return $new;
    }

    method push(Int $delta --> Str) {
        my $pos := $!pos + $delta;
        my $box := $pos + $delta;
        return '' unless $!board.substr($box,1) eq ' ' | '.';
        my $new = $!board;
        if $new.substr($!pos,1) eq '@' {
            substr-rw($new,$!pos,1) = ' ';
        } else {
            substr-rw($new,$!pos,1) = '.';
        }
        if $new.substr($pos,1) eq '$' {
            substr-rw($new,$pos,1) = '@';
        } else {
            substr-rw($new,$pos,1) = '+';
        }
        if $new.substr($box,1) eq ' ' {
            substr-rw($new,$box,1) = '$';
        } else {
            substr-rw($new,$box,1) = '*';
        }
        return $new;
    }
}

sub solve(Str $start --> Str) {
    my $board = $start;
    my $width = $board.lines[0].chars + 1;
    my @dirs =
        ["u", "U", -$width],
        ["r", "R", 1],
        ["d", "D", $width],
        ["l", "L", -1];

    my %visited = $board => True;

    my $pos = $board.index('@');
    my @open = State.new(:$board, :sol(''), :$pos);
    while @open {
        my $state = @open.shift;
        for @dirs -> [$move, $push, $delta] {
            my $board;
            my $sol;
            my $pos = $state.pos + $delta;
            given $state.board.substr($pos,1) {
                when '$' | '*' {
                    $board = $state.push($delta);
                    next if $board eq "" || %visited{$board};
                    $sol = $state.sol ~ $push;
                    return $sol unless $board ~~ /<[ . + ]>/;
                }
                when ' ' | '.' {
                    $board = $state.move($delta);
                    next if %visited{$board};
                    $sol = $state.sol ~ $move;
                }
                default { next }
            }
            @open.push: State.new: :$board, :$sol, :$pos;
            %visited{$board} = True;
        }
    }
    return "No solution";
}

```

Output:

```
Level:
#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######
Solution:
ulULLulDDurrrddlULrruLLrrUruLLLulD
```