[User]
Task

Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from  a  to  z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.

For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.

During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:

```
set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}

```

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-10-21

```
say my @letters = 'a'..'z';
```

* `'a'..'z'` is a range literal, it constructs an immutable `Range` object.
* Assigning to an `@` variable flattens it into an `Array`.


[User]
Task

Generate a random chess position in FEN format.

The position does not have to be realistic or even balanced,  but it must comply to the following rules:

:   * there is one and only one king of each color  (one black king and one white king);
    * the kings must not be placed on adjacent squares;
    * there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank);
    * including the kings, up to 32 pieces of either color can be placed.
    * There is no requirement for material balance between sides.
    * The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
    * it is white's turn.
    * It's assumed that both sides have lost castling rights and that there is no possibility for   *en passant*   (the FEN should thus end in w - - 0 1).

No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.

[Assistant]
(formerly Perl 6)

```
sub pick-FEN {
    # First we chose how many pieces to place
    my $n = (2..32).pick;

    # Then we pick $n squares
    my @n = (^64).pick($n);

    # We try to find suitable king positions on non-adjacent squares.
    # If we could not find any, we return recursively
    return pick-FEN() unless
    my @kings[2] = first -> [$a, $b] {
        $a !== $b && abs($a div 8 - $b div 8) | abs($a mod 8 - $b mod 8) > 1
    }, (@n X @n);

    # We make a list of pieces we can pick (apart from the kings)
    my @pieces = <p P n N b B r R q Q>;

    # We make a list of two king symbols to pick randomly a black or white king
    my @k = <K k>.pick(*);

    return (gather for ^64 -> $sq {
        if $sq == @kings.any { take @k.shift }
        elsif $sq == @n.any {
            my $row = 7 - $sq div 8;
            take
            $row == 7 ?? @pieces.grep(none('P')).pick !!
            $row == 0 ?? @pieces.grep(none('p')).pick !!
            @pieces.pick;
        }
        else { take 'ø' }
    }).rotor(8)».join».subst(/ø+/,{ .chars }, :g).join('/') ~ ' w - - 0 1';
}

say pick-FEN();

```

Output:

```
q2n1n2/1Qpk3Q/1r3bP1/1b1b4/2pRBR2/4P1bN/2R3K1/N1r2rPB w - - 0 1
```


[User]
Many puzzle games such as the 15 puzzle game need a way to randomize the order of the pieces. One way to do this is to create an array and fill it with random values, with each element's index in that array being its position. Unfortunately, most random number generators can produce the same value more than once, which in this case isn't what we want.

Task

Create a random number generator and have it output the numbers 1 through 20 (inclusive), in a random order. It cannot produce the same value more than once.

Or

Given the output of an existing random number generator that *does* produce repeated output, create a function that constrains the output to numbers 1 through 20 (inclusive), and no number is output more than once. (Technically it stops being "random" at that point, but that's beyond the scope of this task.) Try your best not to make the process take too long at runtime.

For the second version of the task, the random number generator itself need not be implemented; however you must specify its possible range of values before your constraint function is applied. (e.g "Assume the random number generator creates a value from 0 to 255, and values are allowed to repeat")

Related Tasks
:   * 15 Puzzle Solver
    * 16 Puzzle Game
    * Random numbers

[Assistant]
Raku has three distinct "random" functions built in. rand() for when you want some fraction between 0 and 1. roll() when you want to select elements from a collection with replacement (rolls of a die). And pick() for when you want to select some elements from a collection *without* replacement. (pick a card, any card, or two cards or 10 cards...). If you want to select *all* the elements in random order, just pick 'whatever'. Here we'll pick all from 1 to 20, 5 times using the repetition operator.

Pick random elements *without* replacement

```
.put for (1..20).pick(*) xx 5

```

Sample output:

```
20 4 5 7 15 19 2 16 8 6 3 12 14 13 10 18 9 17 1 11
4 5 18 10 13 3 1 11 6 2 19 8 12 7 16 17 14 20 15 9
14 8 15 11 17 4 3 10 18 7 16 13 1 20 12 9 6 5 19 2
7 5 15 11 12 18 17 3 20 6 13 19 14 2 16 10 4 9 8 1
19 12 4 7 3 20 13 17 5 8 6 15 10 18 1 11 2 14 16 9
```

Pick random elements *with* replacement

```
.put for (1..20).roll(20) xx 5

```

Sample output:

```
16 20 15 17 13 4 19 1 3 8 4 12 13 4 4 5 14 17 10 14
12 6 8 8 9 6 2 4 16 8 4 3 14 8 19 20 5 12 7 15
20 4 20 16 14 6 15 15 16 18 5 19 20 3 14 11 2 7 13 12
3 19 11 13 9 4 5 11 2 20 16 17 14 18 12 10 4 1 13 2
17 20 12 17 19 4 20 20 14 8 2 19 2 12 18 14 4 14 10 8
```


[User]
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.

Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.

Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.

Task

* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
* Use it to create a generator of:

:   :   :   * Squares.
            * Cubes.

* Create a new generator that filters all cubes from the generator of squares.
* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.

Note that this task *requires* the use of generators in the calculation of the result.

Also see

* Generator

[Assistant]
(formerly Perl 6)

As with Haskell, generators are disguised as lazy lists in Raku.

```
sub powers($m) { 0..* X** $m }

my @squares = powers(2);
my @cubes   = powers(3);

sub infix:<with-out> (@orig, @veto) {
    gather for @veto -> $veto {
        take @orig.shift while @orig[0] before $veto;
        @orig.shift if @orig[0] eqv $veto;
    }
}

say (@squares with-out @cubes)[20 ..^ 20+10].join(', ');

```

Output:

```
529, 576, 625, 676, 784, 841, 900, 961, 1024, 1089
```


[User]
Task

Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.

If your solution language is statically typed please describe the way your language provides genericity.

If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.

Generic swap is a task which brings together a few separate issues in programming language semantics.

Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.

Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.

Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).

Do your best!

[Assistant]
(formerly Perl 6)

Similar to Perl 5. Raku supports type constraints for variables and subroutines, unlike Perl 5, but the default is still to permit all values.

Alternatively, you can write it like this:

```
($x, $y) .= reverse;
```


[User]
Geohashes are used to represent standard latitude and longitude coordinates as single values in the form of a simple string -- using the digits (0-9) and the letters (B-Z excluding I, L, O). They can vary in length, with more characters in the string representing more precision.

Task

Generate a Geohash with a desired precision from a coordinate represented as an array of two floating point numbers, latitude and longitude. (Ideally double precision).

**Example 1:**
:   print (encodeGeohash (for: [51.433718, -0.214126], withPrecision: 2))
:   // Result: "gc" (all of Ireland, most of England and Wales, small part of Scotland)

**Example 2:**
:   print (encodeGeohash (for: [51.433718, -0.214126], withPrecision: 9))
:   // Result: "gcpue5hp4" (the umpire's chair on Center Court at Wimbledon)

From the Wikipedia page, geohashes can be "useful in database systems where queries on a single index are much easier or faster than multiple-index queries."

Extra credit

Provide a decode function to convert a geohash code back to latitude and longitude, expressed either as ranges or in median +/- deviation format.

Reference

* Wikipedia article - Geohash.

[Assistant]
### Module based

Reference: Used this for verification.

```
#20200615 Raku programming solution

use Geo::Hash;

# task example 1 : Ireland, most of England and Wales, small part of Scotland
say geo-encode(51.433718e0, -0.214126e0, 2);

# task example 2 : the umpire's chair on Center Court at Wimbledon
say geo-encode(51.433718e0, -0.214126e0, 9);

# Lake Raku is an artificial lake in Tallinn, Estonia
# https://goo.gl/maps/MEBXXhiFbN8WMo5z8
say geo-encode(59.358639e0, 24.744778e0, 4);

# Village Raku is a development committee in north-western Nepal
# https://goo.gl/maps/33s7k2h3UrHCg8Tb6
say geo-encode(29.2021188e0, 81.5324561e0, 4);

```

Output:

```
gc
gcpue5hp4
ud99
tv1y

```

### Roll your own

Alternately, a roll-your-own version that will work with any Real coordinate, not just floating point values, and thus can return ridiculous precision.
The geo-decode routine returns the range in which the actual value will be found; converted here to the mid-point with the interval size. Probably better
to specify an odd precision so the error interval ends up the same for both latitude and longitude.

```
my @Geo32 = <0 1 2 3 4 5 6 7 8 9 b c d e f g h j k m n p q r s t u v w x y z>;

sub geo-encode ( Rat(Real) $latitude, Rat(Real) $longitude, Int $precision = 9 ) {
    my @coord = $latitude, $longitude;
    my @range = [-90, 90], [-180, 180];
    my $which = 1;
    my $value = '';
    while $value.chars < $precision * 5 {
        my $mid = @range[$which].sum / 2;
        $value ~= my $upper = +(@coord[$which] > $mid);
        @range[$which][not $upper] = $mid;
        $which = not $which;
    }
    @Geo32[$value.comb(5)».parse-base(2)].join;
}

sub geo-decode ( Str $geo ) {
     my @range = [-90, 90], [-180, 180];
     my $which = 1;
     my %Geo32 = @Geo32.antipairs;
     for %Geo32{$geo.comb}».fmt('%05b').join.comb {
         @range[$which][$_] = @range[$which].sum / 2;
         $which = not $which;
     }
     @range
}

# TESTING

for 51.433718,   -0.214126,  2, # Ireland, most of England and Wales, small part of Scotland
    51.433718,   -0.214126,  9, # the umpire's chair on Center Court at Wimbledon
    51.433718,   -0.214126, 17, # likely an individual molecule of the chair
    57.649110,   10.407440, 11, # Wikipedia test value - Råbjerg Mile in Denmark
    59.358639,   24.744778,  7, # Lake Raku in Estonia
    29.2021188, 81.5324561,  7  # Village Raku in Nepal
  -> $lat, $long, $precision {
     say "$lat, $long, $precision:\ngeo-encoded: ",
     my $enc = geo-encode $lat, $long, $precision;
     say 'geo-decoded: ', geo-decode($enc).map( {-.sum/2 ~ ' ± ' ~
          (abs(.[0]-.[1])/2).Num.fmt('%.3e')} ).join(',  ') ~ "\n";
}

```

```
51.433718, -0.214126, 2:
geo-encoded: gc
geo-decoded: 53.4375 ± 2.813e+00,  -5.625 ± 5.625e+00

51.433718, -0.214126, 9:
geo-encoded: gcpue5hp4
geo-decoded: 51.4337182 ± 2.146e-05,  -0.21412611 ± 2.146e-05

51.433718, -0.214126, 17:
geo-encoded: gcpue5hp4ebnf8unc
geo-decoded: 51.43371800000523 ± 2.046e-11,  -0.21412600000303 ± 2.046e-11

57.64911, 10.40744, 11:
geo-encoded: u4pruydqqvj
geo-decoded: 57.64911063 ± 6.706e-07,  10.407439694 ± 6.706e-07

59.358639, 24.744778, 7:
geo-encoded: ud99ejf
geo-decoded: 59.358444 ± 6.866e-04,  24.744644 ± 6.866e-04

29.2021188, 81.5324561, 7:
geo-encoded: tv1ypk4
geo-decoded: 29.202347 ± 6.866e-04,  81.532974 ± 6.866e-04

```


