[User]
Write a function that prints the result of the division of two positive integers with infinite precision (only limited by the available memory), stopping before the period starts repeating itself. Return also the length of this period (0 if there is no period).

Demonstrate it with the division 1/149, whose result is 0.0067114093959731543624161073825503355704697986577181208053691275167785234899328859060402684563758389261744966442953020134228187919463087248322147651, where the last 148 digits repeat endlessly.

The result could be stored as a string or simply output to the screen.
Note that the division of any two integers will always produce a period, but if the numerator is an exact multiple of the denominator, or if the denominator contains only the factors 2 and 5, the period will be 0. In the remaining cases, these possible 2's and 5's of the denominator produce a leading number of digits in the quotient, but have no effect on the period.

References

* Wikipedia: Long Division

Related

* Long primes

[Assistant]
It's a built-in.

```
for 0/1, 1/1, 1/3, 1/7, -83/60, 1/17, 10/13, 3227/555, 5**21/2**63, 1/149, 1/5261 -> $rat {
    printf "%35s - Period is %-5s: %s%s\n", $rat.nude.join('/'), .[1].chars, .[0], (.[1].comb Z~ "\c[COMBINING OVERLINE]" xx *).join
        given $rat.base-repeating
}

```

Output:

```
                                0/1 - Period is 0    : 0
                                1/1 - Period is 0    : 1
                                1/3 - Period is 1    : 0.3̅
                                1/7 - Period is 6    : 0.1̅4̅2̅8̅5̅7̅
                             -83/60 - Period is 1    : -1.383̅
                               1/17 - Period is 16   : 0.0̅5̅8̅8̅2̅3̅5̅2̅9̅4̅1̅1̅7̅6̅4̅7̅
                              10/13 - Period is 6    : 0.7̅6̅9̅2̅3̅0̅
                           3227/555 - Period is 3    : 5.81̅4̅4̅
476837158203125/9223372036854775808 - Period is 0    : 0.000051698788284564229679463043254372678347863256931304931640625
                              1/149 - Period is 148  : 0.0̅0̅6̅7̅1̅1̅4̅0̅9̅3̅9̅5̅9̅7̅3̅1̅5̅4̅3̅6̅2̅4̅1̅6̅1̅0̅7̅3̅8̅2̅5̅5̅0̅3̅3̅5̅5̅7̅0̅4̅6̅9̅7̅9̅8̅6̅5̅7̅7̅1̅8̅1̅2̅0̅8̅0̅5̅3̅6̅9̅1̅2̅7̅5̅1̅6̅7̅7̅8̅5̅2̅3̅4̅8̅9̅9̅3̅2̅8̅8̅5̅9̅0̅6̅0̅4̅0̅2̅6̅8̅4̅5̅6̅3̅7̅5̅8̅3̅8̅9̅2̅6̅1̅7̅4̅4̅9̅6̅6̅4̅4̅2̅9̅5̅3̅0̅2̅0̅1̅3̅4̅2̅2̅8̅1̅8̅7̅9̅1̅9̅4̅6̅3̅0̅8̅7̅2̅4̅8̅3̅2̅2̅1̅4̅7̅6̅5̅1̅
                             1/5261 - Period is 1052 : 0.0̅0̅0̅1̅9̅0̅0̅7̅7̅9̅3̅1̅9̅5̅2̅1̅0̅0̅3̅6̅1̅1̅4̅8̅0̅7̅0̅7̅0̅8̅9̅9̅0̅6̅8̅6̅1̅8̅1̅3̅3̅4̅3̅4̅7̅0̅8̅2̅3̅0̅3̅7̅4̅4̅5̅3̅5̅2̅5̅9̅4̅5̅6̅3̅7̅7̅1̅1̅4̅6̅1̅6̅9̅9̅2̅9̅6̅7̅1̅1̅6̅5̅1̅7̅7̅7̅2̅2̅8̅6̅6̅3̅7̅5̅2̅1̅3̅8̅3̅7̅6̅7̅3̅4̅4̅6̅1̅1̅2̅9̅0̅6̅2̅9̅1̅5̅7̅9̅5̅4̅7̅6̅1̅4̅5̅2̅1̅9̅5̅4̅0̅0̅1̅1̅4̅0̅4̅6̅7̅5̅9̅1̅7̅1̅2̅6̅0̅2̅1̅6̅6̅8̅8̅8̅4̅2̅4̅2̅5̅3̅9̅4̅4̅1̅1̅7̅0̅8̅8̅0̅0̅6̅0̅8̅2̅4̅9̅3̅8̅2̅2̅4̅6̅7̅2̅1̅1̅5̅5̅6̅7̅3̅8̅2̅6̅2̅6̅8̅7̅7̅0̅1̅9̅5̅7̅8̅0̅2̅6̅9̅9̅1̅0̅6̅6̅3̅3̅7̅1̅9̅8̅2̅5̅1̅2̅8̅3̅0̅2̅6̅0̅4̅0̅6̅7̅6̅6̅7̅7̅4̅3̅7̅7̅4̅9̅4̅7̅7̅2̅8̅5̅6̅8̅7̅1̅3̅1̅7̅2̅4̅0̅0̅6̅8̅4̅2̅8̅0̅5̅5̅5̅0̅2̅7̅5̅6̅1̅3̅0̅0̅1̅3̅3̅0̅5̅4̅5̅5̅2̅3̅6̅6̅4̅7̅0̅2̅5̅2̅8̅0̅3̅6̅4̅9̅4̅9̅6̅2̅9̅3̅4̅8̅0̅3̅2̅6̅9̅3̅4̅0̅4̅2̅9̅5̅7̅6̅1̅2̅6̅2̅1̅1̅7̅4̅6̅8̅1̅6̅1̅9̅4̅6̅3̅9̅8̅0̅2̅3̅1̅8̅9̅5̅0̅7̅6̅9̅8̅1̅5̅6̅2̅4̅4̅0̅6̅0̅0̅6̅4̅6̅2̅6̅4̅9̅6̅8̅6̅3̅7̅1̅4̅1̅2̅2̅7̅9̅0̅3̅4̅4̅0̅4̅1̅0̅5̅6̅8̅3̅3̅3̅0̅1̅6̅5̅3̅6̅7̅8̅0̅0̅7̅9̅8̅3̅2̅7̅3̅1̅4̅1̅9̅8̅8̅2̅1̅5̅1̅6̅8̅2̅1̅8̅9̅6̅9̅7̅7̅7̅6̅0̅8̅8̅1̅9̅6̅1̅6̅0̅4̅2̅5̅7̅7̅4̅5̅6̅7̅5̅7̅2̅7̅0̅4̅8̅0̅8̅9̅7̅1̅6̅7̅8̅3̅8̅8̅1̅3̅9̅1̅3̅7̅0̅4̅6̅1̅8̅8̅9̅3̅7̅4̅6̅4̅3̅6̅0̅3̅8̅7̅7̅5̅8̅9̅8̅1̅1̅8̅2̅2̅8̅4̅7̅3̅6̅7̅4̅2̅0̅6̅4̅2̅4̅6̅3̅4̅0̅9̅9̅9̅8̅0̅9̅9̅2̅2̅0̅6̅8̅0̅4̅7̅8̅9̅9̅6̅3̅8̅8̅5̅1̅9̅2̅9̅2̅9̅1̅0̅0̅9̅3̅1̅3̅8̅1̅8̅6̅6̅5̅6̅5̅2̅9̅1̅7̅6̅9̅6̅2̅5̅5̅4̅6̅4̅7̅4̅0̅5̅4̅3̅6̅2̅2̅8̅8̅5̅3̅8̅3̅0̅0̅7̅0̅3̅2̅8̅8̅3̅4̅8̅2̅2̅2̅7̅7̅1̅3̅3̅6̅2̅4̅7̅8̅6̅1̅6̅2̅3̅2̅6̅5̅5̅3̅8̅8̅7̅0̅9̅3̅7̅0̅8̅4̅2̅0̅4̅5̅2̅3̅8̅5̅4̅7̅8̅0̅4̅5̅9̅9̅8̅8̅5̅9̅5̅3̅2̅4̅0̅8̅2̅8̅7̅3̅9̅7̅8̅3̅3̅1̅1̅1̅5̅7̅5̅7̅4̅6̅0̅5̅5̅8̅8̅2̅9̅1̅1̅9̅9̅3̅9̅1̅7̅5̅0̅6̅1̅7̅7̅5̅3̅2̅7̅8̅8̅4̅4̅3̅2̅6̅1̅7̅3̅7̅3̅1̅2̅2̅9̅8̅0̅4̅2̅1̅9̅7̅3̅0̅0̅8̅9̅3̅3̅6̅6̅2̅8̅0̅1̅7̅4̅8̅7̅1̅6̅9̅7̅3̅9̅5̅9̅3̅2̅3̅3̅2̅2̅5̅6̅2̅2̅5̅0̅5̅2̅2̅7̅1̅4̅3̅1̅2̅8̅6̅8̅2̅7̅5̅9̅9̅3̅1̅5̅7̅1̅9̅4̅4̅4̅9̅7̅2̅4̅3̅8̅6̅9̅9̅8̅6̅6̅9̅4̅5̅4̅4̅7̅6̅3̅3̅5̅2̅9̅7̅4̅7̅1̅9̅6̅3̅5̅0̅5̅0̅3̅7̅0̅6̅5̅1̅9̅6̅7̅3̅0̅6̅5̅9̅5̅7̅0̅4̅2̅3̅8̅7̅3̅7̅8̅8̅2̅5̅3̅1̅8̅3̅8̅0̅5̅3̅6̅0̅1̅9̅7̅6̅8̅1̅0̅4̅9̅2̅3̅0̅1̅8̅4̅3̅7̅5̅5̅9̅3̅9̅9̅3̅5̅3̅7̅3̅5̅0̅3̅1̅3̅6̅2̅8̅5̅8̅7̅7̅2̅0̅9̅6̅5̅5̅9̅5̅8̅9̅4̅3̅1̅6̅6̅6̅9̅8̅3̅4̅6̅3̅2̅1̅9̅9̅2̅0̅1̅6̅7̅2̅6̅8̅5̅8̅0̅1̅1̅7̅8̅4̅8̅3̅1̅7̅8̅1̅0̅3̅0̅2̅2̅2̅3̅9̅1̅1̅8̅0̅3̅8̅3̅9̅5̅7̅4̅2̅2̅5̅4̅3̅2̅4̅2̅7̅2̅9̅5̅1̅9̅1̅0̅2̅8̅3̅2̅1̅6̅1̅1̅8̅6̅0̅8̅6̅2̅9̅5̅3̅8̅1̅1̅0̅6̅2̅5̅3̅5̅6̅3̅9̅6̅1̅2̅2̅4̅1̅0̅1̅8̅8̅1̅7̅7̅1̅5̅2̅6̅3̅2̅5̅7̅9̅3̅5̅7̅5̅3̅6̅5̅9̅
```


[User]
Some languages support one or more integer types of the underlying processor.

This integer types have fixed size;   usually   **8**-bit,   **16**-bit,   **32**-bit,   or   **64**-bit.

The integers supported by such a type can be   *signed*   or   *unsigned*.

Arithmetic for machine level integers can often be done by single CPU instructions.

This allows high performance and is the main reason to support machine level integers.

Definition

An integer overflow happens when the result of a computation does not fit into the fixed size integer.
The result can be too small or too big to be representable in the fixed size integer.

Task

When a language has fixed size integer types, create a program that
does arithmetic computations for the fixed size integers of the language.

These computations must be done such that the result would overflow.

The program should demonstrate what the following expressions do.

For 32-bit signed integers:

:   :   :   :   :   | Expression | Result that does not fit into a 32-bit signed integer |
                    | --- | --- |
                    | -(-2147483647-1) | 2147483648 |
                    | 2000000000 + 2000000000 | 4000000000 |
                    | -2147483647 - 2147483647 | -4294967294 |
                    | 46341 \* 46341 | 2147488281 |
                    | (-2147483647-1) / -1 | 2147483648 |

For 64-bit signed integers:

:   :   :   | Expression | Result that does not fit into a 64-bit signed integer |
            | --- | --- |
            | -(-9223372036854775807-1) | 9223372036854775808 |
            | 5000000000000000000+5000000000000000000 | 10000000000000000000 |
            | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |
            | 3037000500 \* 3037000500 | 9223372037000250000 |
            | (-9223372036854775807-1) / -1 | 9223372036854775808 |

For 32-bit unsigned integers:

:   :   :   :   :   | Expression | Result that does not fit into a 32-bit unsigned integer |
                    | --- | --- |
                    | -4294967295 | -4294967295 |
                    | 3000000000 + 3000000000 | 6000000000 |
                    | 2147483647 - 4294967295 | -2147483648 |
                    | 65537 \* 65537 | 4295098369 |

For 64-bit unsigned integers:

:   :   :   | Expression | Result that does not fit into a 64-bit unsigned integer |
            | --- | --- |
            | -18446744073709551615 | -18446744073709551615 |
            | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |
            | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |
            | 4294967296 \* 4294967296 | 18446744073709551616 |

Notes
:   * When the integer overflow does trigger an exception show how the exception is caught.
    * When the integer overflow produces some value,   print it.
    * It should be explicitly noted when an integer overflow is not recognized,   the program continues with wrong results.
    * This should be done for signed and unsigned integers of various sizes supported by the computer programming language.
    * When a language has no fixed size integer type,   or when no integer overflow can occur for other reasons,   this should be noted.
    * It is okay to mention,   when a language supports unlimited precision integers,   but this task is NOT the place to demonstrate the
        capabilities of unlimited precision integers.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

The Raku program below does **not** recognize a signed integer overflow and the program **continues with wrong results**.

```
my int64 ($a, $b, $c) = 9223372036854775807, 5000000000000000000, 3037000500;
.say for -(-$a - 1), $b + $b, -$a - $a, $c * $c, (-$a - 1)/-1;

```

Output:

```
-9223372036854775808
-8446744073709551616
2
-9223372036709301616
9223372036854775808
```


[User]
Task

Create a program that computes an approximation of the principal   Nth   root of   X   as the largest integer less than or equal to   R   for which   RN=X.

──where:

```
       N  is a positive integer.
       X  is a non-negative integer.
       R  (the root)   is a non-negative real number.

```

No arbitrary limits should be placed on the magnitudes of the numbers involved.

Example:   With   N=3   and   X=8   you would calculate the number   **2**   because

2

3
=
8
{\displaystyle {\displaystyle 2^{3}=8}}

Example:   With   N=3   and   X=9  you would again calculate the number   **2**   because **2** is the largest integer less than or equal to the root   R.

Example:   With   N=2   and   X=2×1002,000   you would calculate a large integer consisting of the first   2,001   digits (in order) of the square root of two.

[Assistant]
(formerly Perl 6)

**Translation of**: Python

```
sub integer_root ( Int $p where * >= 2, Int $n --> Int ) {
    my Int $d = $p - 1;
    (
      10**($n.chars div $p),
      { ( $d * $^x   +   $n div ($x ** $d) ) div $p } ...
      -> $a, $, $c { $a == $c }
    ).tail(2).min;
}

say integer_root( 2, 2 * 100 ** 2000 );

```

Output:

```
141421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147010955997160597027453459686201472851741864088919860955232923048430871432145083976260362799525140798968725339654633180882964062061525835239505474575028775996172983557522033753185701135437460340849884716038689997069900481503054402779031645424782306849293691862158057846311159666871301301561856898723723528850926486124949771542183342042856860601468247207714358548741556570696776537202264854470158588016207584749226572260020855844665214583988939443709265918003113882464681570826301005948587040031864803421948972782906410450726368813137398552561173220402450912277002269411275736272804957381089675040183698683684507257993647290607629969413804756548237289971803268024744206292691248590521810044598421505911202494413417285314781058036033710773091828693147101711116839165817268894197587165821521282295184884720896946338628915628827659526351405422676532396946175112916024087155101351504553812875600526314680171274026539694702403005174953188629256313851881634780015693691768818523786840522878376293892143006558695686859645951555016447245098368960368873231143894155766510408839142923381132060524336294853170499157717562285497414389991880217624309652065642118273167262575395947172559346372386322614827426222086711558395999265211762526989175409881593486400834570851814722318142040704265090565323333984364578657967965192672923998753666172159825788602633636178274959942194037777536814262177387991945513972312740668983299898953867288228563786977496625199665835257761989393228453447356947949629521688914854925389047558288345260965240965428893945386466257449275563819644103169798330618520193793849400571563337205480685405758679996701213722394758214263065851322174088323829472876173936474678374319600015921888073478576172522118674904249773669292073110963697216089337086611567345853348332952546758516447107578486024636008

```


[User]
Task