[User]
**Geometric algebra** is another name for Clifford algebras and it's basically an algebra containing a vector space

V
{\displaystyle {\displaystyle {\mathcal {V}}}}
 and obeying the following axioms:

:   (
    a
    b
    )
    c
    =
    a
    (
    b
    c
    )

    a
    (
    b
    +
    c
    )
    =
    a
    b
    +
    a
    c

    (
    a
    +
    b
    )
    c
    =
    a
    c
    +
    b
    c

    ∀

    x
    ∈

    V
    ,

    x

    2
    ∈

    R
    {\displaystyle {\displaystyle {\begin{array}{c}(ab)c=a(bc)\\a(b+c)=ab+ac\\(a+b)c=ac+bc\\\forall \mathbf {x} \in {\mathcal {V}},\,\mathbf {x} ^{2}\in \mathbb {R} \end{array}}}}

The product operation in such algebra is called the *geometric product*. Elements are called *multivectors*, while multivectors in

V
{\displaystyle {\displaystyle {\mathcal {V}}}}
 are just called *vectors*.

There are a few simple examples of geometric algebras. A trivial one for instance is simply

R
{\displaystyle {\displaystyle \mathbb {R} }}
, where

V
=

R
{\displaystyle {\displaystyle {\mathcal {V}}=\mathbb {R} }}
. The complex numbers also form a geometric algebra, where the vector space is the one-dimensional space of all purely imaginary numbers. Another example is the space of quaternions, where the vector space is the three-dimensional space of all linear combinations of

(
i
,
j
,
k
)
{\displaystyle {\displaystyle (i,j,k)}}
.

The purpose of this task is to implement a geometric algebra with a vector space

V
{\displaystyle {\displaystyle {\mathcal {V}}}}
 of dimension *n* of at least five, but for extra-credit you can implement a version with *n* arbitrary large. Using a dimension five is useful as it is the dimension required for the so-called *conformal model* which will be the subject of a derived task.

To ensure the unicity of the solution (that is, up to some isomorphism), we will also restrict ourselves to the so-called euclidean case, where the square of a non-zero vector is positive:

∀

x
∈

V
,

x
≠
0

⟹

x

2
>
0
{\displaystyle {\displaystyle \forall \mathbf {x} \in {\mathcal {V}},\,\mathbf {x} \neq 0\implies \mathbf {x} ^{2}>0}}
.

You can of course, for extra credit, implement the general case. This would require the definition of a parameter for the *signature* of the metric.

In order to show that your solution uses a vector space of dimension at least five, you will create a function n -> e(n) such that the vectors e(0), e(1), e(2), e(3), e(4) are linearly independent. To do so you will make them orthonormal with the following scalar product:

x
⋅

y
=
(

x

y
+

y

x
)

/
2
{\displaystyle {\displaystyle \mathbf {x} \cdot \mathbf {y} =(\mathbf {x} \mathbf {y} +\mathbf {y} \mathbf {x} )/2}}

The fact that this so-called *inner product* defines a scalar product is a consequence of the fourth axiom. To see it one just needs to notice the relation:

x

y
+

y

x
=
(

x
+

y

)

2
−

x

2
−

y

2
{\displaystyle {\displaystyle \mathbf {x} \mathbf {y} +\mathbf {y} \mathbf {x} =(\mathbf {x} +\mathbf {y} )^{2}-\mathbf {x} ^{2}-\mathbf {y} ^{2}}}

Once you'll have shown that your vector space is at least of dimension five, you will show that the axioms are satisfied. For this purpose you will pick three random multivectors *a*, *b* and *c*, along with a random vector

x
{\displaystyle {\displaystyle \mathbf {x} }}
.

Producing a random vector is easy. Just use a pseudo-random generation function rand and create a vector:

r
a
n
d
o
m
V
e
c
t
o
r
(
)
=

∑

i
=
0

4

r
a
n
d
(
)

e

i
{\displaystyle {\displaystyle \mathrm {randomVector} ()=\sum \_{i=0}^{4}\mathrm {rand} ()\mathbf {e} \_{i}}}

Producing a random multivector is slightly more involved. It is known that when the dimension of

V
{\displaystyle {\displaystyle {\mathcal {V}}}}
 is *n*, then the dimension of the algebra (seen as a vector space with its natural scalar multiplication) is 2n. This means that for n=5 there is a basis of 25 = 32 basis multivectors from which any multivector can be written as a linear combination. Create such a basis

m

0
,

m

1
,
…
,

m

31
{\displaystyle {\displaystyle m\_{0},m\_{1},\ldots ,m\_{31}}}
 along with a function producting a random multivector:

r
a
n
d
o
m
M
u
l
t
i
v
e
c
t
o
r
(
)
=

∑

i
=
0

31

r
a
n
d
(
)

m

i
{\displaystyle {\displaystyle \mathrm {randomMultivector} ()=\sum \_{i=0}^{31}\mathrm {rand} ()m\_{i}}}

To summarize, to solve this task you will:

* define the inner product of two vectors :

  x
  ⋅

  y
  =
  (

  x
  y
  +

  y
  x
  )

  /
  2
  {\displaystyle {\displaystyle \mathbf {x} \cdot \mathbf {y} =(\mathbf {xy} +\mathbf {yx} )/2}}
  .
* define the function e
* verify the orthonormality

  e

  i
  ⋅

  e

  j
  =

  δ

  i
  ,
  j
  {\displaystyle {\displaystyle \mathbf {e} \_{i}\cdot \mathbf {e} \_{j}=\delta \_{i,j}}}
   for i, j in

  {
  0
  ,
  1
  ,
  2
  ,
  3
  ,
  4
  }
  {\displaystyle {\displaystyle \{0,1,2,3,4\}}}
  .
* create a function returning a random multivector
* create a function returning a random vector
* verify the axioms for three rarndom multivectors *a*, *b*, *c* and a random vector **x**.

Optionally, you will repeat the last step a large number of times, in order to increase confidence in the result.

[Assistant]
(formerly Perl 6)

Here we write a simplified version of the Clifford module. It is very general as it is of infinite dimension and also contains an anti-euclidean basis @ē in addition to the euclidean basis @e.

```
class MultiVector is Mix {
  subset Vector of ::?CLASS is export where *.grades.all == 1;

  method narrow { self.keys.any > 0 ?? self !!  (self{0} // 0) }
  method grades { self.keys.map: *.base(2).comb.sum }

  multi method new(Real $x) returns ::?CLASS { self.new-from-pairs: 0 => $x }
  multi method new(Str $ where /^^e(\d+)$$/) { self.new-from-pairs: (1 +< (2*$0)) => 1 }

  our @e is export = map { ::?CLASS.new: "e$_" }, ^Inf;

  my sub order(UInt:D $i is copy, UInt:D $j) {
    (state %){$i}{$j} //= do {
      my $n = 0;
      repeat {
	$i +>= 1;
	$n += [+] ($i +& $j).polymod(2 xx *);
      } until $i == 0;
      $n +& 1 ?? -1 !! 1;
    }
  }

  sub infix:<·>(Vector $x, Vector $y) returns Real is export { (($x*$y + $y*$x)/2){0} }

  multi infix:<+>(::?CLASS $A, ::?CLASS $B) returns ::?CLASS is export {
    return ::?CLASS.new-from-pairs: |$A.pairs, |$B.pairs;
  }
  multi infix:<+>(Real $s, ::?CLASS $B) returns ::?CLASS is export {
    samewith $B.new($s), $B
  }
  multi infix:<+>(::?CLASS $A, Real $s) returns ::?CLASS is export {
    samewith $s, $A
  }

  multi infix:<*>(::?CLASS $,  0) is export { 0  }
  multi infix:<*>(::?CLASS $A, 1) returns ::?CLASS is export { $A }
  multi infix:<*>(::?CLASS $A, Real $s) returns ::?CLASS is export {
    ::?CLASS.new-from-pairs: $A.pairs.map({Pair.new: .key, $s*.value})
  }
  multi infix:<*>(::?CLASS $A, ::?CLASS $B) returns ::?CLASS is export {
    ::?CLASS.new-from-pairs: gather
      for $A.pairs -> $a {
	for $B.pairs -> $b {
	  take ($a.key +^ $b.key) => [*]
	    $a.value, $b.value,
	    order($a.key, $b.key),
	    |grep +*, (
		|(1, -1) xx * Z*
		($a.key +& $b.key).polymod(2 xx *)
	    )
	}
      }
  }
  multi infix:<**>(::?CLASS $ , 0) returns ::?CLASS is export { ::?CLASS.new: (0 => 1).Mix }
  multi infix:<**>(::?CLASS $A, 1) returns ::?CLASS is export { $A }
  multi infix:<**>(::?CLASS $A, 2) returns ::?CLASS is export { $A * $A }
  multi infix:<**>(::?CLASS $A, UInt $n where $n %% 2) returns ::?CLASS is export { ($A ** ($n div 2)) ** 2 }
  multi infix:<**>(::?CLASS $A, UInt $n) returns ::?CLASS is export { $A * ($A ** ($n div 2)) ** 2 }

  multi infix:<*>(Real $s, ::?CLASS $A) returns ::?CLASS is export { $A * $s }
  multi infix:</>(::?CLASS $A, Real $s) returns ::?CLASS is export { $A * (1/$s) }
  multi prefix:<->(::?CLASS $A) returns ::?CLASS is export { return -1 * $A }
  multi infix:<->(::?CLASS $A, ::?CLASS $B) returns ::?CLASS is export { $A + -$B }
  multi infix:<->(::?CLASS $A, Real $s) returns ::?CLASS is export { $A + -$s }
  multi infix:<->(Real $s, ::?CLASS $A) returns ::?CLASS is export { $s + -$A }

  multi infix:<==>(::?CLASS $A, 0) returns Bool is export { $A.elems == 0 }
  multi infix:<==>(::?CLASS $A, ::?CLASS $B) returns Bool is export { samewith $A - $B, 0 }
  multi infix:<==>(Real $x, ::?CLASS $A) returns Bool is export { samewith $A, $x }
  multi infix:<==>(::?CLASS $A, Real $x) returns Bool is export { samewith $A, $A.new($x); }

  sub random is export {
      [+] map {
	  ::?CLASS.new-from-pairs: $_ => rand.round(.01)
      }, ^32;
  }
}

#########################################
##  Test code to verify the solution:  ##
#########################################

import MultiVector;
use Test;

constant N = 10;
plan 5;

subtest "Orthonormality", {
  for ^N X ^N -> ($i, $j) {
    my $s = $i == $j ?? 1 !! 0;
    ok @e[$i]·@e[$j] == $s, "e$i·e$j = $s";
  }
}

my ($a, $b, $c) = random() xx 3;

ok ($a*$b)*$c == $a*($b*$c), 'associativity';
ok $a*($b + $c) == $a*$b + $a*$c, 'left distributivity';
ok ($a + $b)*$c == $a*$c + $b*$c, 'right distributivity';
my @coeff = (.5 - rand) xx 5;
my $v = [+] @coeff Z* @e[^5];
ok ($v**2).narrow ~~ Real, 'contraction';

```