Create a program that, when run, would display all integers from   **1**   to     ****∞****     (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time.

An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295.   Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.

If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations—or lack thereof.

[Assistant]
(formerly Perl 6)

```
.say for 1..*
```


[User]
Task

Demonstrate any interactive (or command line) help offered by the language implementation.

This can be for exploring features or syntax, or perhaps a simple message on where to find more information.

[Assistant]
(formerly Perl 6)

Raku help is generally in a specialized text format known as POD (Plain Old Documentation). It is sometimes referred to as POD6 to distinguish it from Perl 5 POD which is slightly different and not completely compatible. Raku has a local command line help app: p6doc. zef install p6doc It also has online browsable HTML documentation at docs.raku.org. If you want to download the HTML docs for a local copy, or just prefer to browse the documentation as a single page docs.raku.org/perl6.html may be more to your preference. If you prefer a different format, there are utilities available to convert the POD docs to several different formats; Markdown, PDF, Latex, plain text, etc.

Individual Raku scripts are to some extent self-documenting. If the script has a MAIN sub, and it is called with improper parameters, it will display an automatically generated help message showing the various possible parameters, which are required, which are optional, and what type each takes:

```
sub MAIN(
    Str $run,             #= Task or file name
    Str :$lang = 'raku',  #= Language, default raku
    Int :$skip = 0,       #= Skip # to jump partially into a list
    Bool :f(:$force),     #= Override any skip parameter
) {
    # do whatever
}

```

When saved locally as main.raku and invoked with no (or wrong) passed parameters:

```
Usage:
  main.raku [--lang=<Str>] [--skip=<Int>] [-f|--force] <run>

    <run>           Task or file name
    --lang=<Str>    Language, default raku
    --skip=<Int>    Skip # to jump partially into a list
    -f|--force      Override any skip parameter

```


[User]
Many language implementations come with an *interactive mode*.

This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.

An interactive mode may also be known as a *command mode*,   a *read-eval-print loop* (REPL),   or a *shell*.

Task

Show how to start this mode.

Then, as a small example of its use, interactively create a function of two strings and a separator that returns the strings separated by two concatenated instances of the separator   (the 3rd argument).

Example

```
             f('Rosetta',  'Code',  ':')

```

should return

```
             'Rosetta::Code'

```

Note

This task is   *not*   about creating your own interactive mode.

[Assistant]
(formerly Perl 6)
Using Rakudo.

```
$ rakudo/perl6
> sub f($str1,$str2,$sep) { $str1~$sep x 2~$str2 };
f
> f("Rosetta","Code",":");
Rosetta::Code
>

```


[User]
A number wheel has:

* A *name* which is an uppercase letter.
* A set of ordered *values* which are either *numbers* or *names*.

A *number* is generated/yielded from a named wheel by:

:   1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel":

    :   1.a If the value is a number, yield it.
    :   1.b If the value is a name, yield the next value from the named wheel
    :   1.c Advance the position of this wheel.

Given the wheel

:   `A: 1 2 3`

the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...

**Note:** When more than one wheel is defined as a set of intersecting wheels then the
first named wheel is assumed to be the one that values are generated from.

Examples

Given the wheels:

```
   A: 1 B 2
   B: 3 4

```

The series of numbers generated starts:

```
   1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...

```

The intersections of number wheels can be more complex, (and might loop forever),
and wheels may be multiply connected.

**Note:** If a named wheel is referenced more than
once by one or many other wheels, then there is only one position of the wheel
that is advanced by each and all references to it.

E.g.

```
 A:  1 D D
 D:  6 7 8
 Generates:
   1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ...

```

Task

Generate and show the first twenty terms of the sequence of numbers generated
from these groups:

```
   Intersecting Number Wheel group:
     A:  1 2 3

   Intersecting Number Wheel group:
     A:  1 B 2
     B:  3 4

   Intersecting Number Wheel group:
     A:  1 D D
     D:  6 7 8

   Intersecting Number Wheel group:
     A:  1 B C
     B:  3 4
     C:  5 B

```

Show your output here, on this page.

[Assistant]
(formerly Perl 6)
A succinct Raku example using a few additional language features. Wheels are implemented as infinite repeating sequences, allowing a single iterator to keep track of the current position. This means the code contains no position tracking whatsoever.

```
#| advance rotates a named wheel $n by consuming an item from an infinite sequence. It is called
#| from within a gather block and so can use take in order to construct an infinite, lazy sequence
#| of result values
sub advance($g, $n) {
	given $g{$n}.pull-one {
		when /\d/ { take $_ }
		default   { samewith $g, $_ } # samewith re-calls this function with new parameters
	}
}

#| Input groups are a hash containing each wheel name as the key, and a list of values constructed
#| using <> to split on whitespace. They are transformed using xx * to repeat the list infinitely.
#| We then retrieve the underlying iterator in order for wheel position to be persistent. Each group
#| is then aggregated into a lazy output sequence using an infinite loop inside a gather block.
[
	{A => <1 2 3>},
	{A => <1 B 2>, B => <3 4>},
	{A => <1 D D>, D => <6 7 8>},
	{A => <1 B C>, B => <3 4>, C => <5 B>},
]
	#| %() converts a list of pairs produced by map into a hash. $^k and $^v are implicit variables.
	#| They are processed in alphabetical order and make the block arity 2, called with two vars.
	#| .kv gets the list of wheel names and wheel values from the input entry
	==> map({ %(.kv.map: { $^k => (|$^v xx *).iterator }) })
	#| gather constructs a lazy sequence, in which we infinitely loop advancing wheel A
	==> map({ gather { loop { advance $_, 'A' }} })
	#| state variables are only initialised once, and are kept between invocations.
	==> map({ state $i = 1; say "Group {$i++}, First 20 values: $_[^20]" })

```

Output:

```
Group 1, First 20 values: 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2
Group 2, First 20 values: 1 3 2 1 4 2 1 3 2 1 4 2 1 3 2 1 4 2 1 3
Group 3, First 20 values: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6
Group 4, First 20 values: 1 3 5 1 4 3 1 4 5 1 3 4 1 3 5 1 4 3 1 4

```


[User]
Task

* verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
* check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute *abs(bloop)*.

Extra credit

* Report the number of integer variables in global scope, and their sum.

[Assistant]
(formerly Perl 6)

```
my $bloop = -123;

if MY::{'$bloop'}.defined and CORE::{'&abs'}.defined { say abs $bloop }

my @ints = ($_ when Int for PROCESS::.values);
say "Number of PROCESS vars of type Int: ", +@ints;
say "PROCESS vars of type Int add up to ", [+] @ints;

```

Output:

```
123
Number of PROCESS vars of type Int: 1
PROCESS vars of type Int add up to 28785
```

Obviously Raku doesn't maintain a lot of global integer variables... :-)

Nevertheless, you can use similar code to access all the variables in any package you like,
such as the GLOBAL package, which typically has absolutely nothing in it. Since the PROCESS package is even more global than GLOBAL, we used that instead. Go figure...


[User]
To build the **inventory sequence**, first take inventory of what numbers are already in the sequence, then, starting with 0 add the count of each number in turn to the end of the sequence. When you reach a number that has a count of **0**, stop, add the **0** to the end of the sequence, and then restart the inventory from **0**.

E.G.
:   Start taking inventory; how many **0**s are there? **0**. Add a **0** to the end of the sequence and restart the inventory. **(0)**

:   How many **0**s are there? **1**. Add a **1** to the end of the sequence. How many **1**s are there? **1**. Add a **1** to the end of the sequence. How many **2**s are there? **0**. Add a **0** to the end of the sequence and restart the inventory. **(0 1 1 0)**

:   *and so on.*

Task

* Find and display the first **100** elements of the sequence.
* Find and display the position and value of the first element greater than or equal to **1000**.

Stretch

* Find and display the position and value of the first element greater than or equal to **2000**, **3000** ... **10,000**.
* Plot a graph of the first **10,000** elements of the sequence.

See also

* OEIS:A342585 - Inventory sequence * Numberphile: The inventory sequence

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

my ($i, %i) = 0;

my @inventory = (^∞).map: {
    my $count = %i{$i} // 0;
    $i = $count ?? $i+1 !! 0;
    ++%i{$count};
    $count
}

say "Inventory sequence, first 100 elements:\n" ~
  @inventory[^100].batch(20)».fmt("%2d").join: "\n";

say '';

for (1..10).map: * × 1000 {
    my $k = @inventory.first: * >= $_, :k;
    printf "First element >= %6s is %6s in position: %s\n",
      .&comma, @inventory[$k].&comma, comma $k;
}

use SVG;
use SVG::Plot;

my @x = ^10000;

'Inventory-raku.svg'.IO.spurt:
 SVG.serialize: SVG::Plot.new(
    background  => 'white',
    width       => 1000,
    height      => 600,
    plot-width  => 950,
    plot-height => 550,
    x           => @x,
    values      => [@inventory[@x],],
    title       => "Inventory Sequence - First {+@x} values (zero indexed)",
).plot: :lines;

```

Output:

```
Inventory sequence, first 100 elements:
 0  1  1  0  2  2  2  0  3  2  4  1  1  0  4  4  4  1  4  0
 5  5  4  1  6  2  1  0  6  7  5  1  6  3  3  1  0  7  9  5
 3  6  4  4  2  0  8  9  6  4  9  4  5  2  1  3  0  9 10  7
 5 10  6  6  3  1  4  2  0 10 11  8  6 11  6  9  3  2  5  3
 2  0 11 11 10  8 11  7  9  4  3  6  4  5  0 12 11 10  9 13

First element >=  1,000 is  1,001 in position: 24,255
First element >=  2,000 is  2,009 in position: 43,301
First element >=  3,000 is  3,001 in position: 61,708
First element >=  4,000 is  4,003 in position: 81,456
First element >=  5,000 is  5,021 in position: 98,704
First element >=  6,000 is  6,009 in position: 121,342
First element >=  7,000 is  7,035 in position: 151,756
First element >=  8,000 is  8,036 in position: 168,804
First element >=  9,000 is  9,014 in position: 184,428
First element >= 10,000 is 10,007 in position: 201,788
```

*converted to a .png to reduce size for display here:*


[User]
An Inverted Index is a data structure used to create full text search.

Task

Given a set of text files, implement a program to create an inverted index.

Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms.

The search index can be in memory.

[Assistant]
(formerly Perl 6)

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

```
sub MAIN (*@files) {
    my %norm;
    do for @files -> $file {
        %norm.push: $file X=> slurp($file).lc.words;
    }
    (my %inv).push: %norm.invert.unique;

    while prompt("Search terms: ").words -> @words {
        for @words -> $word {
            say "$word => {%inv.{$word.lc}//'(not found)'}";
        }
    }
}

```


[User]
**Inverted syntax with conditional expressions**

In traditional syntax conditional expressions are usually shown before the action within a statement or code block:

```
 IF raining=true THEN needumbrella=true
```

In inverted syntax, the action is listed before the conditional expression in the statement or code block:

```
 needumbrella=true IF raining=true
```

**Inverted syntax with assignment**

In traditional syntax, assignments are usually expressed with the variable appearing before the expression:

```
 a = 6
```

In inverted syntax, the expression appears before the variable:

```
 6 = a
```

**Task**

The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.

[Assistant]
(formerly Perl 6)

Raku has statement modifiers:

```
if $guess == 6 { say "Wow! Lucky Guess!" }          # Traditional
say 'Wow! Lucky Guess!' if $guess == 6;             # Inverted
unless $guess == 6 { say "Huh! You Guessed Rong!" } # Traditional
say 'Huh! You Guessed Rong!' unless $guess == 6;    # Inverted

```

Raku can also invert the syntax of loops:

```
while $i { --$i }
--$i while $i;

until $x > 10 { $x++ }
$x++ until $x > 10;

for 1..10 { .say if $_ %% 2 }
.say if $_ %% 2 for 1..10;  # list comprehension

```

Raku has a system of metaoperators that modify the characteristics of normal operators. Among these is the R metaoperator, which is able to reverse the arguments of most infix operators (including user-defined ones).
So a reversed assignment is easy to write:

```
42 R= $_; say $_;   # prints 42

```

Since, much like list operators, assignment loosens the precedence of the following expression to allow comma lists, reverse assignment of a list requires parens where the normal assignment would not:

```
my @a = 1,2,3;
(1,2,3) R= my @a;

```

However, generally in that case you'd use a feed operator anyway, which is like an object pipe, but unlike Unix pipes works in either direction:

```
my @a <== 1,2,3;
1,2,3 ==> my @a;

```

We think this is much more readable than a reversed assignment.

One other interesting inversion is the ability to put the conditional of a repeat loop at either end, with identical test-after semantics:

```
repeat {
    $_ = prompt "Gimme a number: ";
} until /^\d+$/;

repeat until /^\d+$/ {
    $_ = prompt "Gimme a number: ";
}

```

This might seem relatively useless, but it allows a variable to be declared in the conditional that isn't actually set until the loop body:

```
repeat until my $answer ~~ 42 {
    $answer = prompt "Gimme an answer: ";
}

```

This would require a prior declaration (and two extra semicolons, horrors)
if written in the non-inverted form with the conditional at the bottom:

```
my $answer;
repeat {
    $answer = prompt "Gimme an answer: ";
} until $answer ~~ 42;

```

You can't just put the my on the $answer in the block because the conditional is outside the scope of the block, and would not see the declaration.


[User]
Named pipe, or FIFO, is a way of providing inter-process communications (IPC). The task is to demonstrate how it works, create two pipes, say, "in" and "out" (choose suitable names for your system), and write a program that works the two pipes such that:

1. Data written to the "in" FIFO will be discarded except the byte count, which will be added to a total tally kept by the program;
2. Whenever another process reads the "out" FIFO, it should receive the total count so far.

Possible issues:

* Chances are you don't already have "in" and "out" pipes lying around. Create them within your program or without, at your discretion. You may assume they are already created for you.
* Your program may assume it's the sole reader on "in" and the sole writer on "out".
* Read/write operations on pipes are generally blocking. Make your program responsive to both pipes, so that it won't block trying to read the "in" pipe while leaving another process hanging on the other end of "out" pipe indefinitely -- or vice versa. You probably need to either poll the pipes or use multi-threading.
* You may assume other processes using the pipes behave; specificially, your program may assume the process at the other end of a pipe will not unexpectedly break away before you finish reading or writing.

[Assistant]
|  |
| --- |
| This example is **incorrect**. Please fix the code and remove this message.  ***Details:*** Blocks on the read pipe and not able to empty/update the write pipe according to the task requirement |

Couldn't figure out how to get around the IO blockages as per the talk page so any help would be appreciated, thanks in advance.

```
# 20200923 Added Raku programming solution

use NativeCall;
use UUID; # cannot mix File::Temp with mkfifo well so use this as tmpnam

my ($in, $out) = <in out>.map: { "/tmp/$_-" ~ UUID.new } ;

sub mkfifo(Str $pathname, int32 $mode --> int32) is native('libc.so.6') is symbol('mkfifo') {*}

($in,$out).map: { die $!.message if mkfifo($_, 0o666) } ; # c style exit code

say "In  pipe: ", $in;
say "Out pipe: ", $out;

my atomicint $CharCount = 0;

signal(SIGINT).tap: {
   ($in,$out).map: { .IO.unlink or die } ;
   say "\nBye." and exit;
}

loop {
   given $in.IO.watch { # always true even when nothing is spinning ?

      say "Current count: ", $CharCount  ⚛+= $in.IO.open.readchars.codes;

      given $out.IO.open(:update :truncate) { # both truncate and flush aren't
         .flush or die ;                      # working on pipes so without a
         .spurt: "$CharCount\t"               # prior consumer it just appends
      }
      $out.IO.open.close or die;
   }
   sleep ½;
}

```

Output:

Terminal 1

```
named-pipe.raku
In  pipe: /tmp/in-b49e4cdf-80b6-49da-b4a3-2810f1eeeb6a
Out pipe: /tmp/out-44fcd0db-ce02-47b4-bdd3-34833f3dd621
Current count: 5
Current count: 10
Current count: 15
^C
Bye.
```

Terminal 2

```
echo asdf > /tmp/in-b49e4cdf-80b6-49da-b4a3-2810f1eeeb6a
cat /tmp/out-44fcd0db-ce02-47b4-bdd3-34833f3dd621
5       ^C
echo qwer > /tmp/in-b49e4cdf-80b6-49da-b4a3-2810f1eeeb6a
echo uiop > /tmp/in-b49e4cdf-80b6-49da-b4a3-2810f1eeeb6a
cat /tmp/out-44fcd0db-ce02-47b4-bdd3-34833f3dd621
10      15      ^C
```


[User]
Task

Validate the check digit of an ISBN-13 code:

:   :   * Multiply every other digit by  **3**.
        * Add these numbers and the other digits.
        * Take the remainder of this number after division by  **10**.
        * If it is  **0**,   the ISBN-13 check digit is correct.

You might use the following codes for testing:

:   :   :   :   * 978-0596528126       (good)
                * 978-0596528120         (bad)
                * 978-1788399081       (good)
                * 978-1788399083         (bad)

Show output here, on this page

See also
:   * for details:   13-digit ISBN method of validation.       (installs cookies.)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

Also test a value that has a zero check digit.

```
sub check-digit ($isbn) {
     (10 - (sum (|$isbn.comb(/<[0..9]>/)) »*» (1,3)) % 10).substr: *-1
}

{
    my $check = .substr(*-1);
    my $check-digit = check-digit .chop;
    say "$_ : ", $check == $check-digit ??
        'Good' !!
        "Bad check-digit $check; should be $check-digit"
} for words <
    978-0596528126
    978-0596528120
    978-1788399081
    978-1788399083
    978-2-74839-908-0
    978-2-74839-908-5
>;

```

Output:

```
978-0596528126 : Good
978-0596528120 : Bad check-digit 9; should be 2
978-1788399081 : Good
978-1788399083 : Bad check-digit 3; should be 1
978-2-74839-908-0 : Good
978-2-74839-908-5 : Bad check-digit 5; should be 0

```


[User]
Definitions

For the purposes of this task, an **isogram** means a string where each character present is used the same number of times and an **n-isogram** means an isogram where each character present is used exactly **n** times.

A **heterogram** means a string in which no character occurs more than once. It follows that a **heterogram** is the same thing as a **1-isogram**.

Examples

*caucasus* is a **2-isogram** because the letters c, a, u and s all occur twice.

*atmospheric* is a **heterogram** because all its letters are used once only.

Task

Using **unixdict.txt** and ignoring capitalization:

**1)** Find and display here all words which are **n-isograms** where **n > 1**.

Present the results as a single list but sorted as follows:

a. By decreasing order of **n**;

b. Then by decreasing order of word length;

c. Then by ascending lexicographic order.

**2)** Secondly, find and display here all words which are **heterograms** and have more than **10** characters.

Again present the results as a single list but sorted as per b. and c. above.

Reference

* Wikipedia: Heterogram

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]
```
my $file = 'unixdict.txt';

my @words = $file.IO.slurp.words.race.map: { $_ => .comb.Bag };

.say for (6...2).map: -> $n {
    next unless my @iso = @words.race.grep({.value.values.all == $n})».key;
    "\n({+@iso}) {$n}-isograms:\n" ~ @iso.sort({[-.chars, ~$_]}).join: "\n";
}

my $minchars = 10;

say "\n({+$_}) heterograms with more than $minchars characters:\n" ~
  .sort({[-.chars, ~$_]}).join: "\n" given
  @words.race.grep({.key.chars >$minchars && .value.values.max == 1})».key;

```

Output:

```
(2) 3-isograms:
aaa
iii

(31) 2-isograms:
beriberi
bilabial
caucasus
couscous
teammate
appall
emmett
hannah
murmur
tartar
testes
anna
coco
dada
deed
dodo
gogo
isis
juju
lulu
mimi
noon
otto
papa
peep
poop
teet
tete
toot
tutu
ii

(32) heterograms with more than 10 characters:
ambidextrous
bluestocking
exclusionary
incomputable
lexicography
loudspeaking
malnourished
atmospheric
blameworthy
centrifugal
christendom
consumptive
countervail
countryside
countrywide
disturbance
documentary
earthmoving
exculpatory
geophysical
inscrutable
misanthrope
problematic
selfadjoint
stenography
sulfonamide
switchblade
switchboard
switzerland
thunderclap
valedictory
voluntarism
```


[User]
Sometimes a function is needed to find the integer square root of   **X**,   where   **X**   can be a
real non─negative number.

Often   **X**   is actually a non─negative integer.

For the purposes of this task,   **X**   can be an integer or a real number,   but if it
simplifies things in your computer programming language,   assume it's an integer.

One of the most common uses of   **`Isqrt`**   is in the division of an integer by all factors   (or
primes)   up to the
√ X     of that
integer,   either to find the factors of that integer,   or to determine primality.

An alternative method for finding the   **`Isqrt`**   of a number is to
calculate:        floor( sqrt(X) )

:   :   * where   **sqrt**    is the   square root   function for non─negative real numbers,   and
        * where   **floor**   is the   floor   function for real numbers.

If the hardware supports the computation of (real) square roots,   the above method might be a faster method for
small numbers that don't have very many significant (decimal) digits.

However, floating point arithmetic is limited in the number of   (binary or decimal)   digits that it can support.

Pseudo─code using quadratic residue

For this task, the integer square root of a non─negative number will be computed using a version
of   *quadratic residue*,   which has the advantage that no   *floating point*   calculations are
used,   only integer arithmetic.

Furthermore, the two divisions can be performed by bit shifting,   and the one multiplication can also be be performed by bit shifting or additions.

The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.

Pseudo─code of a procedure for finding the integer square root of   **X**       (all variables are integers):

```
         q ◄── 1                                /*initialize  Q  to unity.  */
                                  /*find a power of 4 that's greater than X.*/
                  perform  while q <= x         /*perform while  Q <= X.    */
                  q ◄── q * 4                   /*multiply  Q  by  four.    */
                  end  /*perform*/
                                                /*Q  is now greater than  X.*/
         z ◄── x                                /*set  Z  to the value of X.*/
         r ◄── 0                                /*initialize  R  to zero.   */
                  perform  while q > 1          /*perform while  Q > unity. */
                  q ◄── q ÷ 4                   /*integer divide by  four.  */
                  t ◄── z - r - q               /*compute value of  T.      */
                  r ◄── r ÷ 2                   /*integer divide by  two.   */
                  if t >= 0  then do
                                  z ◄── t       /*set  Z  to value of  T.   */
                                  r ◄── r + q   /*compute new value of  R.  */
                                  end
                  end  /*perform*/
                                                /*R  is now the  Isqrt(X).  */

         /* Sidenote: Also, Z is now the remainder after square root (i.e.  */
         /*           R^2 + Z = X, so if Z = 0 then X is a perfect square). */

```

Another version for the (above)   1st   **perform**   is:

```
                  perform  until q > X          /*perform until  Q > X.     */
                  q ◄── q * 4                   /*multiply  Q  by  four.    */
                  end  /*perform*/

```

Integer square roots of some values:

```
Isqrt( 0)  is   0               Isqrt(60)  is  7                Isqrt( 99)  is   9
Isqrt( 1)  is   1               Isqrt(61)  is  7                Isqrt(100)  is  10
Isqrt( 2)  is   1               Isqrt(62)  is  7                Isqrt(102)  is  10
Isqrt( 3)  is   1               Isqrt(63)  is  7
Isqrt( 4)  is   2               Isqrt(64)  is  8                Isqet(120)  is  10
Isqrt( 5)  is   2               Isqrt(65)  is  8                Isqrt(121)  is  11
Isqrt( 6)  is   2               Isqrt(66)  is  8                Isqrt(122)  is  11
Isqrt( 7)  is   2               Isqrt(67)  is  8
Isqrt( 8)  is   2               Isqrt(68)  is  8                Isqrt(143)  is  11
Isqrt( 9)  is   3               Isqrt(69)  is  8                Isqrt(144)  is  12
Isqrt(10)  is   3               Isqrt(70)  is  8                Isqrt(145)  is  12

```

Task

Compute and show all output here   (on this page)   for:

:   :   * the `Isqrt` of the     integers     from     **0** ───► **65**    (inclusive), shown in a horizontal format.
        * the `Isqrt` of the   odd powers  from   **71** ───► **773**   (inclusive), shown in a   vertical   format.
        * use commas in the displaying of larger numbers.

You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.

If your computer programming language only supports smaller integers,   show what you can.

Related tasks
:   * sequence of non-squares
    * integer roots
    * square root by hand

[Assistant]
There is a task Integer roots that covers a similar operation, with the caveat that it will calculate **any** nth root (including 2) not just **square** roots.

See the Integer roots Raku entry.

Quadratic residue algorithm follows:

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

sub isqrt ( \x ) { my ( $X, $q, $r, $t ) =  x, 1, 0 ;
    $q +<= 2 while $q ≤ $X ;
    while $q > 1 {
        $q +>= 2; $t = $X - $r - $q; $r +>= 1;
        if $t ≥ 0 { $X = $t; $r += $q }
    }
    $r
}

say (^66)».&{ isqrt $_ }.Str ;

(1, 3…73)».&{ "7**$_: " ~ comma(isqrt 7**$_) }».say

```

Output:

```
0 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8
7**1: 2
7**3: 18
7**5: 129
7**7: 907
7**9: 6,352
7**11: 44,467
7**13: 311,269
7**15: 2,178,889
7**17: 15,252,229
7**19: 106,765,608
7**21: 747,359,260
7**23: 5,231,514,822
7**25: 36,620,603,758
7**27: 256,344,226,312
7**29: 1,794,409,584,184
7**31: 12,560,867,089,291
7**33: 87,926,069,625,040
7**35: 615,482,487,375,282
7**37: 4,308,377,411,626,977
7**39: 30,158,641,881,388,842
7**41: 211,110,493,169,721,897
7**43: 1,477,773,452,188,053,281
7**45: 10,344,414,165,316,372,973
7**47: 72,410,899,157,214,610,812
7**49: 506,876,294,100,502,275,687
7**51: 3,548,134,058,703,515,929,815
7**53: 24,836,938,410,924,611,508,707
7**55: 173,858,568,876,472,280,560,953
7**57: 1,217,009,982,135,305,963,926,677
7**59: 8,519,069,874,947,141,747,486,745
7**61: 59,633,489,124,629,992,232,407,216
7**63: 417,434,423,872,409,945,626,850,517
7**65: 2,922,040,967,106,869,619,387,953,625
7**67: 20,454,286,769,748,087,335,715,675,381
7**69: 143,180,007,388,236,611,350,009,727,669
7**71: 1,002,260,051,717,656,279,450,068,093,686
7**73: 7,015,820,362,023,593,956,150,476,655,802
```


[User]
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:

```
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
```

An example in Python:

```
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]

```

Task
:   Count how many number chains for integers 1 <= n < 100\_000\_000 end with a value 89.

Or, for much less credit - (showing that your algorithm and/or language is slow):

:   Count how many number chains for integers 1 <= n < 1\_000\_000 end with a value 89.

This problem derives from the Project Euler problem 92.

For a quick algorithm for this task see the talk page

Related tasks

* Combinations with repetitions
* Digital root
* Digital root/Multiplicative digital root
* Happy numbers

[Assistant]
(formerly Perl 6)
This fairly abstract version does caching and filtering to reduce the number of values it needs to check and moves calculations out of the hot loop, but is still interminably slow... even for just up to 1,000,000.

```
constant @sq = ^10 X** 2;
my $cnt = 0;

sub Euler92($n) {
    $n == any(1,89) ?? $n !!
    (state %){$n} //= Euler92( [+] @sq[$n.comb] )
}

for 1 .. 1_000_000 -> $n {
   my $i = +$n.comb.sort.join;
   ++$cnt if Euler92($i) == 89;
}

say $cnt;

```

Output:

```
856929
```

All is not lost, however. Through the use of gradual typing, Raku scales down as well as up, so this jit-friendly version is performant enough to brute force the larger calculation:

```
my @cache;
@cache[1] = 1;
@cache[89] = 89;

sub Euler92(int $n) {
    $n < 649  # 99,999,999 sums to 648, so no point remembering more
        ?? (@cache.AT-POS($n) //= ids($n))
        !! ids($n)
}

sub ids(int $num --> int) {
    my int $n = $num;
    my int $ten = 10;
    my int $sum = 0;
    my int $t;
    my int $c;
    repeat until $n == 89 or $n == 1 {
        $sum = 0;
        repeat {
            $t = $n div $ten;
            $c = $n - $t * $ten;
            $sum = $sum + $c * $c;
        } while $n = $t;
        $n = @cache.AT-POS($sum) // $sum;
    }
    $n;
}

my int $cnt = 0;
for 1 .. 100_000_000 -> int $n {
   $cnt = $cnt + 1 if Euler92($n) == 89;
}
say $cnt;

```

Output:

```
85744333
```

Which is better, but is still pretty slow.

The biggest gains are often from choosing the right algorithm.

```
sub endsWithOne($n --> Bool) {
    my $digit;
    my $sum = 0;
    my $nn = $n;
    loop {
        while $nn > 0 {
            $digit = $nn % 10;
            $sum += $digit²;
            $nn = $nn div 10;
        }
        return True  if $sum == 1;
        return False if $sum == 89;
        $nn = $sum;
        $sum = 0;
    }
}

my $k = 8; # 10**8
my @sums is default(0) = 1,0;
my $s;
for 1 .. $k -> $n {
    for $n*81 … 1 -> $i {
        for 1 .. 9 -> $j {
            $s = $j²;
            last if $s > $i;
            @sums[$i] += @sums[$i - $s];
        }
    }
}

my $ends-with-one = sum flat @sums[(1 .. $k*81).grep: { endsWithOne($_) }], +endsWithOne(10**$k);

say 10**$k - $ends-with-one;

```

Output:

```
85744333
```


[User]
Iterators are a design pattern that can be used to access elements of a container without depending on the
implementation or type of the container.

Task

* Create an array like container to hold the days of the week and a linked-list like container to hold colors.
* Print all of the elements of each container.
* Print the first, fourth, and fifth elements of each container.
* Print the last, fourth to last, and fifth to last of each container.

If you language supports iterators, use them. Otherwise show how access to elements can be
separated from the containers that hold them.

[Assistant]
Raku has iterators, but is rare for casual users to ever explicitly use them. Operators and functions that are designed to work on Iterable objects generally have the iteration semantics built in; so don't need an iterator to be explicitly called. It is far, **far** more common to use object slices to do the task example operations.

Rakus iterators are one direction only (not reversible), since they are designed to be able to work with infinite streams. It is difficult to reverse a stream that has no end. If the object / collection is finite, it may be reversed, but that is a separate operation from iteration.

Once an iteration has been reified, it is discarded unless explicitly cached. This allows effortless iteration through multi-gigabyte sized data objects and streams without filling up main memory.

The following example iterates though a hash of Positional Iterable objects and demonstrates both using explicit iterators, and object slice operations on each; then has a semi contrived example of where directly using iterators may be actually useful in Raku; collating unique ascending values from several infinite sequence generators.

```
my %positional-iterable-types =
    array    => [<Sunday Monday Tuesday Wednesday Thursday Friday Saturday>],
    list     => <Red Orange Yellow Green Blue Purple>,
    range    => 'Rako' .. 'Raky',
    sequence => (1.25, 1.5, * × * … * > 50),
;

sub first-fourth-fifth ($iterable) {
    my $iterator = $iterable.iterator;
    gather {
        take $iterator.pull-one;
        $iterator.skip-one xx 2;
        take $iterator.pull-one;
        take $iterator.pull-one;
    }
}

say "Note: here we are iterating over the %positional-iterable-types hash, but
the order we get elements out is not the same as the order they were inserted.
Hashes are not guaranteed to be in any specific order, in fact, they are
guaranteed to _not_ be in any specific order.";

for %positional-iterable-types.values {
    say "\nType " ~ .^name ~ ', contents: ' ~ $_ ~
    "\nUsing iterators    : first, fourth and fifth from start: " ~ first-fourth-fifth($_) ~ ', and from end: ' ~ first-fourth-fifth(.reverse) ~
    "\nUsing object slices: first, fourth and fifth from start: " ~ .[0, 3, 4] ~ ', and from end: ' ~ .[*-1, *-4, *-5] ~ "\n";
};

say "\nWhere iterators really shine; when you are collating the values from several infinite generators.";
my @i = (1, * × 2 … *).iterator, (1, * × 3 … *).iterator, (1, * × 5 … *).iterator;
my @v = @i[0].pull-one, @i[1].pull-one, @i[2].pull-one;

my @seq = lazy gather loop {
    take my $min := @v.min;
    for ^@v { @v[$_] = @i[$_].pull-one if @v[$_] == $min };
}

say @seq[^25];

```

Output:

```
Note: here we are iterating over the %positional-iterable-types hash, but
the order we get elements out is not the same as the order they were inserted.
Hashes are not guaranteed to be in any specific order, in fact, they are
guaranteed to _not_ be in any specific order.

Type Range, contents: Rako Rakp Rakq Rakr Raks Rakt Raku Rakv Rakw Rakx Raky
Using iterators    : first, fourth and fifth from start: Rako Rakr Raks, and from end: Raky Rakv Raku
Using object slices: first, fourth and fifth from start: Rako Rakr Raks, and from end: Raky Rakv Raku

Type Seq, contents: 1.25 1.5 1.875 2.8125 5.273438 14.831543 78.2132149
Using iterators    : first, fourth and fifth from start: 1.25 2.8125 5.273438, and from end: 78.2132149 2.8125 1.875
Using object slices: first, fourth and fifth from start: 1.25 2.8125 5.273438, and from end: 78.2132149 2.8125 1.875

Type Array, contents: Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Using iterators    : first, fourth and fifth from start: Sunday Wednesday Thursday, and from end: Saturday Wednesday Tuesday
Using object slices: first, fourth and fifth from start: Sunday Wednesday Thursday, and from end: Saturday Wednesday Tuesday

Type List, contents: Red Orange Yellow Green Blue Purple
Using iterators    : first, fourth and fifth from start: Red Green Blue, and from end: Purple Yellow Orange
Using object slices: first, fourth and fifth from start: Red Green Blue, and from end: Purple Yellow Orange

Where iterators really shine; when you are collating the values from several infinite generators.
(1 2 3 4 5 8 9 16 25 27 32 64 81 125 128 243 256 512 625 729 1024 2048 2187 3125 4096)
```


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

The **Jaccard index**, also known as the **Jaccard similarity coefficient**, is a statistic used for gauging the similarity and diversity of sample sets. It was developed by Paul Jaccard, originally giving the French name *coefficient de communauté*, and independently formulated again by T. Tanimoto. Thus, the **Tanimoto index** or **Tanimoto coefficient** are also used in some fields. However, they are identical in generally taking the ratio of **Intersection over Union**. The Jaccard coefficient measures similarity between finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets:

:   J(A, B) = |A ∩ B|/|A ∪ B|

Define sets as follows, using any linear data structure:

```
A = {}
B = {1, 2, 3, 4, 5}
C = {1, 3, 5, 7, 9}
D = {2, 4, 6, 8, 10}
E = {2, 3, 5, 7}
F = {8}

```

Write a program that computes the Jaccard index for every ordered pairing (to show that J(A, B) and J(B, A) are the same) of these sets, including self-pairings.

[Assistant]
```
sub J(\A, \B) { A ∪ B ?? (A ∩ B) / (A ∪ B) !! A ∪ B == A ∩ B ?? 1 !! 0 }

my %p =
  A => < >,
  B => <1 2 3 4 5>,
  C => <1 3 5 7 9>,
  D => <2 4 6 8 10>,
  E => <2 3 5 7>,
  F => <8>,
;

.say for %p.sort;
say '';
say "J({.join: ','}) = ", J |%p{$_} for [X] <A B C D E F> xx 2;

```

Output:

```
A => ()
B => (1 2 3 4 5)
C => (1 3 5 7 9)
D => (2 4 6 8 10)
E => (2 3 5 7)
F => 8

J(A,A) = 1
J(A,B) = 0
J(A,C) = 0
J(A,D) = 0
J(A,E) = 0
J(A,F) = 0
J(B,A) = 0
J(B,B) = 1
J(B,C) = 0.428571
J(B,D) = 0.25
J(B,E) = 0.5
J(B,F) = 0
J(C,A) = 0
J(C,B) = 0.428571
J(C,C) = 1
J(C,D) = 0
J(C,E) = 0.5
J(C,F) = 0
J(D,A) = 0
J(D,B) = 0.25
J(D,C) = 0
J(D,D) = 1
J(D,E) = 0.125
J(D,F) = 0.2
J(E,A) = 0
J(E,B) = 0.5
J(E,C) = 0.5
J(E,D) = 0.125
J(E,E) = 1
J(E,F) = 0
J(F,A) = 0
J(F,B) = 0
J(F,C) = 0
J(F,D) = 0.2
J(F,E) = 0
J(F,F) = 1
```


[User]
The **Jacobi symbol** is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p\_i)^(k\_i), where n = p\_1^(k\_1)\*p\_2^(k\_2)\*...\*p\_i^(k\_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)