[User]
Task

Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).

Related task

* Execute a system command

[Assistant]
(formerly Perl 6)

If you don't want to execute it in shell (and you probably don't), then use this:

```
say run($command, $arg1, $arg2, :out).out.slurp;

```

Unfortunately, it is very long to type, but that is the only way to pass your variables as arguments safely.

You might be tempted to start using shell when you have to pipe something, but even in that case there is no need to do so. See this code:

```
my $p1 = run 'echo', 'Hello, world', :out;
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.slurp-rest;

```

See docs for more info.

If you really want to run something in shell and you understand potential security problems, then you can use `qx//` (interpolates environment variables) or `qqx//` (interpolates normally). See the docs for more info.

```
say qx[dir]

```

Output:

```
Find_URI_in_text.p6  History_variables.p6  K-d_tree.pl
Fractran.pl	     History_variables.pl  XML_Input.p6
```


[User]
Task

Write a program (function) to get the number of decimal places in a given number.

Examples
:   * for num = 12.345         decimals = 3,     and
    * for num = 12.3450       decimals = 4

(Note that the reference implementation – in the **Ring** language – shows a function over a given **number** rather than a given numeric string, and that the sample values shown above are not enclosed in quotes).

[Assistant]
**Works with**: Rakudo version 2020.07

Raku does not specifically have a "decimal" number type, however we can
easily determine the fractional precision of a rational number. It is somewhat
touchy-feely for floating point numbers; (what is the fractional precision for
2.45e-12?), it's pretty pointless for Integers; (zero, aalllways zero...), but
Rats (rationals) are doable. Note that these are (mostly) actual numerics, not
numeric strings. The exception is '12.3450'. That is a numeric string since
actual numerics automatically truncate non-significant trailing zeros. If you
want to retain them, you need to pass the value as a string. (As below.)

```
use Rat::Precise;

printf "Fractional precision: %-2s || Number: %s\n", (.split('.')[1] // '').chars, $_
    for 9, 12.345, '12.3450', 0.1234567890987654321, (1.5**63).precise;

```

Output:

```
Fractional precision: 0  || Number: 9
Fractional precision: 3  || Number: 12.345
Fractional precision: 4  || Number: 12.3450
Fractional precision: 19 || Number: 0.1234567890987654321
Fractional precision: 63 || Number: 124093581919.648947697827373650380188008224280338254175148904323577880859375
```


[User]
Definition

A **Giuga number** is a composite number **n** which is such that each of its distinct prime factors
**f** divide (n/f - 1) exactly.

All known Giuga numbers are even though it is not known for certain that there are no odd examples.

Example

30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:

* 30/2 - 1 = 14 is divisible by 2
* 30/3 - 1 = 9 is divisible by 3
* 30/5 - 1 = 5 is divisible by 5

Task

Determine and show here the first four Giuga numbers.

Stretch

Determine the fifth Giuga number and any more you have the patience for.

References

* Wikipedia: Giuga number
* OEIS:A007850 - Giuga numbers

[Assistant]
```
my @primes = (3..60).grep: &is-prime;

print 'First four Giuga numbers: ';

put sort flat (2..4).map: -> $c {
    @primes.combinations($c).map: {
        my $n = [×] 2,|$_;
        $n if all .map: { ($n / $_ - 1) %% $_ };
    }
}

```

Output:

```
First 4 Giuga numbers: 30 858 1722 66198
```


[User]
Task

Replace every occurring instance of a piece of text in a group of text files with another one.

For this task we want to replace the text   "**Goodbye London!**"   with   "**Hello New York!**"   for a list of files.

[Assistant]
(formerly Perl 6)

Current Raku implementations do not yet support the -i flag for editing files in place, so we roll our own (rather unsafe) version:

```
slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)
    for <a.txt b.txt c.txt>;

```


[User]
Write a program to let the user play Go Fish against a computer opponent. Use the following rules:

* Each player is dealt nine cards to start with.
* On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.
  + If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.
  + If the opponent has no cards of the named rank, the requester draws a card and ends their turn.
* A *book* is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.
* If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.
* The game ends when every book is complete. The player with the most books wins.

The game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.

You may want to use code from Playing Cards.

Related tasks:

* Playing cards
* Card shuffles
* Deal cards\_for\_FreeCell
* War Card\_Game
* Poker hand\_analyser

[Assistant]
(formerly Perl 6)
See Go Fish/Raku


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

**Goldbach's comet** is the name given to a plot of the function **g(E)**, the so-called **Goldbach function**.

The Goldbach function is studied in relation to Goldbach's conjecture. The function **g(E)** is defined for all *even* integers **E>2** to be the number of different ways in which E can be expressed as the sum of two primes.

Examples

* G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)
* G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)

Task

* Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)
* Find and display the value of G(1000000)

Stretch

* Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet

See also

* Wikipedia: Goldbach's conjecture * OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes

[Assistant]
For the stretch, actually generates a plot, doesn't just calculate values to be plotted by a third party application. Deviates slightly from the stretch goal, plots the first two thousand defined values rather than the values up to two thousand that happen to be defined. (More closely matches the wikipedia example image.)

```
sub G (Int $n) { +(2..$n/2).grep: { .is-prime && ($n - $_).is-prime } }

# Task
put "The first 100 G values:\n", (^100).map({ G 2 × $_ + 4 }).batch(10)».fmt("%2d").join: "\n";

put "\nG 1_000_000 = ", G 1_000_000;

# Stretch
use SVG;
use SVG::Plot;

my @x = map 2 × * + 4, ^2000;
my @y = @x.map: &G;

'Goldbachs-Comet-Raku.svg'.IO.spurt: SVG.serialize: SVG::Plot.new(
    width       => 1000,
    height      => 500,
    background  => 'white',
    title       => "Goldbach's Comet",
    x           => @x,
    values      => [@y,],
).plot: :points;

```

Output:

```
The first 100 G values:
 1  1  1  2  1  2  2  2  2  3
 3  3  2  3  2  4  4  2  3  4
 3  4  5  4  3  5  3  4  6  3
 5  6  2  5  6  5  5  7  4  5
 8  5  4  9  4  5  7  3  6  8
 5  6  8  6  7 10  6  6 12  4
 5 10  3  7  9  6  5  8  7  8
11  6  5 12  4  8 11  5  8 10
 5  6 13  9  6 11  7  7 14  6
 8 13  5  8 11  7  9 13  8  9

G 1_000_000 = 5402
```

**Stretch goal:** (offsite SVG image) Goldbachs-Comet-Raku.svg


[User]
The golden ratio can be defined as the continued fraction

:   ϕ
    =
    1
    +

    1

    1
    +

    1

    1
    +

    1

    1
    +
    ⋯
    {\displaystyle {\displaystyle \phi =1+{1 \over {1+{1 \over {1+{1 \over {1+\cdots }}}}}}}}

Thus

ϕ
=
1
+

1

/
ϕ
{\displaystyle {\displaystyle \phi =1+{1/\phi }}}
. Multiplying both sides by

ϕ
{\displaystyle {\displaystyle \phi }}
 and solving the resulting quadratic equation for its positive solution, one gets

ϕ
=
(
1
+

5
)

/
2
≈
1.61803398875
{\displaystyle {\displaystyle \phi =(1+{\sqrt {5}})/2\approx 1.61803398875}}
.

The golden ratio has the slowest convergence of any continued fraction, as one might guess by noting that the denominators are made of the smallest positive integer. This task treats the problem of convergence in a somewhat backwards fashion: we are going to iterate the recursion

ϕ

n
+
1
=
1
+

1

/

ϕ

n
{\displaystyle {\displaystyle \phi \_{n+1}=1+{1/\phi \_{n}}}}
,

ϕ

0
=
1
{\displaystyle {\displaystyle \phi \_{0}=1}}
, and see how long it takes to get an answer.

### Task

Iterate

ϕ

n
+
1
=
1
+

1

/

ϕ

n
{\displaystyle {\displaystyle \phi \_{n+1}=1+{1/\phi \_{n}}}}
,

ϕ

0
=
1
{\displaystyle {\displaystyle \phi \_{0}=1}}
, until

|

ϕ

n
+
1
−

ϕ

n

|
≤
1
×

10

−
5
{\displaystyle {\displaystyle |\phi \_{n+1}-\phi \_{n}|\leq 1\times 10^{-5}}}
. Report the final value of

ϕ

n
+
1
{\displaystyle {\displaystyle \phi \_{n+1}}}
, the number of iterations required, and the error with respect to

(
1
+

5
)

/
2
{\displaystyle {\displaystyle (1+{\sqrt {5}})/2}}
.

### See also

* Metallic ratios

[Assistant]
```
constant phi = 1.FatRat, 1 + 1/* ... { abs($^a-$^b)≤1e-5 };

say "It took {phi.elems} iterations to reach {phi.tail}";
say "The error is {{ ($^a - $^b)/$^b }(phi.tail, (1+sqrt(5))/2)}"

```

Output:

```
It took 15 iterations to reach 1.618033
The error is -7.427932029059675e-07
```


[User]
Background

Goodstein sequences are sequences defined for a given counting number n by applying increasing bases to a representation of n after n has been
used to construct a *hereditary representation* of that number, originally in base 2.

Start by defining the hereditary base-b representation of a number n. Write n as a sum of powers of b, staring with b = 2. For example, with
n = 29, write 31 = 16 + 8 + 4 + 1. Now we write each exponent as a sum of powers of n, so as 2^4 + 2^3 + 2^1 + 2^0.

Continue by re-writing all of the current term's exponents that are still > b as a sum of terms that are <= b, using a sum of powers of b: so,
n = 16 + 8 + 4 + 1 = 2^4 + 2^3 + 2 + 1 = 2^(2^2) + 2^(2 + 1) + 2 + 1.

If we consider this representation as a representation of a calculation with b = 2, we have the hereditary representation
b^(b^b) + b^(b + 1) + b + 1.

Other integers and bases are done similarly. Note that an exponential term can be repeated up to (b - 1) times, so that, for example,
if b = 5, 513 = b^3 + b^3 + b^3 + b^3 + b + b + 3 = 4 \* b^3 + 2 \* b + 3.

The Goodstein sequence for n, G(n) is then defined as follows:

The first term, considered the zeroeth term or G(n)(0), is always 0. The second term G(n)(1) is always n. For further terms,
the m-th term G(n)(m) is defined by the following procedure:

```
   1. Write G(n)(m - 1) as a hereditary representation with base (m - 1).
   2. Calculate the results of using the hereditary representation found in step 1 using base m rather than (m - 1)
   3. Subtract 1 from the result calculated in step 2.

```

Task

* Create a function to calculate the Goodstein sequence for a given integer.

* Use this to show the first 10 values of Goodstein(n) for the numbers from 0 through 7.

* Find the nth term (counting from 0) of Goodstein(n) for n from 0 through 10.

Stretch task

* Find the nth term (counting from 0) of Goodstein(n) for n = 11 through 16.

See also

:   * Wikipedia entry for Goodstein's theorem
    * OEIS Goodstein numbers such that a(n) = G\_n(n), where G is the Goodstein function
    * [| "Googology site article " ]

[Assistant]
**Translation of**: Phix

```
# 20240219 Raku programming solution

sub bump($n is copy, $b) {
   loop ( my ($res, $i) = 0, 0; $n.Bool or return $res; $i++,$n div= $b) {
      if my $d = $n % $b { $res += $d * ($b+1) ** bump($i,$b) }
   }
}

sub goodstein($n, $maxterms = 10) {
   my @res = $n;
   while @res.elems < $maxterms && @res[*-1] != 0 {
      @res.push(bump(@res[*-1], (@res.elems + 1)) - 1)
   }
   return @res
}

say "Goodstein(n) sequence (first 10) for values of n from 0 through 7:";
for 0..7 -> $i { say "Goodstein of $i: ", goodstein($i) }

my $max = 16;
say "\nThe Nth term of Goodstein(N) sequence counting from 0, for values of N from 0 through $max :";
for 0..$max -> $i { say "Term $i of Goodstein($i): {goodstein($i, $i+1)[*-1]}" }

```

You may Attempt This Online!


[User]
**Gosper's Hack** is an efficient method of computing the next higher integer with the same number of set bits (Hamming weight). It was invented by Bill Gosper. The algorithm is widely used in combinatorics for enumerating combinations.

Task

Write a function or procedure to compute the next higher integer with the same number of set bits as a given positive integer, using Gosper’s Hack.

Show the result of applying it ten times to each of the numbers 1, 3, 7, and 15.

Reference

* Gosper's Hack explained

[Assistant]
```
sub gosper ($x) {
    my $c = $x +& -$x;
    my $r = $x + $c;
    ((($r +^ $x) +> 2) / $c) +| $r
}

for 1, 3, 7, 15 -> $start {
    my @g = $start, { gosper $_ } … *;
    say @g[^11].fmt('%8d');
    say @g[^11].fmt('%08b');
    say '';
}

```

Output:

```
       1        2        4        8       16       32       64      128      256      512     1024
00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 100000000 1000000000 10000000000

       3        5        6        9       10       12       17       18       20       24       33
00000011 00000101 00000110 00001001 00001010 00001100 00010001 00010010 00010100 00011000 00100001

       7       11       13       14       19       21       22       25       26       28       35
00000111 00001011 00001101 00001110 00010011 00010101 00010110 00011001 00011010 00011100 00100011

      15       23       27       29       30       39       43       45       46       51       53
00001111 00010111 00011011 00011101 00011110 00100111 00101011 00101101 00101110 00110011 00110101

```


[User]
Definition

In programming, a gotcha is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome.

Task

Give an example or examples of common gotchas in your programming language and what, if anything, can be done to defend against it or them without using special tools.

[Assistant]
Raku embraces the philosophy of DWIM or "Do What I Mean". A DWIMmy
language tends to avoid lots of boilerplate code, and accept a certain amount of
imprecision to return the result that, for the vast majority of the time, is
what the user intended.

For example, a numeric string may be treated as either a numeric value or a
string literal, without needing to explicitly coerce it to one or the other.
This makes for easy translation of ideas into code, and is generally a good
thing. HOWEVER, it doesn't always work out. Sometimes it leads to unexpected
behavior, commonly referred to as WAT.

It is something of a running joke in the Raku community that "For every DWIM,
there is an equal and opposite WAT".

Larry Wall, the author and designer of Perl and
lead designer of Raku, coined a term to describe this DWIM / WAT
continuum. The Waterbed Theory of Computational Complexity.

The Waterbed theory is the observation that complicated systems contain a minimum
amount of complexity, and that attempting to "push down" the complexity of such
a system in one place will invariably cause complexity to "pop up" elsewhere.

Much like how in a waterbed mattress, it is possible to push down the mattress in one
place, but the displaced water will always cause the mattress to rise elsewhere,
because water does not compress. It is impossible to push down the waterbed
everywhere at once.

There is a whole chapter in the Raku documentation about
"Traps to Avoid" when beginning in Raku,
most of which, at least partially are due to WATs arising from DWIMmy behavior
someplace else.

Expanding on the numeric string example cited above; numeric values and numeric
strings may be used almost interchangeably in most cases.

```
say 123 ~ 456; # join two integers together
say "12" + "5.7"; # add two numeric strings together
say .sqrt for <4 6 8>; # take the square root of several allomorphic numerics

```

```
123456
17.7
2
2.449489742783178
2.8284271247461903
```

You can run into problems though with certain constructs that are more strict about
object typing.

A Bag is a "counting" construct. It takes a collection and counts how many of
each object are within. Works great for strings.

```
say my $bag = <a b a c a b d>.Bag;
say $bag{'a'}; # a count?
say $bag< a >; # another way

```

```
Bag(a(3) b(2) c d)
3
3
```

But numerics can present unobvious problems.

```
say my $bag = (1, '1', '1', <1 1 1>).Bag;
say $bag{ 1 }; # how many 1s?
say $bag{'1'}; # wait, how many?
say $bag< 1 >; # WAT
dd $bag; # The different numeric types LOOK the same, but are different types behind the scenes

```

```
Bag(1 1(2) 1(3))
1
2
3
Bag $bag = (1=>1,"1"=>2,IntStr.new(1, "1")=>3).Bag
```

The different '1's are distinctive to the type system even if they visually look
identical when printing them to the console. They all have a value of 1 but are
respectively and Int, a String, and an IntStr allomorph. Many of the "collective"
objects have this property (Bags, Sets, Maps, etc.) This behavior is correct
but can be very jarring when you are used to being able to use numeric strings
and numeric values nearly interchangeably.

Another such DWIMmy construct, which can trip up even experienced Raku programmers is
The Single Argument Rule.

Single argument is a special exception to parameterization rules causing an iterable
object to be be automatically flattened when passed to an iterator if only a single
object is passed.

E.G. Say we have two small list objects; `(1,2,3)` and `(4,5,6)`,
and we want to print the contents to the console.

```
.say for (1,2,3), (4,5,6);

```

```
(1,2,3)
(4,5,6)
```

However, if we only pass a single list to the iterator (`for`), it will
flatten the object due to the single argument rule.

```
.say for (1,2,3);

```

```
1
2
3
```

If we want the multiple object non-flattening behavior, we need to "fake it out"
by adding a trailing comma to signal to the compiler that this should be treated
like multiple object parameters even if there is only one. (Note the trailing comma after the list.)

```
.say for (1,2,3),;

```

```
(1,2,3)
```

Conversely, if we want the flattening behavior when passing multiple objects, we need to manually, explicitly flatten the objects.

```
.say for flat (1,2,3), (4,5,6);

```

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

Single argument mostly arose in Raku to make it act more like Perl 5, for which
it was originally conceived of as a replacement. Perl 5 flattens collective
object parameters by default, and the original non-flattening behavior was
*extremely* confusing to early Perl / Raku crossover programmers. Larry Wall
came up with single argument to reduce confusion and increase DWIMiness, and it
has overall, but it still leads to the occasional WAT when programmers first bump up against it.


[User]
Gradient descent (also known as steepest descent) is a first-order iterative optimization algorithm for finding the minimum of a function which is described in this Wikipedia article.

Task

Use this algorithm to search for minimum values of the bi-variate function:

```
  f(x, y) = (x - 1)(x - 1)e^(-y^2) + y(y+2)e^(-2x^2)

```

around x = 0.1 and y = -1.

This book excerpt shows sample C# code for solving this task.

[Assistant]
(formerly Perl 6)

**Translation of**: Go

```
# 20200904 Updated Raku programming solution

sub steepestDescent(@x, $alpha is copy, $h) {

   my $g0 = g |@x ; # Initial estimate of result.

   my @fi = gradG |@x ; #  Calculate initial gradient

   my $b = $alpha / my $delG = sqrt ( sum @fi»² ) ;  # Calculate initial norm.

   while ( $delG > $h ) {   # Iterate until value is <= tolerance.

      @x «-»= $b «*« @fi; #  Calculate next value.

      @fi = gradG |@x ; # Calculate next gradient and next value

      $b = $alpha / ($delG = sqrt( sum @fi»² ));  # Calculate next norm.

      my $g1 = g |@x ;

      $g1 > $g0 ?? ( $alpha /= 2 ) !! ( $g0 = $g1 )   # Adjust parameter.
   }
}

sub gradG(\x,\y) { # gives a rough calculation of gradient g(x).
   2*(x-1)*exp(-y²) - 4*x*exp(-2*x²)*y*(y+2) , -2*(x-1)²*y*exp(-y²) + exp(-2*x²)*(2*y+2)
}

# Function for which minimum is to be found.
sub g(\x,\y) { (x-1)² * exp(-y²) + y*(y+2) * exp(-2*x²) }

my $tolerance = 0.0000006 ; my $alpha = 0.1;

my @x = 0.1, -1; # Initial guess of location of minimum.

steepestDescent(@x, $alpha, $tolerance);

say "Testing steepest descent method:";
say "The minimum is at x[0] = ", @x[0], ", x[1] = ", @x[1];

```

Output:

```
Testing steepest descent method:
The minimum is at x[0] = 0.10762682432947938, x[1] = -1.2232596548816097

```


[User]
A Graph is a collection of nodes
(or vertices), connected by edges (or not).
Nodes directly connected by edges are called neighbours.

In our representation of graphs, nodes are numbered and edges are represented
by the two node numbers connected by the edge separated by a dash.
Edges define the nodes being connected. Only unconnected nodes *need* a separate
description.

For example,

```
0-1 1-2 2-0 3
```

Describes the following graph. Note that node 3 has no neighbours

Example graph

```
+---+
| 3 |
+---+

  +-------------------+
  |                   |
+---+     +---+     +---+
| 0 | --- | 1 | --- | 2 |
+---+     +---+     +---+

```

A useful internal datastructure for a graph and for later graph algorithms is
as a mapping between each node and the set/list of its neighbours.

In the above example:

```
0 maps-to 1 and 2
1 maps to 2 and 0
2 maps-to 1 and 0
3 maps-to <nothing>
```

Graph colouring task

Colour the vertices of a given graph so that no edge is between verticies of
the same colour.

* Integers may be used to denote different colours.
* Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is **not** a requirement).
* Show for each edge, the colours assigned on each vertex.
* Show the total number of nodes, edges, and colours used for each graph.

Use the following graphs

Ex1

```
       0-1 1-2 2-0 3

```

```
+---+
| 3 |
+---+

  +-------------------+
  |                   |
+---+     +---+     +---+
| 0 | --- | 1 | --- | 2 |
+---+     +---+     +---+

```