* (a | p) ≡   1     if a is a square (mod p)
* (a | p) ≡ -1     if a is not a square (mod p)
* (a | p) ≡   0     if a ≡ 0

If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).

Task

Calculate the Jacobi symbol (a | n).

Reference

* Wikipedia article on Jacobi symbol.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

```
# Jacobi function
sub infix:<J> (Int $k is copy, Int $n is copy where * % 2) {
    $k %= $n;
    my $jacobi = 1;
    while $k {
        while $k %% 2 {
            $k div= 2;
            $jacobi *= -1 if $n % 8 == 3 | 5;
        }
        ($k, $n) = $n, $k;
        $jacobi *= -1 if 3 == $n%4 & $k%4;
        $k %= $n;
    }
    $n == 1 ?? $jacobi !! 0
}

# Testing

my $maxa = 30;
my $maxn = 29;

say 'n\k ', (1..$maxa).fmt: '%3d';
say '   ', '-' x 4 * $maxa;
for 1,*+2 … $maxn -> $n {
    print $n.fmt: '%3d';
    for 1..$maxa -> $k {
        print ($k J $n).fmt: '%4d';
    }
    print "\n";
}

```

Output:

```
n\k   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30
   ------------------------------------------------------------------------------------------------------------------------
  1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
  3   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0
  5   1  -1  -1   1   0   1  -1  -1   1   0   1  -1  -1   1   0   1  -1  -1   1   0   1  -1  -1   1   0   1  -1  -1   1   0
  7   1   1  -1   1  -1  -1   0   1   1  -1   1  -1  -1   0   1   1  -1   1  -1  -1   0   1   1  -1   1  -1  -1   0   1   1
  9   1   1   0   1   1   0   1   1   0   1   1   0   1   1   0   1   1   0   1   1   0   1   1   0   1   1   0   1   1   0
 11   1  -1   1   1   1  -1  -1  -1   1  -1   0   1  -1   1   1   1  -1  -1  -1   1  -1   0   1  -1   1   1   1  -1  -1  -1
 13   1  -1   1   1  -1  -1  -1  -1   1   1  -1   1   0   1  -1   1   1  -1  -1  -1  -1   1   1  -1   1   0   1  -1   1   1
 15   1   1   0   1   0   0  -1   1   0   0  -1   0  -1  -1   0   1   1   0   1   0   0  -1   1   0   0  -1   0  -1  -1   0
 17   1   1  -1   1  -1  -1  -1   1   1  -1  -1  -1   1  -1   1   1   0   1   1  -1   1  -1  -1  -1   1   1  -1  -1  -1   1
 19   1  -1  -1   1   1   1   1  -1   1  -1   1  -1  -1  -1  -1   1   1  -1   0   1  -1  -1   1   1   1   1  -1   1  -1   1
 21   1  -1   0   1   1   0   0  -1   0  -1  -1   0  -1   0   0   1   1   0  -1   1   0   1  -1   0   1   1   0   0  -1   0
 23   1   1   1   1  -1   1  -1   1   1  -1  -1   1   1  -1  -1   1  -1   1  -1  -1  -1  -1   0   1   1   1   1  -1   1  -1
 25   1   1   1   1   0   1   1   1   1   0   1   1   1   1   0   1   1   1   1   0   1   1   1   1   0   1   1   1   1   0
 27   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0   1  -1   0
 29   1  -1  -1   1   1   1   1  -1   1  -1  -1  -1   1  -1  -1   1  -1  -1  -1   1  -1   1   1   1   1  -1  -1   1   0   1
```