Ex2

The wp articles left-side graph

```
   1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7

```

```

  +----------------------------------+
  |                                  |
  |                      +---+       |
  |    +-----------------| 3 | ------+----+
  |    |                 +---+       |    |
  |    |                   |         |    |
  |    |                   |         |    |
  |    |                   |         |    |
  |  +---+     +---+     +---+     +---+  |
  |  | 8 | --- | 1 | --- | 6 | --- | 4 |  |
  |  +---+     +---+     +---+     +---+  |
  |    |         |                   |    |
  |    |         |                   |    |
  |    |         |                   |    |
  |    |       +---+     +---+     +---+  |
  +----+------ | 7 | --- | 2 | --- | 5 | -+
       |       +---+     +---+     +---+
       |                   |
       +-------------------+

```

Ex3

The wp articles right-side graph which is the same graph as Ex2, but with
different node orderings and namings.

```
   1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6

```

```

  +----------------------------------+
  |                                  |
  |                      +---+       |
  |    +-----------------| 5 | ------+----+
  |    |                 +---+       |    |
  |    |                   |         |    |
  |    |                   |         |    |
  |    |                   |         |    |
  |  +---+     +---+     +---+     +---+  |
  |  | 8 | --- | 1 | --- | 4 | --- | 7 |  |
  |  +---+     +---+     +---+     +---+  |
  |    |         |                   |    |
  |    |         |                   |    |
  |    |         |                   |    |
  |    |       +---+     +---+     +---+  |
  +----+------ | 6 | --- | 3 | --- | 2 | -+
       |       +---+     +---+     +---+
       |                   |
       +-------------------+

```

Ex4

This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.
This might alter the node order used in the greedy algorithm leading to differing numbers of colours.

```
   1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7

```

```

                      +-------------------------------------------------+
                      |                                                 |
                      |                                                 |
  +-------------------+---------+                                       |
  |                   |         |                                       |
+---+     +---+     +---+     +---+     +---+     +---+     +---+     +---+
| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |
+---+     +---+     +---+     +---+     +---+     +---+     +---+     +---+
  |         |                             |         |         |         |
  +---------+-----------------------------+---------+         |         |
            |                             |                   |         |
            |                             |                   |         |
            +-----------------------------+-------------------+         |
                                          |                             |
                                          |                             |
                                          +-----------------------------+

```

References

* Greedy coloring Wikipedia.
* Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.

[Assistant]
(formerly Perl 6)

```
sub GraphNodeColor(@RAW) {
   my %OneMany = my %NodeColor;
   for @RAW { %OneMany{$_[0]}.push: $_[1] ; %OneMany{$_[1]}.push: $_[0] }
   my @ColorPool = "0", "1" … ^+%OneMany.elems; # as string
   my %NodePool  = %OneMany.BagHash; # this DWIM is nice
   if %OneMany<NaN>:exists { %NodePool{$_}:delete for %OneMany<NaN>, NaN } # pending
   while %NodePool.Bool {
      my $color = @ColorPool.shift;
      my %TempPool = %NodePool;
      while (my \n = %TempPool.keys.sort.first) {
         %NodeColor{n} = $color;
         %TempPool{n}:delete;
         %TempPool{$_}:delete for @(%OneMany{n}) ; # skip neighbors as well
         %NodePool{n}:delete;
      }
   }
   if %OneMany<NaN>:exists { # islanders use an existing color
      %NodeColor{$_} = %NodeColor.values.sort.first for @(%OneMany<NaN>)
   }
   return %NodeColor
}

my \DATA = [
   [<0 1>,<1 2>,<2 0>,<3 NaN>,<4 NaN>,<5 NaN>],
   [<1 6>,<1 7>,<1 8>,<2 5>,<2 7>,<2 8>,<3 5>,<3 6>,<3 8>,<4 5>,<4 6>,<4 7>],
   [<1 4>,<1 6>,<1 8>,<3 2>,<3 6>,<3 8>,<5 2>,<5 4>,<5 8>,<7 2>,<7 4>,<7 6>],
   [<1 6>,<7 1>,<8 1>,<5 2>,<2 7>,<2 8>,<3 5>,<6 3>,<3 8>,<4 5>,<4 6>,<4 7>],
];

for DATA {
   say "DATA   : ", $_;
   say "Result : ";
   my %out = GraphNodeColor $_;
   say "$_[0]-$_[1]:\t Color %out{$_[0]} ",$_[1].isNaN??''!!%out{$_[1]} for @$_;
   say "Nodes  : ", %out.keys.elems;
   say "Edges  : ", $_.elems;
   say "Colors : ", %out.values.Set.elems;
}

```

Output:

```
DATA   : [(0 1) (1 2) (2 0) (3 NaN) (4 NaN) (5 NaN)]
Result :
0-1:     Color 0 1
1-2:     Color 1 2
2-0:     Color 2 0
3-NaN:   Color 0
4-NaN:   Color 0
5-NaN:   Color 0
Nodes  : 6
Edges  : 6
Colors : 3
DATA   : [(1 6) (1 7) (1 8) (2 5) (2 7) (2 8) (3 5) (3 6) (3 8) (4 5) (4 6) (4 7)]
Result :
1-6:     Color 0 1
1-7:     Color 0 1
1-8:     Color 0 1
2-5:     Color 0 1
2-7:     Color 0 1
2-8:     Color 0 1
3-5:     Color 0 1
3-6:     Color 0 1
3-8:     Color 0 1
4-5:     Color 0 1
4-6:     Color 0 1
4-7:     Color 0 1
Nodes  : 8
Edges  : 12
Colors : 2
DATA   : [(1 4) (1 6) (1 8) (3 2) (3 6) (3 8) (5 2) (5 4) (5 8) (7 2) (7 4) (7 6)]
Result :
1-4:     Color 0 1
1-6:     Color 0 2
1-8:     Color 0 3
3-2:     Color 1 0
3-6:     Color 1 2
3-8:     Color 1 3
5-2:     Color 2 0
5-4:     Color 2 1
5-8:     Color 2 3
7-2:     Color 3 0
7-4:     Color 3 1
7-6:     Color 3 2
Nodes  : 8
Edges  : 12
Colors : 4
DATA   : [(1 6) (7 1) (8 1) (5 2) (2 7) (2 8) (3 5) (6 3) (3 8) (4 5) (4 6) (4 7)]
Result :
1-6:     Color 0 1
7-1:     Color 1 0
8-1:     Color 1 0
5-2:     Color 1 0
2-7:     Color 0 1
2-8:     Color 0 1
3-5:     Color 0 1
6-3:     Color 1 0
3-8:     Color 0 1
4-5:     Color 0 1
4-6:     Color 0 1
4-7:     Color 0 1
Nodes  : 8
Edges  : 12
Colors : 2
```


[User]
Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps in order from left to right or top to bottom.

Create functions to encode a number to and decode a number from Gray code.

Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).

There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."

Encoding (MSB is bit 0, b is binary, g is Gray code):

```
if b[i-1] = 1
   g[i] = not b[i]
else
   g[i] = b[i]
```

Or:

```
g = b xor (b logically right shifted 1 time)
```

Decoding (MSB is bit 0, b is binary, g is Gray code):

```
b[0] = g[0]

for other bits:
b[i] = g[i] xor b[i-1]
```

Reference

* Converting Between Gray and Binary Codes. It includes step-by-step animations.

[Assistant]
(formerly Perl 6)

```
sub gray_encode ( Int $n --> Int ) {
    return $n +^ ( $n +> 1 );
}

sub gray_decode ( Int $n is copy --> Int ) {
    my $mask = 1 +< (32-2);
    $n +^= $mask +> 1 if $n +& $mask while $mask +>= 1;
    return $n;
}

for ^32 -> $n {
    my $g = gray_encode($n);
    my $d = gray_decode($g);
    printf "%2d: %5b => %5b => %5b: %2d\n", $n, $n, $g, $d, $d;
    die if $d != $n;
}

```

Output:

```
 0:     0 =>     0 =>     0:  0
 1:     1 =>     1 =>     1:  1
 2:    10 =>    11 =>    10:  2
 3:    11 =>    10 =>    11:  3
 4:   100 =>   110 =>   100:  4
 5:   101 =>   111 =>   101:  5
 6:   110 =>   101 =>   110:  6
 7:   111 =>   100 =>   111:  7
 8:  1000 =>  1100 =>  1000:  8
 9:  1001 =>  1101 =>  1001:  9
10:  1010 =>  1111 =>  1010: 10
11:  1011 =>  1110 =>  1011: 11
12:  1100 =>  1010 =>  1100: 12
13:  1101 =>  1011 =>  1101: 13
14:  1110 =>  1001 =>  1110: 14
15:  1111 =>  1000 =>  1111: 15
16: 10000 => 11000 => 10000: 16
17: 10001 => 11001 => 10001: 17
18: 10010 => 11011 => 10010: 18
19: 10011 => 11010 => 10011: 19
20: 10100 => 11110 => 10100: 20
21: 10101 => 11111 => 10101: 21
22: 10110 => 11101 => 10110: 22
23: 10111 => 11100 => 10111: 23
24: 11000 => 10100 => 11000: 24
25: 11001 => 10101 => 11001: 25
26: 11010 => 10111 => 11010: 26
27: 11011 => 10110 => 11011: 27
28: 11100 => 10010 => 11100: 28
29: 11101 => 10011 => 11101: 29
30: 11110 => 10001 => 11110: 30
31: 11111 => 10000 => 11111: 31

```

Raku distinguishes numeric bitwise operators with a leading + sign,
so +< and +> are left and right shift,
while +& is a bitwise AND, while +^ is bitwise XOR
(here used as part of an assignment metaoperator).


[User]
Many image processing algorithms are defined for grayscale (or else monochromatic) images.

Task

Extend the data storage type defined on this page to support grayscale images.

Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.

To get luminance of a color use the formula recommended by CIE:

```
 L  =  0.2126 × R   +   0.7152 × G   +   0.0722 × B

```

When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.

[Assistant]
(formerly Perl 6)

This script expects to be fed a P6 .ppm file name at the command line. It will convert it to grey scale and save it as a binary portable grey map (P5 .pgm) file.

```
sub MAIN ($filename = 'default.ppm') {

    my $in = open($filename, :r, :enc<iso-8859-1>) or die $in;

    my ($type, $dim, $depth) = $in.lines[^3];

    my $outfile = $filename.subst('.ppm', '.pgm');
    my $out = open($outfile, :w, :enc<iso-8859-1>) or die $out;

    $out.say("P5\n$dim\n$depth");

    for $in.lines.ords -> $r, $g, $b {
        my $gs = $r * 0.2126 + $g * 0.7152 + $b * 0.0722;
        $out.print: chr($gs.floor min 255);
    }

    $in.close;
    $out.close;
}

```

Using the .ppm file from the Write a PPM file task:

Original:  Grey Scale:


[User]
Task

Find the greatest common divisor   (**GCD**)   of two integers.

*Greatest common divisor*   is also known as   *greatest common factor* **(gcf)**   and   *greatest common measure*.

Related task
:   * least common multiple.

See also
:   * MathWorld entry:   greatest common divisor.
    * Wikipedia entry:     greatest common divisor.

[Assistant]
(formerly Perl 6)

### Iterative

```
sub gcd (Int $a is copy, Int $b is copy) {
   $a & $b == 0 and fail;
   ($a, $b) = ($b, $a % $b) while $b;
   return abs $a;
}
```

### Recursive

```
multi gcd (0,      0)      { fail }
multi gcd (Int $a, 0)      { abs $a }
multi gcd (Int $a, Int $b) { gcd $b, $a % $b }
```

### Recursive(inline coderef)

```
{ $^b ?? &?BLOCK( $^b, $^a % $^b ) !! $^a }
```

### Concise

```
my &gcd = { ($^a.abs, $^b.abs, * % * ... 0)[*-2] }
```

### Actually, it's a built-in infix

```
my $gcd = $a gcd $b;
```

Because it's an infix, you can use it with various meta-operators:

```
[gcd] @list;         # reduce with gcd
@alist Zgcd @blist;  # lazy zip with gcd
@alist Xgcd @blist;  # lazy cross with gcd
@alist »gcd« @blist; # parallel gcd
```


[User]
Task

Create a function that returns the maximum value in a provided set of values,

where the number of values may not be known until run-time.

[Assistant]
(formerly Perl 6)
The built-in function works with any type that defines ordering.

```
say max 10, 4, 5, -2, 11;
say max <zero one two three four five six seven eight nine>;

# Even when the values and number of values aren't known until runtime
my @list = flat(0..9,'A'..'H').roll((^60).pick).rotor(4,:partial)».join.words;
say @list, ': ', max @list;
```

Sample output:

```
11
zero
[6808 013C 6D5B 4219 29G9 DC13 CA4F 55F3 AA06 0AGF DAB0 2]: DC13
```


[User]
Definitions

A cubefree number is a positive integer whose prime factorization does not contain any third (or higher) power factors. If follows that all primes are trivially cubefree and the first cubefree number is 1 because it has no prime factors.

Let a[n] be the greatest prime dividing the n-th cubefree number for n >= 2. By convention, let a[1] = 1 even though the first cubefree number, 1, has no prime factors.

Examples

a[2] is clearly 2 because it is the second cubefree number and also prime. The fourth cubefree number is 4 and it's highest prime factor is 2, hence a[4] = 2.

Task

Compute and show on this page the first **100** terms of a[n].
Also compute and show the **1,000th**, **10,000th** and **100,000th** members of the sequence.

Stretch

Compute and show the **1 millionth** and **10 millionth** terms of the sequence.

This may take a while for interpreted languages.

Reference

* OEIS sequence: A370833: a(n) is the greatest prime dividing the n-th cubefree number, for n >= 2; a(1)=1.
* The number of integers in a given interval which are multiple of at least one of the given numbers

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

sub max_factor_if_cubefree ($i) {
    my @f = prime-factors($i);
    return @f.tail if @f.elems          < 3
                   or @f.Bag.values.all < 3;
}

constant @Aₙ = lazy flat 1, map &max_factor_if_cubefree, 2..*;

say 'The first terms of A370833 are:';
say .fmt('%3d') for @Aₙ.head(100).batch(10);

say '';

for 10 X** (3..6) -> $k {
    printf "The %8dth term of A370833 is %7d\n", $k, @Aₙ[$k-1];
}

```

Output:

```
The first terms of A370833 are:
  1   2   3   2   5   3   7   3   5  11
  3  13   7   5  17   3  19   5   7  11
 23   5  13   7  29   5  31  11  17   7
  3  37  19  13  41   7  43  11   5  23
 47   7   5  17  13  53  11  19  29  59
  5  61  31   7  13  11  67  17  23   7
 71  73  37   5  19  11  13  79  41  83
  7  17  43  29  89   5  13  23  31  47
 19  97   7  11   5 101  17 103   7  53
107 109  11  37 113  19  23  29  13  59

The     1000th term of A370833 is     109
The    10000th term of A370833 is     101
The   100000th term of A370833 is    1693
The  1000000th term of A370833 is 1202057
```


[User]
Task

Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.

An empty subsequence is considered to have the sum of   **0**;   thus if all elements are negative, the result must be the empty sequence.

[Assistant]
(formerly Perl 6)

**Translation of**: Python

**Works with**: Rakudo version 2016.12

```
sub max-subseq (*@a) {
    my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0;
    for @a.kv -> $i, $x {
        $sum += $x;
        if $maxsum < $sum {
            ($maxsum, $end) = $sum, $i;
        }
        elsif $sum < 0 {
            ($sum, $start) = 0, $i;
        }
    }
    return @a[$start ^.. $end];
}

```

Another solution, not translated from any other language:

For each starting position, we calculate all the subsets starting at that position.
They are combined with the best subset ($max-subset) from previous loops, to form (@subsets).
The best of those @subsets is saved at the new $max-subset.

Consuming the array (.shift) allows us to skip tracking the starting point; it is always 0.

The empty sequence is used to initialize $max-subset, which fulfils the "all negative" requirement of the problem.

```
sub max-subseq ( *@a ) {

    my $max-subset = ();
    while @a {
        my @subsets = [\,] @a;
        @subsets.push: $max-subset;
        $max-subset = @subsets.max: { [+] .list };
        @a.shift;
    }

    return $max-subset;
}

max-subseq( -1, -2,  3,  5,  6, -2, -1,  4, -4,  2, -1 ).say;
max-subseq( -2, -2, -1,  3,  5,  6, -1,  4, -4,  2, -1 ).say;
max-subseq( -2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1 ).say;

```

Output:

```
(3 5 6 -2 -1 4)
(3 5 6 -1 4)
()
```


[User]
This task is about making a clone of the game "GREED" by Matthew Day.

This game is played on a grid of   **79**   column by   **22**   rows of random numbers from   **1**   to   **9**   (inclusive).

The player location is signified by the   **@**   symbol.

The object of Greed is to erase as much of the screen as possible by moving around   (all 8 directions are allowed in this grid).

When you move in a direction,   **N**   number of grid squares are erased ("eaten") in that direction,   **N**   being the first number in that direction.

Your score reflects the total number of squares "eaten".

You may not make a move that places you off the grid or over a previously eaten square.

The game is over if there is no more valid moves.

Video on YouTube

[Assistant]
**Translation of**: Phix

```
# 20200913 added Raku programming solution

srand 123456;

my @board = [ (1..9).roll xx my \w = 79 ] xx my \h = 22 ;
my \X = $ = w.rand.Int ; my \Y = $ = h.rand.Int;
@board[Y;X] = '@';
my \score = $ = 0;

sub execute (\y,\x) {
   my \i = $ = @board[Y+y;X+x];
   if countSteps(i, x, y) {
      score += i;
      @board[ Y +  y*$_ ; X +  x*$_ ] = ' ' for ^i;
      @board[ Y += y*i  ; X += x*i  ] = '@';
   }
}

sub countSteps(\i, \x, \y) {
   my \tX = $ = X ; my \tY = $ = Y;
   for ^i {
      tX += x; tY += y;
      return False if tX < 0 or tY < 0 or tX ≥ w or tY ≥ h or @board[tY;tX] eq ' '
   }
   return True;
}

sub existsMoves {
   for (-1 .. 1) X (-1 .. 1) -> (\x,\y) {
      next if x == 0 and y == 0;
      next if X+x < 0 or X+x > w or Y+y < 0 or Y+y > h ;
      my \i = @board[Y+y;X+x];
      return True if ( i ne ' ' and countSteps(i, x, y) )
   }
   return False;
}

loop {
   for @board { .join.print ; print "\r\n" } ;
   { say "Game over." and last } unless existsMoves();
   print "Current score : ", score, "\r\n";
   given my $c = $*IN.getc {
      when 'q' { say "So long." and last}
      when 'e' { execute(-1,-1) if X > 0 and Y > 0 } # North-West
      when 'r' { execute(-1, 0) if           Y > 0 } # North
      when 't' { execute(-1, 1) if X < w and Y > 0 } # North-East
      when 'd' { execute( 0,-1) if X > 0           } # West
      when 'g' { execute( 0, 1) if X < w           } # East
      when 'x' { execute( 1,-1) if X > 0 and Y < h } # South-West
      when 'c' { execute( 1, 0) if           Y < h } # South
      when 'v' { execute( 1, 1) if X < w and Y < h } # South-East
   }
}

```


[User]
An   Egyptian fraction   is the sum of distinct unit fractions such as:

:   :   :   :   1
                2
                +

                1
                3
                +

                1
                16

                (
                =

                43
                48
                )
                {\displaystyle {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}}

Each fraction in the expression has a numerator equal to   **1**   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions).

Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction

x
y
{\displaystyle {\displaystyle {\tfrac {x}{y}}}}
    to be represented by repeatedly performing the replacement

:   :   :   :   x
                y
                =

                1

                ⌈
                y

                /
                x
                ⌉
                +

                (
                −
                y
                )

                mod

                x

                y
                ⌈
                y

                /
                x
                ⌉
                {\displaystyle {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}}

(simplifying the 2nd term in this replacement as necessary, and where

⌈
x
⌉
{\displaystyle {\displaystyle \lceil x\rceil }}
    is the   *ceiling*   function).

For this task,   Proper and improper fractions   must be able to be expressed.

Proper  fractions   are of the form

a
b
{\displaystyle {\displaystyle {\tfrac {a}{b}}}}
    where

a
{\displaystyle {\displaystyle a}}
    and

b
{\displaystyle {\displaystyle b}}
    are positive integers, such that

a
<
b
{\displaystyle {\displaystyle a<b}}
,     and

improper fractions are of the form

a
b
{\displaystyle {\displaystyle {\tfrac {a}{b}}}}
    where

a
{\displaystyle {\displaystyle a}}
    and

b
{\displaystyle {\displaystyle b}}
    are positive integers, such that    *a* ≥ *b*.

(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)

For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [*n*].

Task requirements

* show the Egyptian fractions for:

  43
  48
  {\displaystyle {\displaystyle {\tfrac {43}{48}}}}
   and

  5
  121
  {\displaystyle {\displaystyle {\tfrac {5}{121}}}}
   and

  2014
  59
  {\displaystyle {\displaystyle {\tfrac {2014}{59}}}}
* for all proper fractions,

  a
  b
  {\displaystyle {\displaystyle {\tfrac {a}{b}}}}
      where

  a
  {\displaystyle {\displaystyle a}}
      and

  b
  {\displaystyle {\displaystyle b}}
      are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:

:   :   * the largest number of terms,
        * the largest denominator.

* for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit}

Also see

* Wolfram MathWorld™ entry: Egyptian fraction
* Numberphile YouTube video: Egyptian Fractions and the Greedy Algorithm

[Assistant]
(formerly Perl 6)

```
role Egyptian {
    method gist {
	join ' + ',
	    ("[{self.floor}]" if self.abs >= 1),
	    map {"1/$_"}, self.denominators;
    }
    method denominators {
	my ($x, $y) = self.nude;
	$x %= $y;
	my @denom = gather ($x, $y) = -$y % $x, $y * take ($y / $x).ceiling
	    while $x;
    }
}