[User]
**Jacobsthal numbers** are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1.

```

   J0 = 0
   J1 = 1
   Jn = Jn-1 + 2 × Jn-2

```

Terms may be calculated directly using one of several possible formulas:

```

   Jn = ( 2n - (-1)n ) / 3

```

**Jacobsthal-Lucas numbers** are very similar. They have the same recurrence relationship, the only difference is an initial starting value **J0 = 2** rather than **J0 = 0**.

Terms may be calculated directly using one of several possible formulas:

```

   JLn = 2n + (-1)n

```

**Jacobsthal oblong numbers** is the sequence obtained from multiplying each **Jacobsthal number** **Jn** by its direct successor **Jn+1**.

**Jacobsthal primes** are **Jacobsthal numbers** that are prime.

Task

* Find and display the first 30 **Jacobsthal numbers**
* Find and display the first 30 **Jacobsthal-Lucas numbers**
* Find and display the first 20 **Jacobsthal oblong numbers**
* Find and display at least the first 10 **Jacobsthal primes**

See also

* Wikipedia: Jacobsthal number * Numbers Aplenty - Jacobsthal number * OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers) * OEIS:A014551 - Jacobsthal-Lucas numbers. * OEIS:A084175 - Jacobsthal oblong numbers * OEIS:A049883 - Primes in the Jacobsthal sequence * Related task: Fibonacci sequence * Related task: Leonardo numbers