say .nude.join('/'), " = ", $_ but Egyptian for 43/48, 5/121, 2014/59;

my @sample = map { $_ => .denominators },
    grep * < 1,
        map {$_ but Egyptian},
            (2 .. 99 X/ 2 .. 99);

say .key.nude.join("/"),
    " has max denominator, namely ",
    .value.max
        given max :by(*.value.max), @sample;

say .key.nude.join("/"),
    " has max number of denominators, namely ",
    .value.elems
        given max :by(*.value.elems), @sample;

```

Output:

```
43/48 = 1/2 + 1/3 + 1/16
5/121 = 1/25 + 1/757 + 1/763309 + 1/873960180913 + 1/1527612795642093418846225
2014/59 = [34] + 1/8 + 1/95 + 1/14947 + 1/670223480
8/97 has max denominator, namely 579504587067542801713103191859918608251030291952195423583529357653899418686342360361798689053273749372615043661810228371898539583862011424993909789665
8/97 has max number of denominators, namely 8
```

Because the harmonic series diverges (albeit very slowly), it is possible to write even improper fractions as a sum of distinct unit fractions. Here is a code to do that:

```
role Egyptian {
    method gist { join ' + ', map {"1/$_"}, self.list }
    method list {
	my $sum = 0;
	gather for 2 .. * {
	    last if $sum == self;
	    $sum += 1 / .take unless $sum + 1 / $_ > self;
	}
    }
}

say 5/4 but Egyptian;

```

Output:

```
1/2 + 1/3 + 1/4 + 1/6
```

The list of terms grows exponentially with the value of the fraction, though.


[User]
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.

For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)

For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).

Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.

[Assistant]
(formerly Perl 6)

```
my ($width,$height) = 1280,768;

my $PGM = open "Greyscale-bars-perl6.pgm", :w orelse die "Can't create Greyscale-bars-perl6.pgm: $_";

$PGM.print: qq:to/EOH/;
    P2
    # Greyscale-bars-perl6.pgm
    $width $height
    65535
    EOH

my ($h1,$h2,$h3,$h4) = divvy($height,4);

my @nums = ((0/7,1/7...7/7) X* 65535)».floor;
my $line = ~(@nums Zxx divvy($width,8));
$PGM.say: $line for ^$h1;

@nums = ((15/15,14/15...0/15) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,16));
$PGM.say: $line for ^$h2;

@nums = ((0/31,1/31...31/31) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,32));
$PGM.say: $line for ^$h3;

@nums = ((63/63,62/63...0/63) X* 65535)».floor;
$line = ~(@nums Zxx divvy($width,64));
$PGM.say: $line for ^$h4;

$PGM.close;

sub divvy($all, $div) {
    my @marks = ((1/$div,2/$div ... 1) X* $all)».round;
    @marks Z- 0,|@marks;
}

```

See Greyscale-bars-perl6 (offsite image)


[User]
**GSTrans** string encoding is a method of encoding all 8-bit character values 0-255 with only printable characters. It originates on Acorn computers to allow command line
commands to process non-printable characters.

```
 Character Encoding
 0-31      |letter eg |@, |A, |i |[ etc.
 32-126    character, except for:
 "         |"
 |         ||
 127       |?
 128-255   |! followed by encoding, eg |!|@ = 128

```

A string can be surrounded in quotes, eg "ALERT|G".

See http://www.riscos.com/support/developers/prm/conversions.html

Examples:

```
 |LHello|G|J|M       encodes  CHR$12;"Hello";CHR$7;CHR$10;CHR$13
 "|m|j|@|e|!t|m|!|?" encodes  13,10,0,5,244,13,255

```

Task

:   * Write two functions, one to encode a string of characters into a GSTrans string, and one to decode a GSTrans string. Indicate if any error checking is done, and how it is indicated.

[Assistant]
**Translation of**: Julia

```
# 20231105 Raku programming solution

sub GSTrans-encode(Str $str) {
   return [~] $str.encode('utf8').list.chrs.comb.map: -> $c {
      my $i = $c.ord;
      die "Char value of $c, $i, is out of range" unless 0 <= $i <= 255;
      given ($i,$c) {
         when 0 <= $i <= 31    { '|' ~ chr(64 + $i) }
         when $c eq '"'        { '|"' }
         when $c eq '|'        { '||' }
         when $i == 127        { '|?' }
         when 128 <= $i <= 255 { '|!' ~ GSTrans-encode(chr($i - 128)) }
         default               { $c }
      }
   }
}

sub GSTrans-decode(Str $str) {
   my ($gotbar, $gotbang, $bangadd) = False, False, 0;

   my @result = gather for $str.comb -> $c {
      if $gotbang {
         if $c eq '|' {
            $bangadd = 128;
            $gotbar = True;
         } else {
            take $c.ord + 128;
         }
         $gotbang = False;
      } elsif $gotbar {
         given $c {
            when $c eq '?' { take 127 + $bangadd }
            when $c eq '!' { $gotbang = True }
            when $c eq '|' || $c eq '"' || $c eq '<' { take $c.ord + $bangadd }
            when $c eq '[' || $c eq '{' { take 27 + $bangadd }
            when $c eq '\\' { take 28 + $bangadd }
            when $c eq ']' || $c eq '}' { take 29 + $bangadd }
            when $c eq '^' || $c eq '~' { take 30 + $bangadd }
            when $c eq '_' || $c eq '`' { take 31 + $bangadd }
            default { my $i = $c.uc.ord - 64 + $bangadd;
                      take $i >= 0 ?? $i !! $c.ord      }
         }
         $gotbar = False;
         $bangadd = 0;
      } elsif $c eq '|' {
         $gotbar = True
      } else {
         take $c.ord
      }
   }
   return Blob.new(@result).decode('utf8c8')
}

my @TESTS = <ALERT|G 'wert↑>;
my @RAND_TESTS = ^256 .roll(10).chrs.join xx 8;
my @DECODE_TESTS = < |LHello|G|J|M |m|j|@|e|!t|m|!|? abc|1de|5f >;

for |@TESTS, |@RAND_TESTS -> $t {
   my $encoded = GSTrans-encode($t);
   my $decoded = GSTrans-decode($encoded);
   say "String $t encoded is: $encoded, decoded is: $decoded.";
   die unless $t ~~ $decoded;
}
for @DECODE_TESTS -> $enc {
    say "Encoded string $enc decoded is: ", GSTrans-decode($enc);
}

```

You may Attempt This Online!


[User]
Task

Write a program where the program chooses a number between   **1**   and   **10**.

A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct.

When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   and the program exits.

A   conditional loop   may be used to repeat the guessing until the user is correct.

Related tasks

* Bulls and cows
* Bulls and cows/Player
* Guess the number/With Feedback
* Mastermind

[Assistant]
(formerly Perl 6)

```
my $number = (1..10).pick;
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!";

```


[User]
Task

Write a game (computer program) that follows the following rules:

:   :   * The computer chooses a number between given set limits.
        * The player is asked for repeated guesses until the the target number is guessed correctly
        * At each guess, the computer responds with whether the guess is:

        :   :   :   * higher than the target,
                    * equal to the target,
                    * less than the target,   or
                    * the input was inappropriate.

Related task

* Guess the number/With Feedback (Player)

[Assistant]
(formerly Perl 6)

```
my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
    say "Oops! The upper boundary should be > 0 and not Inf";
    $maxnum = prompt("Please give me a valid upper boundary: ");
}

my $count = 0;
my $number = (1..$maxnum).pick;

say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
repeat until my $guessed-right {
    given prompt("Your guess: ") {
        when /^[e|q]/ { say 'Goodbye.'; exit; }
        when not 1 <= $_ <= $maxnum {
           say "You really should give me a number from 1 to $maxnum."
        }
        $count++;
        when $number { $guessed-right = True }
        when $number < $_ { say "Sorry, my number is smaller." }
        when $number > $_ { say "Sorry, my number is bigger." }
    }
}
say "Great you guessed right after $count attempts!";

```

```
Hello, please give me an upper boundary: 10
I'm thinking of a number from 1 to 10, try to guess it!
Your guess: 5
Sorry, my number is bigger.
Your guess: 7
Sorry, my number is smaller.
Your guess: 6
Great you guessed right after 3 attempts!
```


[User]
Task

Write a player for the game that follows the following rules:

:   The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.

The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.

Related tasks

* Guess the number/With Feedback
* Bulls and cows/Player

[Assistant]
(formerly Perl 6)

```
multi sub MAIN() { MAIN(0, 100) }
multi sub MAIN($min is copy where ($min >= 0), $max is copy where ($max > $min)) {
    say "Think of a number between $min and $max and I'll guess it!";
    while $min <= $max {
        my $guess = (($max + $min)/2).floor;
        given lc prompt "My guess is $guess. Is your number higher, lower or equal? " {
            when /^e/ { say "I knew it!"; exit }
            when /^h/ { $min = $guess + 1      }
            when /^l/ { $max = $guess          }
            default   { say "WHAT!?!?!"        }
        }
    }
    say "How can your number be both higher and lower than $max?!?!?";
}

```

You may execute this program with 'raku program' or with 'raku program min max'. Raku creates a usage for us if we don't give the right parameters. It also parses the parameters for us and provides them via $min and $max. We use multi-subs to provide two MAIN subroutines so the user is able to choose between min and max parameters and no parameters at all, in which case min is set to 0 and max to 100.


[User]
Almost every application needs to communicate with the user in some way.
Therefore, a substantial part of the code deals with the interaction
of program logic with GUI components.

Typically, the following is needed:

* put values into input fields under program control
* read and check input from the user
* pop up dialogs to query the user for further information

Task

For a minimal "application", write a program that presents a form with three components to the user:

:   :   * a numeric input field ("Value")
        * a button ("increment")
        * a button ("random")

The field is initialized to zero.

The user may manually enter a new value into the field,
or increment its value with the "increment" button.

Entering a non-numeric value should be either impossible,
or issue an error message.

Pressing the "random" button presents a confirmation dialog,
and resets the field's value to a random value if the answer is "Yes".

(This task may be regarded as an extension of the task Simple windowed application).

[Assistant]
(formerly Perl 6)

**Library:** GTK

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

my GTK::Simple::App $app .= new(title => 'GUI component interaction');

$app.set-content(
    my $box = GTK::Simple::VBox.new(
        my $value     = GTK::Simple::Entry.new(text => '0'),
        my $increment = GTK::Simple::Button.new(label => 'Increment'),
        my $random    = GTK::Simple::Button.new(label => 'Random'),
    )
);

$app.size-request(400, 100);
$app.border-width = 20;
$box.spacing = 10;

$value.changed.tap: {
    ($value.text ||= '0') ~~ s:g/<-[0..9]>//;
}

$increment.clicked.tap: {
    my $val = $value.text; $val += 1; $value.text = $val.Str
}

$random.clicked.tap: {
    # Dirty hack to work around the fact that GTK::Simple doesn't provide
    # access to GTK message dialogs yet :P
    if run «zenity --question --text "Reset to random value?"» {
        $value.text = (^100).pick.Str
    }
}

$app.run;

```