[Assistant]
```
my $jacobsthal = cache lazy 0, 1, * × 2 + * … *;
my $jacobsthal-lucas = lazy 2, 1, * × 2 + * … *;

say "First 30 Jacobsthal numbers:";
say $jacobsthal[^30].batch(5)».fmt("%9d").join: "\n";

say "\nFirst 30 Jacobsthal-Lucas numbers:";
say $jacobsthal-lucas[^30].batch(5)».fmt("%9d").join: "\n";

say "\nFirst 20 Jacobsthal oblong numbers:";
say (^∞).map( { $jacobsthal[$_] × $jacobsthal[$_+1] } )[^20].batch(5)».fmt("%11d").join: "\n";

say "\nFirst 20 Jacobsthal primes:";
say $jacobsthal.grep( &is-prime )[^20].join: "\n";

```

Output:

```
First 30 Jacobsthal numbers:
        0         1         1         3         5
       11        21        43        85       171
      341       683      1365      2731      5461
    10923     21845     43691     87381    174763
   349525    699051   1398101   2796203   5592405
 11184811  22369621  44739243  89478485 178956971

First 30 Jacobsthal-Lucas numbers:
        2         1         5         7        17
       31        65       127       257       511
     1025      2047      4097      8191     16385
    32767     65537    131071    262145    524287
  1048577   2097151   4194305   8388607  16777217
 33554431  67108865 134217727 268435457 536870911

First 20 Jacobsthal oblong numbers:
          0           1           3          15          55
        231         903        3655       14535       58311
     232903      932295     3727815    14913991    59650503
  238612935   954429895  3817763271 15270965703 61084037575

First 20 Jacobsthal primes:
3
5
11
43
683
2731
43691
174763
2796203
715827883
2932031007403
768614336404564651
201487636602438195784363
845100400152152934331135470251
56713727820156410577229101238628035243
62357403192785191176690552862561408838653121833643
1046183622564446793972631570534611069350392574077339085483
267823007376498379256993682056860433753700498963798805883563
5562466239377370006237035693149875298444543026970449921737087520370363869220418099018130434731
95562442332919646317117537304253622533190207882011713489066201641121786503686867002917439712921903606443
```


[User]
The Jaro distance is a measure of edit distance between two strings; its inverse, called the *Jaro similarity*, is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   **0**   equates to no similarities and   **1**   is an exact match.

Definition

The Jaro similarity

d

j
{\displaystyle {\displaystyle d\_{j}}}
   of two given strings

s

1
{\displaystyle {\displaystyle s\_{1}}}
   and

s

2
{\displaystyle {\displaystyle s\_{2}}}
   is

:   d

    j
    =

    {

    0

    if
    m
    =
    0

    1
    3

    (

    m

    |

    s

    1

    |
    +

    m

    |

    s

    2

    |
    +

    m
    −
    t
    m
    )

    otherwise

    {\displaystyle {\displaystyle d\_{j}=\left\{{\begin{array}{l l}0&{\text{if }}m=0\\{\frac {1}{3}}\left({\frac {m}{|s\_{1}|}}+{\frac {m}{|s\_{2}|}}+{\frac {m-t}{m}}\right)&{\text{otherwise}}\end{array}}\right.}}

Where:

* m
  {\displaystyle {\displaystyle m}}
     is the number of *matching characters*;
* t
  {\displaystyle {\displaystyle t}}
     is half the number of *transpositions*.

Two characters from

s

1
{\displaystyle {\displaystyle s\_{1}}}
   and

s

2
{\displaystyle {\displaystyle s\_{2}}}
   respectively, are considered *matching* only if they are the same and not farther apart than

⌊

max
(

|

s

1

|
,

|

s

2

|
)
2
⌋
−
1
{\displaystyle {\displaystyle \left\lfloor {\frac {\max(|s\_{1}|,|s\_{2}|)}{2}}\right\rfloor -1}}
 characters.

Each character of

s

1
{\displaystyle {\displaystyle s\_{1}}}
   is compared with all its matching characters in

s

2
{\displaystyle {\displaystyle s\_{2}}}
. Each difference in position is half a *transposition*; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.

Example

Given the strings

s

1
{\displaystyle {\displaystyle s\_{1}}}
   *DWAYNE*   and

s

2
{\displaystyle {\displaystyle s\_{2}}}
   *DUANE*   we find:

* m
  =
  4
  {\displaystyle {\displaystyle m=4}}
* |

  s

  1

  |
  =
  6
  {\displaystyle {\displaystyle |s\_{1}|=6}}
* |

  s

  2

  |
  =
  5
  {\displaystyle {\displaystyle |s\_{2}|=5}}
* t
  =
  0
  {\displaystyle {\displaystyle t=0}}

We find a Jaro score of:

:   d

    j
    =

    1
    3

    (

    4
    6
    +

    4
    5
    +

    4
    −
    0
    4
    )
    =
    0.822
    {\displaystyle {\displaystyle d\_{j}={\frac {1}{3}}\left({\frac {4}{6}}+{\frac {4}{5}}+{\frac {4-0}{4}}\right)=0.822}}

Task

Implement the Jaro algorithm and show the similarity scores for each of the following pairs:

* ("MARTHA", "MARHTA")
* ("DIXON", "DICKSONX")
* ("JELLYFISH", "SMELLYFISH")

See also

* Jaro–Winkler distance on Wikipedia.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

```
sub jaro ($s, $t) {
    return 1 if $s eq $t;

    my $s-len = + my @s = $s.comb;
    my $t-len = + my @t = $t.comb;
    my $match-distance = ($s-len max $t-len) div 2 - 1;

    my ($matches, @s-matches, @t-matches);
    for ^@s -> $i {
        my $start = 0 max $i - $match-distance;
        my $end   = $i + $match-distance min ($t-len - 1);

        for $start .. $end -> $j {
            next if @t-matches[$j] or @s[$i] ne @t[$j];
            (@s-matches[$i], @t-matches[$j]) = (1, 1);
            $matches++ and last;
        }
    }
    return 0 unless $matches;

    my ($k, $transpositions) = (0, 0);
    for ^@s -> $i {
        next unless @s-matches[$i];
        $k++ until  @t-matches[$k];
        $transpositions++ if @s[$i] ne @t[$k];
        $k++;
    }

    ( $matches/$s-len + $matches/$t-len + (($matches - $transpositions/2) / $matches) ) / 3
}

say jaro(.key, .value).fmt: '%.3f' for
    'MARTHA' => 'MARHTA', 'DIXON' => 'DICKSONX', 'JELLYFISH' => 'SMELLYFISH',
    'I repeat myself' => 'I repeat myself', '' => '';

```

Output:

```
0.944
0.767
0.896
1.000
1.000
```


[User]
The Jaro-Winkler distance is a metric for measuring the edit distance between words.
It is similar to the more basic Levenshtein distance but the Jaro distance also accounts
for transpositions between letters in the words. With the Winkler modification to the Jaro
metric, the Jaro-Winkler distance also adds an increase in similarity for words which
start with the same letters (prefix).

The Jaro-Winkler distance is a modification of the Jaro similarity metric, which
measures the similarity between two strings. The Jaro similarity is 1.0 when strings are
identical and 0 when strings have no letters in common. Distance measures such as the
Jaro distance or Jaro-Winkler distance, on the other hand, are 0 when strings are
identical and 1 when they have no letters in common.

The Jaro similarity between two strings s1 and s2, simj, is defined as

:   simj = 0     if m is 0.
:   simj = ( (m / length of s1) + (m / length of s2) + (m - t) / m ) / 3     otherwise.

Where:

* m
  {\displaystyle {\displaystyle m}}
     is the number of *matching characters (the same character within max(|s1|, |s2|)/2 - 1 of one another)*;
* t
  {\displaystyle {\displaystyle t}}
     is half the number of *transpositions (a shared character placed in different positions)*.

The Winkler modification to Jaro is to check for identical prefixes of the strings.

If we define the number of initial (prefix) characters in common as:

*l* = the length of a common prefix between strings, up to 4 characters

and, additionally, select a multiplier (Winkler suggested 0.1) for the relative importance of the
prefix for the word similarity:

*p*    =   0.1

The Jaro-Winkler similarity can then be defined as

simw = simj + *l**p*(1 - simj)

Where:

* simj   is the Jaro similarity.
* *l*   is the number of matching characters at the beginning of the strings, up to 4.
* *p*   is a factor to modify the amount to which the prefix similarity affects the metric.

Winkler suggested this be 0.1.

The Jaro-Winkler distance between strings, which is 0.0 for identical strings, is then defined as

dw = 1 - simw

String metrics such as Jaro-Winkler distance are useful in applications such as spelling checkers,
because letter transpositions are common typing errors and humans tend to misspell the middle portions
of words more often than their beginnings. This may help a spelling checker program to generate
better alternatives for misspelled word replacement.

The task

Using a dictionary of your choice and the following list of 9 commonly misspelled words:

"accomodate", "definately", "goverment", "occured", "publically", "recieve", "seperate", "untill", "wich"

* Calculate the Jaro-Winkler distance between the misspelled word and words in the dictionary.

* Use this distance to list close alternatives (at least two per word) to the misspelled words.

* Show the calculated distances between the misspelled words and their potential replacements.

See also
:   * Wikipedia page: Jaro–Winkler distance.
    * Comparing string similarity algorithms. Comparison of algorithms on Medium

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

A minor modification of the Jaro distance task entry.

using the unixdict.txt file from www.puzzlers.org

```
sub jaro-winkler ($s, $t) {

    return 0 if $s eq $t;

    my $s_len = + my @s = $s.comb;
    my $t_len = + my @t = $t.comb;

    my $match_distance = ($s_len max $t_len) div 2 - 1;

    my @s_matches;
    my @t_matches;
    my $matches = 0;

    for ^@s -> $i {

        my $start = 0 max $i - $match_distance;
        my $end = $i + $match_distance min ($t_len - 1);

        for $start .. $end -> $j {
            @t_matches[$j] and next;
            @s[$i] eq @t[$j] or next;
            @s_matches[$i] = 1;
            @t_matches[$j] = 1;
            $matches++;
            last;
        }
    }

    return 1 if $matches == 0;

    my $k              = 0;
    my $transpositions = 0;

    for ^@s -> $i {
        @s_matches[$i] or next;
        until @t_matches[$k] { ++$k }
        @s[$i] eq @t[$k] or ++$transpositions;
        ++$k;
    }

    my $prefix = 0;

    ++$prefix if @s[$_] eq @t[$_] for ^(min 4, $s_len, $t_len);

    my $jaro = ($matches / $s_len + $matches / $t_len +
        (($matches - $transpositions / 2) / $matches)) / 3;

    1 - ($jaro + $prefix * .1 * ( 1 - $jaro) )
}

my @words =  './unixdict.txt'.IO.slurp.words;

for <accomodate definately goverment occured publically recieve seperate untill wich>
   -> $word {

   my %result = @words.race.map: { $_ => jaro-winkler($word, $_) };

   say "\nClosest 5 dictionary words with a Jaro-Winkler distance < .15 from $word:";

   printf "%15s : %0.4f\n", .key, .value for %result.grep({ .value < .15 }).sort({+.value, ~.key}).head(5);
}

```

Output:

```
Closest 5 dictionary words with a Jaro-Winkler distance < .15 from accomodate:
    accommodate : 0.0182
      accordant : 0.1044
       accolade : 0.1136
      acclimate : 0.1219
    accompanist : 0.1327

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from definately:
         define : 0.0800
       definite : 0.0850
        defiant : 0.0886
     definitive : 0.1200
      designate : 0.1219

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from goverment:
         govern : 0.0667
       governor : 0.1167
      governess : 0.1175
     governance : 0.1330
       coverlet : 0.1361

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from occured:
       occurred : 0.0250
          occur : 0.0571
      occurrent : 0.0952
        occlude : 0.1056
      concurred : 0.1217

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from publically:
         public : 0.0800
    publication : 0.1327
           pull : 0.1400
       pullback : 0.1492

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from recieve:
        receive : 0.0333
        relieve : 0.0667
          reeve : 0.0762
      receptive : 0.0852
      recessive : 0.0852

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from seperate:
      desperate : 0.0708
       separate : 0.0917
      temperate : 0.1042
       selenate : 0.1167
           sept : 0.1167

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from untill:
          until : 0.0333
           till : 0.1111
     huntsville : 0.1333
        instill : 0.1357
         unital : 0.1422

Closest 5 dictionary words with a Jaro-Winkler distance < .15 from wich:
          winch : 0.0533
          witch : 0.0533
          which : 0.0600
        wichita : 0.0857
         switch : 0.1111
```


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

This task is an exercise in call by name.

**Jensen's Device** is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report.

The following program was proposed to illustrate the technique. It computes the 100th harmonic number:

```
begin
   integer i;
   real procedure sum (i, lo, hi, term);
      value lo, hi;
      integer i, lo, hi;
      real term;
      comment term is passed by-name, and so is i;
   begin
      real temp;
      temp := 0;
      for i := lo step 1 until hi do
         temp := temp + term;
      sum := temp
   end;
   comment note the correspondence between the mathematical notation and the call to sum;
   print (sum (i, 1, 100, 1/i))
end

```

The above exploits call by name to produce the correct answer (5.187...). It depends on the assumption that an expression passed as an actual parameter to a procedure would be re-evaluated in the caller's context every time the corresponding formal parameter's value was required. If the last parameter to *sum* had been passed by value, and assuming the initial value of *i* were 1, the result would have been 100 × 1/1 = 100.

Moreover, the *first* parameter to *sum*, representing the "bound" variable of the summation, must also be passed by name (or at least by reference), otherwise changes to it (made within *sum*) would not be visible in the caller's context when computing each of the values to be added.
(On the other hand, the global variable does not have to use the same identifier, in this case *i*, as the formal parameter.)

Donald Knuth later proposed the Man or Boy Test as a more rigorous exercise.

[Assistant]
(formerly Perl 6)

Rather than playing tricks like Perl 5 does, the declarations of the formal parameters are quite straightforward in Raku:

```
sub sum($i is rw, $lo, $hi, &term) {
    my $temp = 0;
    loop ($i = $lo; $i <= $hi; $i++) {
        $temp += term;
    }
    return $temp;
}

my $i;
say sum $i, 1, 100, { 1 / $i };

```

Note that the C-style "for" loop is pronounced "loop" in Raku, and is the only loop statement that actually requires parens.


[User]
Task

Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.

Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.

The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.

Note that:

:   1. Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
    2. A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
    3. The parameters do not need to have exactly the same names.
    4. Validating the arguments is unnecessary.

So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.

This task was inspired by this problem.

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)

```
sub count-jewels ( Str $j, Str $s --> Int ) {
    my %counts_of_all = $s.comb.Bag;
    my @jewel_list    = $j.comb.unique;

    return %counts_of_all ∩ @jewel_list.Bag ?? %counts_of_all{ @jewel_list }.sum !! 0;
}

say count-jewels 'aA' , 'aAAbbbb';
say count-jewels 'z'  , 'ZZ';

```

Output:

```
3
0
```


[User]
**Jordan-Pólya numbers** (or **J-P numbers** for short) are the numbers that can be obtained by multiplying together one or more (not necessarily distinct) factorials.

Example

480 is a J-P number because 480 = 2! x 2! x 5!.

Task

Find and show on this page the first **50** J-P numbers.

What is the largest J-P number less than **100 million**?

Bonus

Find and show on this page the **800**th, **1,800**th, **2,800**th and **3,800**th J-P numbers and also show their decomposition into factorials in highest to lowest order. Optionally, do the same for the **1,050**th J-P number.

Where there is more than one way to decompose a J-P number into factorials, choose the way which uses the largest factorials.

Hint: These J-P numbers are all less than 2^53.

References

* Wikipedia article : Jordan-Pólya number
* OEIS sequence A001013: Jordan-Pólya numbers

[Assistant]
**Partial translation of Go**

```
# 20230719 Raku programming solution

my \factorials = 1, | [\*] 1..18; # with 0!

sub JordanPolya (\limit) {
   my \ix = (factorials.keys.first: factorials[*] >= limit) // factorials.end;
   my ($k, @res) = 2, |factorials[0..ix];

   while $k < @res.elems {
      my \rk = @res[$k];
      for 2 .. @res.elems -> \l {
         my \kl = $ = @res[l] * rk;
         last if kl > limit;
         loop {
            my \p = @res.keys.first: { @res[$_] >= kl } # performance
            if p < @res.elems and @res[p] != kl {
               @res.splice: p, 0, kl
            } elsif p == @res.elems {
               @res.append: kl
            }
            kl > limit/rk ?? ( last ) !! kl *= rk
         }
      }
      $k++
   }
   return @res[1..*]
}

my @result = JordanPolya 2**30 ;
say "First 50 Jordan-Pólya numbers:";
say [~] $_>>.fmt('%5s') for @result[^50].rotor(10);
print "\nThe largest Jordan-Pólya number before 100 million: ";
say @result.first: * < 100_000_000, :end;

```

You may Attempt This Online!


[User]
|  |
| --- |
| Note:   jortSort is considered a work of satire.   It achieves its result in an intentionally roundabout way.   You are encouraged to write your solutions in the spirit of the original jortsort rather than trying to give the most concise or idiomatic solution. |

JortSort is a sorting tool set that makes the user do the work and guarantees efficiency because you don't have to sort ever again.

It was originally presented by Jenn "Moneydollars" Schiffer at the
prestigious   JSConf.

JortSort is a function that takes a single array of comparable objects as its argument.

It then sorts the array in ascending order and compares the sorted array to the originally provided array.

If the arrays match   (i.e. the original array was already sorted),   the function returns   **true**.

If the arrays do not match (i.e. the original array was not sorted), the function returns   **false**.

[Assistant]
(formerly Perl 6)

```
sub jort-sort { @_ eqv @_.sort }

```

Actually, there's a better internal sort that seems to work best for lists that are already completely sorted, but tends to fails for any other list. The name of this sort, [!after], is completely opaque, so we're pretty much forced to hide it inside a subroutine to prevent widespread panic.

```
sub jort-sort-more-better-sorta { [!after] @_ }

```

However, since Perl 6 has a really good inliner, there's really little point anyway in using the [!after] reduction operator directly, and jort-sort-more-better-sorta is really much more self-documenting, so please don't use the reduction operator if you can. For example:

Output:

```
$ perl6
> [!after] <a b c>  # DON'T do it this way
True
> [!after] 1,3,2    # DON'T do it this way either
False
```

Please do your part to uphold and/or downhold our community standards.


[User]
Josephus problem is a math puzzle with a grim description:

n
{\displaystyle {\displaystyle n}}
 prisoners are standing on a circle, sequentially numbered from

0
{\displaystyle {\displaystyle 0}}
 to

n
−
1
{\displaystyle {\displaystyle n-1}}
.

An executioner walks along the circle, starting from prisoner

0
{\displaystyle {\displaystyle 0}}
,
removing every

k
{\displaystyle {\displaystyle k}}
-th prisoner and killing him.

As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed. >

For example, if there are

n
=
5
{\displaystyle {\displaystyle n=5}}
 prisoners and

k
=
2
{\displaystyle {\displaystyle k=2}}
, the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2.

Task

Given any

n
,
k
>
0
{\displaystyle {\displaystyle n,k>0}}
,   find out which prisoner will be the final survivor.

In one such incident, there were 41 prisoners and every 3rd prisoner was being killed   (

k
=
3
{\displaystyle {\displaystyle k=3}}
).

Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale.

Which number was he?

Extra

The captors may be especially kind and let

m
{\displaystyle {\displaystyle m}}
 survivors free,

and Josephus might just have

m
−
1
{\displaystyle {\displaystyle m-1}}
   friends to save.

Provide a way to calculate which prisoner is at any given position on the killing sequence.

Notes

1. You can always play the executioner and follow the procedure exactly as described, walking around the circle, counting (and cutting off) heads along the way. This would yield the complete killing sequence and answer the above questions, with a complexity of probably

   O
   (
   k
   n
   )
   {\displaystyle {\displaystyle O(kn)}}
   . However, individually it takes no more than

   O
   (
   m
   )
   {\displaystyle {\displaystyle O(m)}}
    to find out which prisoner is the

   m
   {\displaystyle {\displaystyle m}}
   -th to die.
2. If it's more convenient, you can number prisoners from

   1
   {\displaystyle {\displaystyle 1}}
    to

   n
   {\displaystyle {\displaystyle n}}
      instead.   If you choose to do so, please state it clearly.
3. An alternative description has the people committing assisted suicide instead of being executed, and the last person simply walks away. These details are not relevant, at least not mathematically.

[Assistant]
(formerly Perl 6)

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

Straightforward implementation of the executioner's algorithm:

```
sub Execute(@prisoner, $k) {
    until @prisoner == 1 {
	@prisoner.=rotate($k - 1);
	@prisoner.shift;
    }
}

my @prisoner = ^41;
Execute @prisoner, 3;
say "Prisoner {@prisoner} survived.";

# We don't have to use numbers.  Any list will do:

my @dalton = <Joe Jack William Averell Rantanplan>;
Execute @dalton, 2;
say "{@dalton} survived.";

```

Output:

```
Prisoner 30 survived.
William survived.
```


[User]
The task is to determine the joystick position and represent this on the display via a crosshair.
For a centred joystick, the crosshair should appear in the centre of the screen.
If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed.

If the joystick is pushed forward or pulled back, then the crosshair should move up or down according to the extent that that joystick is pushed or pulled.
The edges of the display represent maximum extents for joystick movement.

For example, a joystick pushed fully forward would raise the crosshair to the top centre of the screen.

A joystick pulled backwards and to the right would move the crosshair to the bottom right of the screen (except for a small area reserved to show joystick status). Implementations can use a graphical display method to produce the crosshair, or alternatively represent the crosshair using a plus symbol on
a terminal, and move the plus symbol position according to the joystick.
The bottom part of the display can hide or show an alphanumeric sequence to represent the buttons pressed.

For example, if pushbuttons 1,4 and 10 are depressed, we could display "1 4 A".

The implemented code should continue to redraw the crosshair according to the joystick position and show the current pushbutton statuses until the task is terminated.
Digital joysticks that produce no extent data, should have their position indicated as full extent movement of the crosshair.

For the purpose of this task, we assume that the joystick is calibrated and that the first joystick is being used.
The task implementer could at their option provide a solution that includes a joystick selection facility, enabling the user to choose which joystick is to be used for this task.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.011

Linux only terminal based joystick testing utility. Reads events from the joystick asynchronously, allows a main processing loop if desired. This uses the main loop to check for and compensate for a resized terminal but not really anything else. Hit control-c to exit; needs one extra event from the the joystick to exit completely. Only shows the first 3 axes, no matter how many are available. Tested with an Logitech extreme joystick and an Xbox controller.

```
use experimental :pack;

# Joysticks generally show up in the /dev/input/ directory as js(n) where n is
# the number assigned by the OS. E.G. /dev/input/js1 . In my particular case:

my $device = '/dev/input/js0';

my $exit = 0;

my $event-stream = $device.IO.open(:bin);
my $js = $event-stream.Supply(:8size);

my %config; # joystick configuration: number of axes and buttons
my %event;  # global "joystick event"

%config<button>.push: 0;

my $callback = sub { update };

sub get-js-event ( $ev, &callback ) {
    exit if $exit;
    # 32 bit timestamp milliseconds. Allows easy checking for "double-click" button presses
    %event<timestamp> = $ev.subbuf(0, 4).reverse.unpack('N');

    # 16 bit (signed int16) value of current control
    %event<value> = (my $v = $ev.subbuf(4, 2).unpack('S')) > 32767 ?? -65536 + $v !! $v;

    # Two 8 bit integers, current event: control type, and control ID
    (%event<type>, %event<number>) = $ev.subbuf(6).unpack('CC');

    # Process the event
    if %event<type> +& 128 {       # initialing
        given %event<type> +& 3  { # enumeration of control inputs
            when 1 { %config<button>.push: %event<number> }
            when 2 { %config<axis>.push: %event<number> }
        }
    } else {
        # Optional callback subroutine to run every time a js event is received
        callback
    }
}

# read events from the joystick driver asynchronously
start react whenever $js { $js.act: { get-js-event($_, $callback) } }

# allow a short delay while driver initializes
sleep .5;

# clean up on exit
signal(SIGINT).tap: {
    print "\e[0m", "\n" xx 50, "\e[H\e[J\e[?25hWaiting for one more joystick event...\n";
    $exit = 1;
    exit(0);
}

use Terminal::ANSIColor;

my ($rows, $cols) = qx/stty size/.words; # get the terminal size

my $xhair = '╺╋╸';
my $axis  = '█';
my @btext = %config<button>.map: { sprintf( "%2d", $_) };
my @button = @btext.map: {color('bold white on_blue ') ~ $_ ~ color('reset')};
my ($x, $y, $z) = ($rows/2).floor, ($cols/2).floor, 0;

sub update {
    given %event<type> {
        when 1 { # button event
            given %event<value> {
                when 0 { @button[%event<number>] = color('bold white on_blue ') ~ @btext[%event<number>] ~ color('reset') }
                when 1 { @button[%event<number>] = color('bold white on_green') ~ @btext[%event<number>] ~ color('reset') }
            }
        }
        when 2 { # axis events
            given %event<number> {
                when 0 { $y = ($cols / 2 + %event<value> / 32767 * $cols / 2).Int max 1 }
                when 1 { $x = ($rows / 2 + %event<value> / 32767 * $rows / 2).Int max 2 }
                when 2 { $z = (%event<value> / 32767 * 100).Int }
                default { } # only using the first 3 axes, ignore ant others
            }
            $x min= $rows - 1;
            $y min= $cols - 1;
        }
    }
    print "\e[H\e[J\e[1;1H";
    print "  ", join "  ", flat @button, "Axis 0: $x", "Axis 1: $y" , "Axis 2: $z%\n";
    my $bar = ($z / 100 * $cols / 2).floor;
    if $bar < 0 {
        print ' ' x ($bar + $cols / 2).floor, color('bold green') ~ $axis x -$bar ~ color('reset');
    } else {
        print ' ' x $cols / 2, color('bold green') ~ $axis x $bar ~ color('reset');
    }
    print "\e[{$x};{$y}H", color('bold yellow') ~ $xhair ~ color('reset');
}

print "\e[?25l"; # hide the cursor
update; # initial update

# Main loop, operates independently of the joystick event loop
loop {
    once say " Joystick has {%config<axis>.elems} axes and {%config<button>.elems} buttons";
    sleep 1;
    ($rows, $cols) = qx/stty size/.words;
}

```


[User]
Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.

Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).