[User]
In addition to fundamental GUI component interaction, an application should
dynamically enable and disable GUI components, to give some guidance to the
user, and prohibit (inter)actions which are inappropriate in the current state
of the application.

Task

Similar to the task GUI component interaction, write a program
that presents a form with three components to the user:

:   :   1. a numeric input field ("Value")
        2. a button   ("increment")
        3. a button   ("decrement")

The field is initialized to zero.
The user may manually enter a new value into the field,
increment its value with the "increment" button,
or decrement the value with the "decrement" button.

The input field should be enabled only when its value is zero.
The "increment" button only as long as the field's value is less then 10:
When the value 10 is reached, the button should go into a disabled state.
Analogously, the "decrement" button should be enabled only as long as
the value is greater than zero.

Effectively, the user can now either increment up to 10, or down to zero.
Manually entering values outside that range is still legal,
but the buttons should reflect that and enable/disable accordingly.

[Assistant]
(formerly Perl 6)
Extremely basic implementation using the GTK library.

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

my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );

$app.set-content(
    my $box = GTK::Simple::HBox.new(
        my $inc   = GTK::Simple::Button.new( label => ' + ' ),
        my $value = GTK::Simple::Entry.new,
        my $dec   = GTK::Simple::Button.new( label => ' - ' )
    )
);

$app.border-width = 10;
$box.spacing = 10;

$value.changed.tap: {
    $value.text.=subst(/\D/, '');
    $inc.sensitive = $value.text < 10;
    $dec.sensitive = $value.text > 0;
}

$value.text = '0';

$inc.clicked.tap: { my $val = $value.text; $val += 1; $value.text = $val.Str }
$dec.clicked.tap: { my $val = $value.text; $val -= 1; $value.text = $val.Str }

$app.run;

```


[User]
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.

This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.

The idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).

The values calculated should represent the usable desktop area of a window maximized to fit the the screen.

Considerations

--- Multiple Monitors

For multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.:   the monitor which would display a window if such instructions were given).

--- Tiling Window Managers

For a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.12

This is kind-of a silly task. The maximum window size is going to depend on your OS, hardware, display server and graphics toolkit, not your programming language. Taken at face value, using a Linux system running an X11 display server, the maximum displayable window size is the resolution of your monitor. Basically, the size of your desktop viewport. The Raku module X11::libxdo returns the desktop viewport size for get-desktop-dimensions which is the effective maximum window size.

```
use X11::libxdo;

my $xdo = Xdo.new;

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

say "Desktop viewport dimensions: (maximum-fullscreen size) $dw x $dh";

```

On my system returns:

```
Desktop viewport dimensions: (maximum-fullscreen size) 1920 x 1080
```


[User]
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:

* If   n   is     **1**     then the sequence ends.
* If   n   is   **even** then the next   n   of the sequence    `= n/2`
* If   n   is   **odd**   then the next   n   of the sequence    `= (3 * n) + 1`

The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.

This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):

:   :   :   * hailstone sequence,   hailstone numbers
            * 3x + 2 mapping,   3n + 1 problem
            * Collatz sequence
            * Hasse's algorithm
            * Kakutani's problem
            * Syracuse algorithm,   Syracuse problem
            * Thwaites conjecture
            * Ulam's problem

The hailstone sequence is also known as   *hailstone numbers*   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).

Task

1. Create a routine to generate the hailstone sequence for a number.
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with `27, 82, 41, 124` and ending with `8, 4, 2, 1`
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
      (But don't show the actual sequence!)

See also

* xkcd (humourous).
* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).

[Assistant]
(formerly Perl 6)

```
sub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }

my @h = hailstone(27);
say "Length of hailstone(27) = {+@h}";
say ~@h;

my $m = max ( (1..99_999).race.map: { +hailstone($_) => $_ } );
say "Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000";
```

Output:

```
Length of hailstone(27) = 112
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Max length 351 was found for hailstone(77031) for numbers < 100_000

```


[User]
Task

Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok?

The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an internal corruption has been detected and it would be dangerous and irresponsible to continue.

References

* Wikipedia: Halt and Catch Fire

Related Tasks

* Program termination

[Assistant]
```
++8

```

Syntactically: Valid.

Semantically: Change the mathematical concept of 8 to 9, either in your whole computer, or maybe the whole universe.

Fails with this run-time error:

Output:

```
Cannot resolve caller prefix:<++>(Int:D); the following candidates
match the type but require mutable arguments:
    (Mu:D $a is rw)
    (Int:D $a is rw --> Int:D)

The following do not match for other reasons:
    (Bool $a is rw)
    (Mu:U $a is rw)
    (Num:D $a is rw)
    (Num:U $a is rw)
    (int $a is rw --> int)
    (num $a is rw --> num)
  in block <unit> at -e line 1
```

Alternately, and perhaps more community condoned, to end the program as soon as possible without trying to change the Laws of the Universe, you could just enter:

```
die

```

In REPL:

```
Died
  in block <unit> at <unknown file> line 1
```

Same character count, exits the program as soon as possible (though trappable if desired through the exception system,) and it looks more like an intentional act rather than a typo. Plus, you can add a message that will be added *when* it dies to explain why.

Here is a silly alternative : A standalone Unicode counterpart for the yada yada yada operator takes up 3 code units but visually just a single codepoint,

Output:

```
cat test.raku ; wc test.raku
…
1 1 4 test.raku

raku -c test.raku ; echo $?
Syntax OK
0

raku test.raku ; echo $?
Stub code executed
  in block <unit> at test.raku line 1

1
```

However when I tried to combine all to test against the Test module, the last one somehow lived through an EVAL,

```
use Test;

dies-ok { ++8 };
dies-ok { die };
dies-ok {  …  };

eval-dies-ok '++8';
eval-dies-ok 'die';
eval-dies-ok  '…' ;

```

Output:

```
ok 1 -
ok 2 -
ok 3 -
ok 4 -
ok 5 -
not ok 6 -
# Failed test at all.raku line 11
```

so it is indeed at one's discretion whether this one is qualified as a crasher.


[User]
**Hamming numbers** are numbers of the form

```
    H = 2i × 3j × 5k
           where
     i,  j,  k  ≥  0

```

*Hamming numbers*   are also known as   *ugly numbers*   and also   *5-smooth numbers*   (numbers whose prime divisors are less or equal to 5).

Task

Generate the sequence of Hamming numbers, *in increasing order*.   In particular:

1. Show the   first twenty   Hamming numbers.
2. Show the   1691st   Hamming number (the last one below   231).
3. Show the   one millionth   Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).

Related tasks

* Humble numbers
* N-smooth numbers

References

* Wikipedia entry:   Hamming numbers     (this link is re-directed to   **Regular number**).
* Wikipedia entry:   Smooth number
* OEIS entry:   A051037   5-smooth   or   Hamming numbers
* Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).

[Assistant]
(formerly Perl 6)

### Merge version

**Works with**: rakudo version 2015-11-04

The limit scaling is not *required*, but it cuts down on a bunch of unnecessary calculation.

```
my $limit = 32;

sub powers_of ($radix) { 1, |[\*] $radix xx * }

my @hammings =
  (   powers_of(2)[^ $limit ]       X*
      powers_of(3)[^($limit * 2/3)] X*
      powers_of(5)[^($limit * 1/2)]
   ).sort;

say @hammings[^20];
say @hammings[1690]; # zero indexed
```

Output:

```
(1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36)
2125764000
```

### Iterative version

**Works with**: rakudo version 6.c

This version uses a lazy list, storing a maximum of two extra value from the highest index requested

```
my \Hammings := gather {
  my %i = 2, 3, 5 Z=> (Hammings.iterator for ^3);
  my %n = 2, 3, 5 Z=> 1 xx 3;

  loop {
    take my $n := %n{2, 3, 5}.min;

    for 2, 3, 5 -> \k {
      %n{k} = %i{k}.pull-one * k if %n{k} == $n;
    }
  }
}

say Hammings.[^20];
say Hammings.[1691 - 1];
say Hammings.[1000000 - 1];
```

Output:

```
(1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36)
2125764000
519312780448388736089589843750000000000000000000000000000000000000000000000000000000
```


[User]
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space.
Unhandled signals generally terminate a program in a disorderly manner.
Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal.

Task

Provide a program that displays an integer on each line of output at the rate of about one per half second.
Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.

[Assistant]
(formerly Perl 6)
We note with glee that the task does not require us to print *consecutive* integers, so we'll print Fibonacci numbers instead. :-)

```
signal(SIGINT).tap: {
    note "Took { now - INIT now } seconds.";
    exit;
}

for 0, 1, *+* ... * {
    sleep 0.5;
    .say;
}

```

Output:

```
0
1
1
2
3
5
8
13
21
34
55
89
^CTook 6.3437449 seconds.
Aborted
```


[User]
From Wikipedia, the free encyclopedia:

:   :   A happy number is defined by the following process:

:   :   Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   **1**   (where it will stay),   or it loops endlessly in a cycle which does not include   **1**.

:   :   Those numbers for which this process end in   **1**   are       *happy*   numbers,
    :   while   those numbers   that   do   not   end in   **1**   are   *unhappy*   numbers.

Task

Find and print the first   **8**   happy numbers.

Display an example of your output here on this page.

Related tasks

* Iterated digits squaring

See also

* The OEIS entry:   The     happy numbers:   A007770
* The OEIS entry:   The unhappy numbers;   A031177

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-09-13

```
sub happy (Int $n is copy --> Bool) {
  loop {
      state %seen;
      $n = [+] $n.comb.map: { $_ ** 2 }
      return True  if $n == 1;
      return False if %seen{$n}++;
  }
}

say join ' ', grep(&happy, 1 .. *)[^8];
```

Output:

```
1 7 10 13 19 23 28 31
```

Here's another approach that uses a different set of tricks including lazy lists, gather/take, repeat-until, and the cross metaoperator X.

```
my @happy = lazy gather for 1..* -> $number {
    my %stopper = 1 => 1;
    my $n = $number;
    repeat until %stopper{$n}++ {
        $n = [+] $n.comb X** 2;
    }
    take $number if $n == 1;
}

say ~@happy[^8];
```

Output is the same as above.

Here is a version using a subset and an anonymous recursion (we cheat a little bit by using the knowledge that 7 is the second happy number):

```
subset Happy of Int where sub ($n) {
    $n == 1 ?? True  !!
    $n < 7  ?? False !!
    &?ROUTINE([+] $n.comb »**» 2);
}

say (grep Happy, 1 .. *)[^8];
```

Again, output is the same as above. It is not clear whether this version returns in finite time for any integer, though.

There's more than one way to do it...