[Assistant]
(formerly Perl 6)

Using JSON::Tiny

```
use JSON::Tiny;

say from-json '{ "foo": 1, "bar": [10, "apples"] }';
say to-json   %( blue => [1,2], ocean => "water" );

```

Output:

```
{bar => [10 apples], foo => 1}
{ "blue" : [ 1, 2 ], "ocean" : "water" }
```


[User]
**JSON Pointer** is a syntax for targeting a value in a JSON (JavaScript Object Notation) document.

Standardized in RFC 6901, a JSON Pointer is a Unicode string containing slash (`/`) separated tokens. Each token is either a potential property name for a JSON object, or a potential index for a JSON array. When a property name contains a slash (`/`) or a tilde (`~`), they are encoded as `~1` and `~0`, respectively.

Pseudocode

*Evaluating* or *resolving* a JSON Pointer against an arbitrary JSON document might look like this.

```
set the current node to the document root
FOR each token in the pointer
  decode the token
  IF the current node is an array
    IF the token is a string representation of an array index AND the index is in range
      set the current node to node[index]
    ELSE
      error condition
    ENDIF
  ELSE IF the current node is an object
    IF the current node has a property matching token
      set the current node to node[token]
    ELSE
      error condition
    ENDIF
  ELSE
    error condition
  ENDIF
ENDFOR

```

Barring any error conditions, the result is the value of the current node after the loop has completed. For example, evaluating the JSON Pointer `/foo/bar/1` against the JSON document `{"foo": {"bar": ["hello", "world"]}}`, would result in the value `"world"`.

See RFC 6901 for details.

Task

Demonstrate parsing and evaluation of JSON Pointers using, at least, the following examples. Display, on this page, either the resulting JSON value for each test case or a helpful error message.

Example JSON document

```
{
  "wiki": {
    "links": [
      "https://rosettacode.org/wiki/Rosetta_Code",
      "https://discord.com/channels/1011262808001880065"
    ]
  },
  "": "Rosetta",
  " ": "Code",
  "g/h": "chrestomathy",
  "i~j": "site",
  "abc": ["is", "a"],
  "def": { "": "programming" }
}

```

Example JSON pointers

JSON pointers are surrounded by quotes to emphasize whitespace and the empty pointer. The quotes are not part of the pointer.

| JSON pointer | Expected result |
| --- | --- |
| `""` | *The entire input document.* |
| `"/"` | `"Rosetta"` |
| `"/ "` | `"Code"` |
| `"/abc"` | `["is", "a"]` |
| `"/def/"` | `"programming"` |
| `"/g~1h"` | `"chrestomathy"` |
| `"/i~0j"` | `"site"` |
| `"/wiki/links/0"` | `"https://rosettacode.org/wiki/Rosetta_Code"` |
| `"/wiki/links/1"` | `"https://discord.com/channels/1011262808001880065"` |
| `"/wiki/links/2"` | *Error condition.* |
| `"/wiki/name"` | *Error condition.* |
| `"/no/such/thing"` | *Error condition.* |
| `"bad/pointer"` | *Error condition.* |

Reference

* RFC 6901 - JSON Pointer Internet Standards Track document

Related tasks

* JSON

[Assistant]
```
# 20240905 Raku programming solution

use JSON::Fast;
use JSON::Pointer;

my $json = from-json q:to/END/;
{
  "wiki": {
    "links": [
      "https://rosettacode.org/wiki/Rosetta_Code",
      "https://discord.com/channels/1011262808001880065"
    ]
  },
  "": "Rosetta",
  " ": "Code",
  "g/h": "chrestomathy",
  "i~j": "site",
  "abc": ["is", "a"],
  "def": { "": "programming" }
}
END

for "",  "/",  "/ ", "/abc",   "/def", "/g~1h", "/i~0j",
    "/wiki/links/0", "/wiki/links/1" , "/wiki/links/2" ,
    "/wiki/name"   , "/no/such/thing", "bad/pointer"     -> $input {
   say "{$input.fmt: '%13s'} => ", ( $input eq "/" and $json{""}.defined )
      ?? $json{""} # :-P
      !! JSON::Pointer.parse($input).resolve($json);
   CATCH { default { say "Error: $_" } }
}

```

Output:

```
              => { => Rosetta,   => Code, abc => [is a], def => { => programming}, g/h => chrestomathy, i~j => site, wiki => {links => [https://rosettacode.org/wiki/Rosetta_Code https://discord.com/channels/1011262808001880065]}}
            / => Rosetta
           /  => Code
         /abc => [is a]
         /def => { => programming}
        /g~1h => chrestomathy
        /i~0j => site
/wiki/links/0 => https://rosettacode.org/wiki/Rosetta_Code
/wiki/links/1 => https://discord.com/channels/1011262808001880065
Error: Element does not exist at 2
Error: Element does not exist at name
Error: Element does not exist at no
Error: Invalid syntax at 0 when trying to resolve 「bad/pointer」

```