[User]
Definitions and restrictions

**Rare**   numbers are positive integers    **n**    where:

:   :   :   * **n**    is expressed in base ten
            * **r**    is the reverse of    **n**      (decimal digits)
            * **n**    must be non-palindromic   (**n** ≠ **r**)
            * **(n+r)**    is the   **sum**
            * **(n-r)**    is the   **difference**   and must be positive
            * the   **sum**   and the   **difference**   must be perfect squares

Task
:   * find and show the first   **5**   *rare*   numbers
    * find and show the first   **8**   *rare*   numbers       (*optional*)
    * find and show more   *rare*   numbers                (*stretch goal*)

Show all output here, on this page.

References
:   * an   OEIS   entry:   A035519          rare numbers.
    * an   OEIS   entry:   A059755   odd rare numbers.
    * planetmath entry:   rare numbers.     (some hints)
    * author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).

[Assistant]
### Translation of Rust

**Translation of**: Rust

```
# 20220315 Raku programming solution

sub rare (\target where ( target > 0 and target ~~ Int )) {

   my \digit          = $ = 2;
   my $count          = 0;
   my @numeric_digits = 0..9 Z, 0 xx *;
   my @diffs1         = 0,1,4,5,6;

   # all possible digits pairs to calculate potential diffs
   my @pairs     = 0..9 X 0..9;
   my @all_diffs = -9..9;

   # lookup table for the first diff
   my @lookup_1 = [ [[2, 2], [8, 8]],    # Diff = 0
                    [[8, 7], [6, 5]],    # Diff = 1
                    [],
                    [],
                    [[4, 0],       ],    # Diff = 4
                    [[8, 3],       ],    # Diff = 5
                    [[6, 0], [8, 2]], ]; # Diff = 6

   # lookup table for all the remaining diffs
   given my %lookup_n { for @pairs -> \pair { $_{ [-] pair.values }.push: pair } }

   loop {
      my @powers = 10 <<**<< (0..digit-1); #  powers like 1, 10, 100, 1000....

      #  for n-r (aka L) the required terms, like 9/ 99 / 999 & 90 / 99999 & 9999 & 900 etc
      my @terms = (@powers.reverse Z- @powers).grep: * > 0 ;

      # create a cartesian product for all potential diff numbers
      # for the first use the very short one, for all other the complete 19 element
      my @diff_list = digit == 2 ?? @diffs1 !! [X] @diffs1, |(@all_diffs xx digit div 2 - 1);

      my @diff_list_iter = gather for @diff_list -> \k {
         # remove invalid first diff/second diff combinations
         { take k andthen next } if k.elems == 1 ;
         given (my (\a,\b) = k.values) {
            when a == 0 && b != 0                                    { next }
            when a == 1 && b ∉ [ -7, -5, -3, -1,  1, 3, 5, 7       ] { next }
            when a == 4 && b ∉ [ -8, -6, -4, -2,  0, 2, 4, 6, 8    ] { next }
            when a == 5 && b ∉ [ -3,  7                            ] { next }
            when a == 6 && b ∉ [ -9, -7, -5, -3, -1, 1, 3, 5, 7, 9 ] { next }
            default { take k }
         }
      }

      for @diff_list_iter -> \diffs {
         # calculate difference of original n and its reverse (aka L = n-r)
         # which must be a perfect square
         if (my \L = [+] diffs <<*>> @terms) > 0 and { $_ == $_.Int }(L.sqrt) {
            # potential candiate, at least L is a perfect square
            # placeholder for the digits
            my \dig = @ = 0 xx digit;

            # generate a cartesian product for each identified diff using the lookup tables
            my @c_iter = digit == 2
               ?? @lookup_1[diffs[0]].map: { [ $_ ] }
               !! [X] @lookup_1[diffs[0]], |(1..(+diffs + (digit % 2 - 1))).map: -> \k {
                  k == diffs ?? @numeric_digits !! %lookup_n{diffs[k]} }

            # check each H (n+r) by using digit combination
            for @c_iter -> \elt {
               for elt.kv -> \i, \pair { dig[i,digit-1-i] = pair.values }
               # for numbers with odd # digits restore the middle digit
               # which has been overwritten at the end of the previous cycle
               dig[(digit - 1) div 2] = elt[+elt - 1][0] if digit % 2 == 1 ;

	       my \rev = ( my \num = [~] dig ).flip;

               if num > rev and { $_ == $_.Int }((num+rev).sqrt) {
                  printf "%d: %12d reverse %d\n", $count+1, num, rev;
		  exit if ++$count == target;
               }
            }
         }
      }
      digit++
   }
}

my $N = 5;
say "The first $N rare numbers are,";
rare $N;

```

Output:

```
The first 5 rare numbers are,
1:           65 reverse 56
2:       621770 reverse 77126
3:    281089082 reverse 280980182
4:   2022652202 reverse 2022562202
5:   2042832002 reverse 2002382402
```

### Using NativeCall with Rust

This example will make use of a modified version of the 'advanced' routine from the Rust entry.

```
~> cargo new --lib Rare && cd $_
     Created library `Rare` package

```

Add to the stock manifest file, Cargo.toml, all required dependencies and build target,

```
~/Rare> tail -5 Cargo.toml
[dependencies]
itertools = "0.10.3"

[lib]
crate-type = ["cdylib"]

```

Now replace the src/lib.rs file with the following,

lib.rs

```
use itertools::Itertools;
use std::collections::HashMap;

fn isqrt(n: u64) -> u64 {
    let mut s = (n as f64).sqrt() as u64;
    s = (s + n / s) >> 1;
    if s * s > n {
        s - 1
    } else {
        s
    }
}

fn is_square(n: u64) -> bool {
    match n & 0xf {
        0 | 1 | 4 | 9 => {
            let t = isqrt(n);
            t * t == n
        }
        _ => false,
    }
}

#[no_mangle]
/// This algorithm uses an advanced search strategy based on Nigel Galloway's approach
pub extern "C" fn advanced64(target: u8) -> *mut u64 {
    // setup
    let digit = 2u8;
    let mut results = Vec::new();
    let mut counter = 0_u8;

    let numeric_digits = (0..=9).map(|x| [x, 0]).collect::<Vec<_>>();
    let diffs1: Vec<i8> = vec![0, 1, 4, 5, 6];

    // all possible digits pairs to calculate potential diffs
    let pairs = (0_i8..=9)
        .cartesian_product(0_i8..=9)
        .map(|x| [x.0, x.1])
        .collect::<Vec<_>>();
    let all_diffs = (-9i8..=9).collect::<Vec<_>>();

    // lookup table for the first diff
    let lookup_1 = vec![
        vec![[2, 2], [8, 8]], //Diff = 0
        vec![[8, 7], [6, 5]], //Diff = 1
        vec![],
        vec![],
        vec![[4, 0]],         // Diff = 4
        vec![[8, 3]],         // Diff = 5
        vec![[6, 0], [8, 2]], // Diff = 6
    ];

    // lookup table for all the remaining diffs
    let lookup_n: HashMap<i8, Vec<_>> = pairs.into_iter().into_group_map_by(|elt| elt[0] - elt[1]);

    let mut d = digit;

    while target > counter {
        // powers like 1, 10, 100, 1000....
        let powers = (0..d).map(|x| 10_u64.pow(x.into())).collect::<Vec<u64>>();

        // for n-r (aka L) the required terms, like 9/ 99 / 999 & 90 / 99999 & 9999 & 900 etc
        let terms = powers
            .iter()
            .zip(powers.iter().rev())
            .map(|(a, b)| b.checked_sub(*a).unwrap_or(0))
            .filter(|x| *x != 0)
            .collect::<Vec<u64>>();

        // create a cartesian product for all potential diff numbers
        // for the first use the very short one, for all other the complete 19 element
        let diff_list_iter = (0_u8..(d / 2))
            .map(|i| match i {
                0 => diffs1.iter(),
                _ => all_diffs.iter(),
            })
            .multi_cartesian_product()
            // remove invalid first diff/second diff combinations - custom iterator would be probably better
            .filter(|x| {
                if x.len() == 1 {
                    return true;
                }
                match (*x[0], *x[1]) {
                    (a, b) if (a == 0 && b != 0) => false,
                    (a, b) if (a == 1 && ![-7, -5, -3, -1, 1, 3, 5, 7].contains(&b)) => false,
                    (a, b) if (a == 4 && ![-8, -6, -4, -2, 0, 2, 4, 6, 8].contains(&b)) => false,
                    (a, b) if (a == 5 && ![7, -3].contains(&b)) => false,
                    (a, b) if (a == 6 && ![-9, -7, -5, -3, -1, 1, 3, 5, 7, 9].contains(&b)) => {
                        false
                    }
                    _ => true,
                }
            });

        'OUTER: for diffs in diff_list_iter {
            // calculate difference of original n and its reverse (aka L = n-r)
            // which must be a perfect square
            let l: i64 = diffs
                .iter()
                .zip(terms.iter())
                .map(|(diff, term)| **diff as i64 * *term as i64)
                .sum();

            if l > 0 && is_square(l.try_into().unwrap()) {
                // potential candiate, at least L is a perfect square

                // placeholder for the digits
                let mut dig: Vec<i8> = vec![0_i8; d.into()];

                // generate a cartesian product for each identified diff using the lookup tables
                let c_iter = (0..(diffs.len() + d as usize % 2))
                    .map(|i| match i {
                        0 => lookup_1[*diffs[0] as usize].iter(),
                        _ if i != diffs.len() => lookup_n.get(diffs[i]).unwrap().iter(),
                        _ => numeric_digits.iter(), // for the middle digits
                    })
                    .multi_cartesian_product();

                // check each H (n+r) by using digit combination
                c_iter.for_each(|elt| {
                    for (i, digit_pair) in elt.iter().enumerate() {
                        dig[i] = digit_pair[0];
                        dig[d as usize - 1 - i] = digit_pair[1]
                    }

                    // for numbers with odd # digits restore the middle digit
                    // which has been overwritten at the end of the previous cycle
                    if d % 2 == 1 {
                        dig[(d as usize - 1) / 2] = elt[elt.len() - 1][0];
                    }

                    let num = dig
                        .iter()
                        .rev()
                        .enumerate()
                        .fold(0_u64, |acc, (i, d)| acc + 10_u64.pow(i as u32) * *d as u64);

                    let reverse = dig
                        .iter()
                        .enumerate()
                        .fold(0_u64, |acc, (i, d)| acc + 10_u64.pow(i as u32) * *d as u64);

                    if num > reverse && is_square(num + reverse) {
                        counter += 1;
                        results.push(num);
                    }
                });
                if counter == target {
                    break 'OUTER;
                }
            }
        }
        d += 1
    }
    let ptr = results.as_mut_ptr();
    std::mem::forget(results); // circumvent the destructor

    ptr
}

```

The needful shared library will be available after the build command,

```
~/Rare> cargo build
~/Rare> file target/debug/libRare.so
target/debug/libRare.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=4f904cce7f8e82130826bf46f93fe9fe944ab9d0, with debug_info, not stripped

```

Here is the main Raku program,

```
use NativeCall;

constant LIB = '/home/hkdtam/Rare/target/debug/libRare.so';

sub advanced64(uint8) returns Pointer[uint64] is native(LIB) {*}

my $N = 5;
say "The first $N rare numbers are,";

for (advanced64 $N)[^$N].kv -> \nth,\rare {
   printf "%d: %12d reverse %d\n", nth+1, { $_, $_.flip }(rare)
}

```

Output is the same.


[User]
Task

Display bars of color,   moving up and down across the screen for horizontal raster bars,   or left and right across the screen for vertical raster bars,   making the raster bars move as stated by swaying side-to-side the respective way if possible.

Use multiple colors in succession and carefully make a gradient between the colors   (if possible)   to achieve an effect of metallic-looking horizontal bars.

Horizontal and/or vertical raster bars are acceptable.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

As there is no reference implementation, and rather sketchy task instructions, this may or may not fulfill the original task authors intent.

Not really sure what is meant by "swaying", perhaps this will suffice.

Generate random colored bars and display them. (They ended up looking more plastic than metallic; ah well.)

* Use Up / Down arrows to change the scroll speed.
* Use Left / Right arrows to adjust the gap between the raster bars.
* Use Pg Up / Pg Dn to adjust raster bar height.
* Use Z / X to change the angle of the raster bars.
* Use Space bar to pause / resume scrolling.
* Use Left Ctrl to toggle the scroll direction.
* Press R to toggle Randomize on / off.
* If Randomize is active, adjust the randomize delay with < / >
* Press S to toggle Swaying on / off.
* If Swaying is active, adjust the period with D / F
* Press Q to exit.

```
unit sub MAIN (
    Int :b(:$bar-height) is copy = 60; #= Height of the individual "Raster bars", minimum 32 (pixels)
    Int :d(:$dir) is copy        = -1; #= Scroll direction: -1 is "up" 1 is "down"
    Int :s(:$step) is copy       = 4;  #= Scroll speed (pixels per step
    Int :g(:$gap) is copy        = $bar-height + 50; #= Gap between bars (pixels)
    Int :a(:$angle) is copy      = 0; #= Angle to orient bars off horizontal (-60 to 60 degrees)
    Int :sw(:$sway) is copy      = 0; #= Swaying on / off
    Real :r(:$rnd) is copy       = 0; #= Delay between randomize events
);

say q:to/END/;

    Use Up / Down arrows to change the scroll speed.
    Use Left / Right arrows to adjust the gap between the raster bars.
    Use Pg Up / Pg Dn to adjust raster bar height.
    Use Z / X to change the angle of the raster bars.
    Use Space bar to pause / resume scrolling.
    Use Left Ctrl to toggle the scroll direction.
    Press R to toggle Randomize on / off.
    If Randomize is active, adjust the randomize delay with < / >
    Press S to toggle Swaying on / off.
    If Swaying is active, adjust the period with D / F
    Press Q to exit.
    END

use SDL2::Raw;
use Cairo;

my $width  = 800;
my $height = 800;

SDL_Init(VIDEO);

my $window = SDL_CreateWindow(
    'Raster Bars - Raku',
    SDL_WINDOWPOS_CENTERED_MASK,
    SDL_WINDOWPOS_CENTERED_MASK,
    $width, $height, RESIZABLE
);

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

my @bars = (^128).map: { gen-bar( rand xx 3 ) };

my $event = SDL_Event.new;

enum KEY_CODES (
    K_UP     => 82,
    K_DOWN   => 81,
    K_LEFT   => 80,
    K_RIGHT  => 79,
    K_SPACE  => 44,
    K_PGUP   => 75,
    K_PGDN   => 78,
    K_LCTRL  => 224,
    K_Z      => 29,
    K_X      => 27,
    K_Q      => 20,
    K_R      => 21,
    K_S      => 22,
    K_D      => 7,
    K_F      => 9,
    K_LT     => 54,
    K_GT     => 55,
);

my $port  = +@bars * $gap;
my $y     = $dir > 0 ?? $height - $port !! $height ;
my $now   = now;
my $period = 2;

main: loop {
    handle-event($event) while SDL_PollEvent($event);

    randomize if $rnd and now - $now > $rnd;

    if $dir > 0 {
        $y = $height - $port if $y > 0 - ceiling $height / cos(π * $angle / 180).abs
    } else {
        $y = 0 - ceiling $height / cos(π * $angle / 180).abs if $y < $height - $port
    }

    $y = $step * $dir + $y;

    $angle = (((now * $period) % τ).sin * 35).Int if $sway;

    for ^@bars {
        my $offset = $sway ?? $gap !! ceiling $gap / cos(π * $angle / 180).abs;
        SDL_RenderCopyEx( $render, @bars[$_], Nil,
          SDL_Rect.new( -($width*4), $y + $offset * $_, $width * 10, $bar-height),
          $angle.Num, SDL_Point.new(:x((4.5*$width).Int),:y($y + $offset * $_)), 0

        )
    }

    SDL_RenderPresent($render);

    SDL_RenderClear($render);

    print fps;
}

put '';

SDL_Quit();

sub gen-bar (@color) {
    my $bar = Cairo::Image.create( Cairo::FORMAT_ARGB32, 1, 128 );
    given Cairo::Context.new($bar) {
        my Cairo::Pattern::Gradient::Linear $lpat .= create(0.0, 0.0,  0.0, 128.0);
        $lpat.add_color_stop_rgba(  1, |(@color »*» .3), 1);
        $lpat.add_color_stop_rgba( .2, |(@color),        1);
        $lpat.add_color_stop_rgba(.75, |(@color),        1);
        $lpat.add_color_stop_rgba(  0, |(@color »+» .5), 1);
        .rectangle(0, 0, 1, 128);
        .pattern($lpat);
        .fill;
        $lpat.destroy;
    }

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

    SDL_UpdateTexture(
        $bar_texture,
        SDL_Rect.new(:x(0), :y(0), :w(1), :h(128)),
        $bar.data, $bar.stride // 1
    );

    $bar_texture
}

sub handle-event ($event) {
    my $casted_event = SDL_CastEvent($event);
    given $casted_event {
        when *.type == QUIT    { last main }
        when *.type == KEYDOWN {
            if KEY_CODES(.scancode) -> $comm {
                given $comm {
                    when 'K_UP'     { $step += 1 }
                    when 'K_DOWN'   { $step -= 1 if $step > 1 }
                    when 'K_LEFT'   { $gap = $gap < 32 ?? $gap !! $gap - 1; $port = +@bars * $gap; }
                    when 'K_RIGHT'  { $gap++; $port += +@bars; }
                    when 'K_PGUP'   { $bar-height += 2 }
                    when 'K_PGDN'   { $bar-height = $bar-height >= 34 ?? $bar-height - 2 !! $bar-height }
                    when 'K_SPACE'  { $step = $step ?? 0 !! 1 }
                    when 'K_LCTRL'  { $dir  *= -1 }
                    when 'K_Z'      { $angle = $angle > -45 ?? $angle - 5 !! $angle }
                    when 'K_X'      { $angle = $angle <  45 ?? $angle + 5 !! $angle }
                    when 'K_R'      { $rnd = $rnd ?? 0 !! 1 }
                    when 'K_S'      { $sway xor= 1 }
                    when 'K_F'      { $period += .1 }
                    when 'K_D'      { $period = $period - .1 max .1;  }
                    when 'K_GT'     { $rnd += .2 }
                    when 'K_LT'     { $rnd = $rnd > .2 ?? $rnd -.2 !! .2 }
                    when 'K_Q'      { last main }
                }
            } #else { say .scancode, "\n" }
        }
        when *.type == WINDOWEVENT {
            if .event == RESIZED {
                $width  = .data1;
                $height = .data2 + $bar-height;
            }
        }
    }
}

sub randomize {
    $dir   = (-1,1).pick;
    $step  = (4..8).pick;
    $bar-height   = (32..200).pick;
    $gap   = $bar-height + (1..100).pick;
    $angle = (-45, *+5 ... 45).pick;

    $port = +@bars * $gap;

    if $dir > 0 {
        $y = $height - $port;
    } else {
        $y = 0 - ceiling ($height max $width) / cos(π * $angle / 180).abs;
    }
    $now = now;
}

sub fps {
    state $fps-frames = 0;
    state $fps-now    = now;
    state $fps        = '';
    $fps-frames++;
    if now - $fps-now >= 1 {
        $fps = [~] "\b" x 40, ' ' x 20, "\b" x 20 ,
            sprintf "FPS: %5.2f  ", ($fps-frames / (now - $fps-now)).round(.01);
        $fps-frames = 0;
        $fps-now = now;
    }
    $fps
}

```

Screenshot still of typical run: (offsite .png image)

(Small) Moving gif of swaying bars: (offsite .gif image)


[User]
Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.

Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.

Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:

* Run N seconds worth of jobs and/or Y jobs.
* Report at least three distinct times.

Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.

**See also:** System time, Time a function

[Assistant]
(formerly Perl 6)

```
sub runrate($N where $N > 0, &todo) {
    my $n = $N;

    my $start = now;
    todo() while --$n;
    my $end = now;

    say "Start time: ", DateTime.new($start).Str;
    say "End time: ", DateTime.new($end).Str;
    my $elapsed = $end - $start;

    say "Elapsed time: $elapsed seconds";
    say "Rate: { ($N / $elapsed).fmt('%.2f') } per second\n";
}

sub factorial($n) { (state @)[$n] //= $n < 2 ?? 1 !! $n * factorial($n-1) }

runrate 100_000, { state $n = 1; factorial($n++) }

runrate 100_000, { state $n = 1; factorial($n++) }

```

Output:

```
Start time: 2023-04-19T08:23:50.276418Z
End time: 2023-04-19T08:23:54.716864Z
Elapsed time: 4.440445313 seconds
Rate: 22520.26 per second

Start time: 2023-04-19T08:23:54.726913Z
End time: 2023-04-19T08:23:54.798238Z
Elapsed time: 0.071324057 seconds
Rate: 1402051.48 per second

```

The Instant type in Perl 6 is defined to be based on TAI seconds, and represented with rational numbers that are more than sufficiently accurate to represent your clock's accuracy. The actual accuracy will depend on your clock's accuracy (even if you don't have an atomic clock in your kitchen, your smartphone can track various orbiting atomic clocks, right?) modulo the vagaries of returning the atomic time (or unreasonable facsimile) via system calls and library APIs.


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Point\_in\_polygon. 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) |

Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm.

A pseudocode can be simply:

```
 count ← 0
 foreach side in polygon:
   if ray_intersects_segment(P,side) then
     count ← count + 1
 if is_odd(count) then
   return inside
 else
   return outside

```

Where the function ray\_intersects\_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise.

An intuitive explanation of why it works is that every time we cross
a border, we change "country" (inside-outside, or outside-inside), but
the last "country" we land on is surely *outside* (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an *inside*: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border).

So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways.

Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3).

So the problematic points are those inside the white area (the box delimited by the points A and B), like P4.

Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment).

Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain *coherent* results. They could be treated apart, but it is not necessary to do so.

An algorithm for the previous speech could be (if P is a point, Px is its x coordinate):

```
 ray_intersects_segment:
    P : the point from which the ray starts
    A : the end-point of the segment with the smallest y coordinate
        (A must be "below" B)
    B : the end-point of the segment with the greatest y coordinate
        (B must be "above" A)
 if Py = Ay or Py = By then
   Py ← Py + ε
 end if
 if Py < Ay or Py > By then
   return false
 else if Px >= max(Ax, Bx) then
   return false
 else
   if Px < min(Ax, Bx) then
     return true
   else
     if Ax ≠ Bx then
       m_red ← (By - Ay)/(Bx - Ax)
     else
       m_red ← ∞
     end if
     if Ax ≠ Px then
       m_blue ← (Py - Ay)/(Px - Ax)
     else
       m_blue ← ∞
     end if
     if m_blue ≥ m_red then
       return true
     else
       return false
     end if
   end if
 end if

```

(To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)

[Assistant]
(formerly Perl 6)

```
constant ε = 0.0001;

sub ray-hits-seg([\Px,\Py], [[\Ax,\Ay], [\Bx,\By]] --> Bool) {
    Py += ε if Py == Ay | By;

    if Py < Ay or Py > By or Px > (Ax max Bx) {
	False;
    }
    elsif Px < (Ax min Bx) {
	True;
    }
    else {
	my \red  = Ax == Bx ?? Inf !! (By - Ay) / (Bx - Ax);
	my \blue = Ax == Px ?? Inf !! (Py - Ay) / (Px - Ax);
	blue >= red;
    }
}

sub point-in-poly(@point, @polygon --> Bool) {
    so 2 R% [+] gather for @polygon -> @side {
	take ray-hits-seg @point, @side.sort(*.[1]);
    }
}

my %poly =
    squared =>
	 [[[ 0.0,  0.0], [10.0,  0.0]],
	  [[10.0,  0.0], [10.0, 10.0]],
	  [[10.0, 10.0], [ 0.0, 10.0]],
	  [[ 0.0, 10.0], [ 0.0,  0.0]]],
    squaredhole =>
	 [[[ 0.0,  0.0], [10.0,  0.0]],
	  [[10.0,  0.0], [10.0, 10.0]],
	  [[10.0, 10.0], [ 0.0, 10.0]],
	  [[ 0.0, 10.0], [ 0.0,  0.0]],
	  [[ 2.5,  2.5], [ 7.5,  2.5]],
	  [[ 7.5,  2.5], [ 7.5,  7.5]],
	  [[ 7.5,  7.5], [ 2.5,  7.5]],
	  [[ 2.5,  7.5], [ 2.5,  2.5]]],
    strange =>
	 [[[ 0.0,  0.0], [ 2.5,  2.5]],
	  [[ 2.5,  2.5], [ 0.0, 10.0]],
	  [[ 0.0, 10.0], [ 2.5,  7.5]],
	  [[ 2.5,  7.5], [ 7.5,  7.5]],
	  [[ 7.5,  7.5], [10.0, 10.0]],
	  [[10.0, 10.0], [10.0,  0.0]],
	  [[10.0,  0.0], [ 2.5,  2.5]],
	  [[ 2.5,  2.5], [ 0.0,  0.0]]],  # conjecturally close polygon
    exagon =>
	 [[[ 3.0,  0.0], [ 7.0,  0.0]],
	  [[ 7.0,  0.0], [10.0,  5.0]],
	  [[10.0,  5.0], [ 7.0, 10.0]],
	  [[ 7.0, 10.0], [ 3.0, 10.0]],
	  [[ 3.0, 10.0], [ 0.0,  5.0]],
	  [[ 0.0,  5.0], [ 3.0,  0.0]]];

my @test-points =
	  [  5.0,  5.0],
	  [  5.0,  8.0],
	  [-10.0,  5.0],
	  [  0.0,  5.0],
	  [ 10.0,  5.0],
	  [  8.0,  5.0],
	  [ 10.0, 10.0];

for <squared squaredhole strange exagon> -> $polywanna {
    say "$polywanna";
    my @poly = %poly{$polywanna}[];
    for @test-points -> @point {
	say "\t(@point.fmt('%.1f',','))\t{ point-in-poly(@point, @poly) ?? 'IN' !! 'OUT' }";
    }
}

```

Output:

```
squared
	(5.0,5.0)	IN
	(5.0,8.0)	IN
	(-10.0,5.0)	OUT
	(0.0,5.0)	OUT
	(10.0,5.0)	IN
	(8.0,5.0)	IN
	(10.0,10.0)	OUT
squaredhole
	(5.0,5.0)	OUT
	(5.0,8.0)	IN
	(-10.0,5.0)	OUT
	(0.0,5.0)	OUT
	(10.0,5.0)	IN
	(8.0,5.0)	IN
	(10.0,10.0)	OUT
strange
	(5.0,5.0)	IN
	(5.0,8.0)	OUT
	(-10.0,5.0)	OUT
	(0.0,5.0)	OUT
	(10.0,5.0)	IN
	(8.0,5.0)	IN
	(10.0,10.0)	OUT
exagon
	(5.0,5.0)	IN
	(5.0,8.0)	IN
	(-10.0,5.0)	OUT
	(0.0,5.0)	OUT
	(10.0,5.0)	IN
	(8.0,5.0)	IN
	(10.0,10.0)	OUT
```


[User]
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.

For this task, we have a configuration file as follows:

```
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.

# This is the fullname parameter
FULLNAME Foo Barber

# This is a favourite fruit
FAVOURITEFRUIT banana

# This is a boolean that should be set
NEEDSPEELING

# This boolean is commented out
; SEEDSREMOVED

# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.

# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.

# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.

OTHERFAMILY Rhu Barber, Harry Barber

```

For the task we need to set four variables according to the configuration entries as follows:

* fullname = Foo Barber
* favouritefruit = banana
* needspeeling = true
* seedsremoved = false

We also have an option that contains multiple parameters. These may be stored in an array.

* otherfamily(1) = Rhu Barber
* otherfamily(2) = Harry Barber

Related tasks

* Update a configuration file

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

This demonstrates several interesting features of Raku, including full grammar support, derived grammars, alternation split across derivations, and longest-token matching that works across derivations. It also shows off Raku's greatly cleaned up regex syntax.

```
my $fullname;
my $favouritefruit;
my $needspeeling = False;
my $seedsremoved = False;
my @otherfamily;

grammar ConfFile {
    token TOP {
	:my $*linenum = 0;
	^ <fullline>* [$ || (\N*) { die "Parse failed at $0" } ]
    }

    token fullline {
	<?before .>
	{ ++$*linenum }
	<line>
	[ \n || { die "Parse failed at line $*linenum" } ]
    }

    proto token line() {*}

    token line:misc  { {} (\S+) { die "Unrecognized word: $0" } }

    token line:sym<comment> { ^^ [ ';' | '#' ] \N* }
    token line:sym<blank>   { ^^ \h* $$ }

    token line:sym<fullname>       {:i fullname»       <rest> { $fullname = $<rest>.trim } }
    token line:sym<favouritefruit> {:i favouritefruit» <rest> { $favouritefruit = $<rest>.trim } }
    token line:sym<needspeeling>   {:i needspeeling»    <yes> { $needspeeling = defined $<yes> } }
    token rest { \h* '='? (\N*) }
    token yes { :i \h* '='? \h*
    	[
	    || ([yes|true|1])
	    || [no|false|0]
	    || (<?>)
	] \h*
    }
}

grammar MyConfFile is ConfFile {
    token line:sym<otherfamily>    {:i otherfamily»    <rest> { @otherfamily = $<rest>.split(',')».trim } }
}

MyConfFile.parsefile('file.cfg');

say "fullname: $fullname";
say "favouritefruit: $favouritefruit";
say "needspeeling: $needspeeling";
say "seedsremoved: $seedsremoved";
print "otherfamily: "; say @otherfamily.raku;

```

Output:

```
fullname: Foo Barber
favouritefruit: banana
needspeeling: True
seedsremoved: False
otherfamily: ["Rhu Barber", "Harry Barber"]

```


[User]
Task

Read a file one character at a time, as opposed to reading the entire file at once.

The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).

The procedure should support the reading of files containing UTF8 encoded wide characters, returning whole characters for each consecutive read.

Related task

* Read a file line by line

[Assistant]
(formerly Perl 6)

Raku has a built in method .getc to get a single character from an open file handle. File handles default to UTF-8, so they will handle multi-byte characters correctly.

To read a single character at a time from the Standard Input terminal; $\*IN in Raku:

```
.say while defined $_ = $*IN.getc;

```

Or, from a file:

```
my $filename = 'whatever';

my $in = open( $filename, :r ) orelse .die;

print $_ while defined $_ = $in.getc;

```


[User]
Read a file one line at a time,
as opposed to reading the entire file at once.

Related tasks

* Read a file character by character
* Input loop.

[Assistant]
(formerly Perl 6)
The lines method is lazy so the following code does indeed read the file line by line, and not all at once.

```
for open('test.txt').lines
{
  .say
}
```

In order to be more explicit about the file being read on line at a time, one can write:

```
my $f = open 'test.txt';
while my $line = $f.get {
    say $line;
}
```


[User]
Some languages have special semantics for obtaining a known line number from a file.

Task

Demonstrate how to obtain the contents of a specific line within a file.

For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded).

If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message.

If no special semantics are available for obtaining the required line,   it is permissible to read line by line.

Note that empty lines are considered and should still be counted.

Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.

[Assistant]
(formerly Perl 6)

```
say lines[6] // die "Short file";

```

Without an argument, the lines function reads filenames from the command line, or defaults to standard input. It then returns a lazy list, which we subscript to get the 7th element. Assuming this code is in a program called line7:

```
$ cal 2011 > cal.txt
$ line7 cal.txt
16 17 18 19 20 21 22  20 21 22 23 24 25 26  20 21 22 23 24 25 26
$
```

This works even on infinite files because lists are lazy:

```
$ yes | line7
y
$
```


[User]
Task

Load the entire contents of some text file as a single string variable.

If applicable, discuss: encoding selection, the possibility of memory-mapping.

Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2010.07

```
my $string = slurp 'sample.txt';
```

The default encoding is UTF-8. The :enc adverb can be used to specify a different one:

```
my $string = slurp 'sample.txt', :enc<UTF-16>;
```

IO::Path objects also provide slurp as a method:

```
my $string = 'sample.txt'.IO.slurp;
```


[User]
A readline interface is a line editing facility that provides auto completion facilities and the ability to recall previously typed lines. Build a simple application that accepts at least two commands and uses a readline style interface.

The interface should provide

* the ability to recall previously typed commands
* commandline editing
* application specific commands

The application could be based on Simple database or something else.

If the language already provides a readline interface, then it should be demonstrated how build an application specific readline interface (one that only understands the applications commands) and also show how to customize the builtin readline to provide the above features and especially add application specific commands.

See also: Input loop

[Assistant]
(formerly Perl 6)

Raku has a built in REPL that can be initiated by running the Raku executable without any parameters. It is fairly basic on its own but here are bindings available in the Raku ecosystem for GNU Readline and/or Linenoise either of which will automatically provide command history, tab completion and more advance command line editing capability if installed. They are not included in the Raku distribution directly. There are incompatible licensing requirements and providing hooks for third party tools allows for more customization options.

Linenoise is generally the preferred option unless you really want the emacs compatible command line editing key bindings. Readline is arguably more powerful but is somewhat fiddly to set up.

If you are not inclined to install Readline *or* Linenoise, the REPL also works fairly well with 3rd party tools like rlwrap.


[User]
Task

Show how to use the following math constants and functions in your language   (if not available, note it):

:   * *e*   (base of the natural logarithm)
    * π
      {\displaystyle {\displaystyle \pi }}
    * square root
    * logarithm   (any base allowed)
    * exponential   (*e**x* )
    * absolute value   (a.k.a. "magnitude")
    * floor   (largest integer less than or equal to this number--not the same as truncate or int)
    * ceiling   (smallest integer not less than this number--not the same as round up)
    * power   (*x**y* )

Related task

* Trigonometric Functions

[Assistant]
(formerly Perl 6)

```
say e;            # e
say π; # or pi    # pi
say τ; # or tau   # tau

# Common mathmatical function are availble
# as subroutines and as numeric methods.
# It is a matter of personal taste and
# programming style as to which is used.
say sqrt 2;       # Square root
say 2.sqrt;       # Square root

# If you omit a base, does natural logarithm
say log 2;        # Natural logarithm
say 2.log;        # Natural logarithm

# Specify a base if other than e
say log 4, 10;    # Base 10 logarithm
say 4.log(10);    # Base 10 logarithm
say 4.log10;      # Convenience, base 10 only logarithm

say exp 7;        # Exponentiation base e
say 7.exp;        # Exponentiation base e

# Specify a base if other than e
say exp 7, 4;     # Exponentiation
say 7.exp(4);     # Exponentiation
say 4 ** 7;       # Exponentiation

say abs -2;       # Absolute value
say (-2).abs;     # Absolute value

say floor -3.5;   # Floor
say (-3.5).floor; # Floor

say ceiling pi;   # Ceiling
say pi.ceiling;   # Ceiling

say e ** π\i + 1 ≅ 0; # :-)

```


[User]
The **Recamán's sequence** generates Natural numbers.

Starting from a(0)=0, the n'th term `a(n)`, where n>0, is the previous term minus `n` i.e `a(n) = a(n-1) - n` but only if this is **both** positive *and* has not been previously generated.

If the conditions *don't* hold then `a(n) = a(n-1) + n`.

Task

1. Generate and show here the first 15 members of the sequence.
2. Find and show here, the first duplicated number in the sequence.
3. **Optionally**: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.

References

* A005132, The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recamán Sequence, Numberphile video.
* Recamán's sequence, on Wikipedia.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.06

```
my @recamans = 0, {
   state %seen;
   state $term;
   $term++;
   my $this = $^previous - $term;
   $this = $previous + $term unless ($this > 0) && !%seen{$this};
   %seen{$this} = True;
   $this
} … *;

put "First fifteen terms of Recaman's sequence: ", @recamans[^15];

say "First duplicate at term: a[{ @recamans.first({@recamans[^$_].Bag.values.max == 2})-1 }]";

my @seen;
my int $i = 0;
loop {
    next if (my int $this = @recamans[$i++]) > 1000 or @seen[$this];
    @seen[$this] = 1;
    say "Range 0..1000 covered by terms up to a[{$i - 1}]" and last if ++$ == 1001;
}

```

Output:

```
First fifteen terms of Recaman's sequence: 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9
First duplicate at term: a[24]
Range 0..1000 covered by terms up to a[328002]
```


[User]
Record a monophonic 16-bit PCM sound into either memory space, a file or array.

(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs might not record sound in the same format.)

[Assistant]
(formerly Perl 6)
Slightly modified from an example provided with the `Audio::PortAudio` module distribution.

```
use Audio::PortAudio;
use Audio::Sndfile;

sub MAIN(Str $filename, Str :$source, Int :$buffer = 256) {
    my $pa = Audio::PortAudio.new;
    my $format = Audio::Sndfile::Info::Format::WAV +| Audio::Sndfile::Info::Subformat::PCM_16;
    my $out-file = Audio::Sndfile.new(:$filename, channels => 1, samplerate => 44100, :$format, :w);
    my $st;

    if $source.defined {
        my $index = 0;
        for $pa.devices -> $device {
            if $device.name eq $source {
                else {
                    my $la = $device.default-high-input-latency;
                    my $si = Audio::PortAudio::StreamParameters.new(device => $index,
                                                                    channel-count => 1,
                                                                    sample-format => Audio::PortAudio::StreamFormat::Float32,
                                                                    suggested-latency => ($la || 0.05e0 ));
                    $st = $pa.open-stream($si, Audio::PortAudio::StreamParameters, 44100, $buffer );
                    last;
                }

            }
            $index++;
        }
        die "Couldn't find a device for '$source'" if !$st.defined;
    }
    else {
        $st = $pa.open-default-stream(2,0, Audio::PortAudio::StreamFormat::Float32, 44100, $buffer);
    }
    $st.start;
    my $p = Promise.new;
    signal(SIGINT).act({
        say "stopping recording";
        $p.keep: "stopped";
        $out-file.close;
        $st.close;
        exit;
    });
    my Channel $write-channel = Channel.new;
    my $write-promise = start {
        react {
            whenever $write-channel -> $item {
                if $p.status ~~ Planned {
                    $out-file.write-float($item[0], $item[1]);
                    $out-file.sync;
                }
                else {
                    done;
                }
            }
        }
    };

    loop {
        if $p.status ~~ Planned {
            my $f = $buffer || $st.read-available;
            if $f > 0 {
                my $buff = $st.read($f,2, num32);
                $write-channel.send([$buff, $f]);
            }
        }
        else {
            last;
        }
    }

}

```


[User]
Write a recursive descent parser generator that takes a description of a grammar as input and outputs the source code for a parser in the same language as the generator. (So a generator written in C++ would output C++ source code for the parser.) You can assume that all of the rules have been preprocessed into a form suitable for the construction of a recursive descent parser. Check the following links for more details.

* http://www.cs.engr.uky.edu/~lewis/essays/compilers/rec-des.html (broken)
* http://www.engr.mun.ca/~theo/Misc/exp\_parsing.htm

Use the parser generator and a grammar file to build a parser that takes an arithmetic expression and turns it in to three address code. The resulting parser should take this (or something similar) as input:

```
(one + two) * three - four * five

```

And generate this (or something similar) as output:

```
_0001 = one + two
_0002 = _0001 * three
_0003 = four * five
_0004 = _0002 - _0003

```

[Assistant]
(formerly Perl 6)
Instead of writing a full-blown generator, it is possible to solve the task partly by making use of the built-in optimizer and study the relevant AST output

```
raku --target=optimize -e 'no strict; say ($one + $two) * $three - $four * $five' | tail -11
                  - QAST::Op(callstatic &say) <sunk> :statement_id<2> say ($one + $two) * $three - $four * $five
                    - QAST::Op(callstatic &infix:<->) <wanted> -
                      - QAST::Op(callstatic &infix:<*>) <wanted> *
                        - QAST::Op(callstatic &infix:<+>) <wanted> :statement_id<3> +
                          - QAST::Var(local __lowered_lex_5) <wanted> $one
                          - QAST::Var(local __lowered_lex_4) <wanted> $two
                        - QAST::Var(local __lowered_lex_3) <wanted> $three
                      - QAST::Op(callstatic &infix:<*>) <wanted> *
                        - QAST::Var(local __lowered_lex_2) <wanted> $four
                        - QAST::Var(local __lowered_lex_1) <wanted> $five
            - QAST::WVal(Nil)

```

As you can see by examining the nested tree, the calculations are done as follows (expressed using a postfix notation)

```
one two + three * four five * -

```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Rref#Pseudocode. 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) |

Task

Show how to compute the **reduced row echelon form**
(a.k.a. **row canonical form**) of a matrix.

The matrix can be stored in any datatype that is convenient
(for most languages, this will probably be a two-dimensional array).

Built-in functions or this pseudocode (from Wikipedia) may be used:

```
function ToReducedRowEchelonForm(Matrix M) is
    lead := 0
    rowCount := the number of rows in M
    columnCount := the number of columns in M
    for 0 ≤ r < rowCount do
        if columnCount ≤ lead then
            stop
        end if
        i = r
        while M[i, lead] = 0 do
            i = i + 1
            if rowCount = i then
                i = r
                lead = lead + 1
                if columnCount = lead then
                    stop
                end if
            end if
        end while
        Swap rows i and r
        If M[r, lead] is not 0 divide row r by M[r, lead]
        for 0 ≤ i < rowCount do
            if i ≠ r do
                Subtract M[i, lead] multiplied by row r from row i
            end if
        end for
        lead = lead + 1
    end for
end function

```

For testing purposes, the RREF of this matrix:

```
 1    2   -1   -4
 2    3   -1   -11
-2    0   -3    22

```

is:

```
 1    0    0   -8
 0    1    0    1
 0    0    1   -2

```

[Assistant]
(formerly Perl 6)

### Following pseudocode

**Translation of**: Perl

```
sub rref (@m) {
    my ($lead, $rows, $cols) = 0, @m, @m[0];
    for ^$rows -> $r {
        return @m unless $lead < $cols;
        my $i = $r;
        until @m[$i;$lead] {
            next unless ++$i == $rows;
            $i = $r;
            return @m if ++$lead == $cols;
        }
        @m[$i, $r] = @m[$r, $i] if $r != $i;
        @m[$r] »/=» $ = @m[$r;$lead];

        for ^$rows -> $n {
            next if $n == $r;
            @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0);
        }
        ++$lead;
    }
    @m
}

sub rat-or-int ($num) {
    return $num unless $num ~~ Rat;
    return $num.narrow if $num.narrow ~~ Int;
    $num.nude.join: '/';
}

sub say_it ($message, @array) {
    say "\n$message";
    $_».&rat-or-int.fmt(" %5s").say for @array;
}

my @M = (
    [ # base test case
      [  1,  2,  -1,  -4 ],
      [  2,  3,  -1, -11 ],
      [ -2,  0,  -3,  22 ],
    ],
    [ # mix of number styles
      [  3,   0,  -3,    1 ],
      [ .5, 3/2,  -3,   -2 ],
      [ .2, 4/5,  -1.6, .3 ],
    ],
    [ # degenerate case
      [ 1,  2,  3,  4,  3,  1],
      [ 2,  4,  6,  2,  6,  2],
      [ 3,  6, 18,  9,  9, -6],
      [ 4,  8, 12, 10, 12,  4],
      [ 5, 10, 24, 11, 15, -4],
    ],
    [ # larger matrix
      [1,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0,  0],
      [1,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0],
      [1,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0, -1,  0,  0,  0,  0],
      [0,  1,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0, -1,  0,  0,  0],
      [0,  1,  0,  0,  0,  0,  0,  0,  1,  0,  0, -1,  0,  0,  0,  0,  0,  0],
      [0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0, -1,  0],
      [0,  0,  1,  0,  0,  0,  1,  0,  0,  0,  0,  0, -1,  0,  0,  0,  0,  0],
      [0,  0,  1,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0, -1,  0,  0,  0],
      [0,  0,  0,  1,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0, -1,  0,  0],
      [0,  0,  0,  1,  0,  0,  0,  0,  0,  1,  0,  0, -1,  0,  0,  0,  0,  0],
      [0,  0,  0,  0,  1,  0,  0,  1,  0,  0,  0,  0,  0, -1,  0,  0,  0,  0],
      [0,  0,  0,  0,  1,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0, -1,  0],
      [0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0, -1,  0,  0],
      [0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
      [0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0],
      [0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1],
      [0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  1,  0,  0,  0, -1,  0,  0,  0],
   ]
);

for @M -> @matrix {
    say_it( 'Original Matrix', @matrix );
    say_it( 'Reduced Row Echelon Form Matrix', rref(@matrix) );
    say "\n";
}

```

Raku handles rational numbers internally as a ratio of two integers
to maintain precision.
For some situations it is useful to return the ratio
rather than the floating point result.

Output:

```
Original Matrix
     1      2     -1     -4
     2      3     -1    -11
    -2      0     -3     22

Reduced Row Echelon Form Matrix
     1      0      0     -8
     0      1      0      1
     0      0      1     -2

Original Matrix
     3      0     -3      1
   1/2    3/2     -3     -2
   1/5    4/5   -8/5   3/10

Reduced Row Echelon Form Matrix
     1      0      0  -41/2
     0      1      0  -217/6
     0      0      1  -125/6

Original Matrix
     1      2      3      4      3      1
     2      4      6      2      6      2
     3      6     18      9      9     -6
     4      8     12     10     12      4
     5     10     24     11     15     -4

Reduced Row Echelon Form Matrix
     1      2      0      0      3      4
     0      0      1      0      0     -1
     0      0      0      1      0      0
     0      0      0      0      0      0
     0      0      0      0      0      0

Original Matrix
     1      0      0      0      0      0      1      0      0      0      0     -1      0      0      0      0      0      0
     1      0      0      0      0      0      0      1      0      0      0      0     -1      0      0      0      0      0
     1      0      0      0      0      0      0      0      1      0      0      0      0     -1      0      0      0      0
     0      1      0      0      0      0      1      0      0      0      0      0      0      0     -1      0      0      0
     0      1      0      0      0      0      0      0      1      0      0     -1      0      0      0      0      0      0
     0      1      0      0      0      0      0      0      0      0      1      0      0      0      0      0     -1      0
     0      0      1      0      0      0      1      0      0      0      0      0     -1      0      0      0      0      0
     0      0      1      0      0      0      0      0      0      1      0      0      0      0     -1      0      0      0
     0      0      0      1      0      0      0      1      0      0      0      0      0      0      0     -1      0      0
     0      0      0      1      0      0      0      0      0      1      0      0     -1      0      0      0      0      0
     0      0      0      0      1      0      0      1      0      0      0      0      0     -1      0      0      0      0
     0      0      0      0      1      0      0      0      1      0      0      0      0      0      0      0     -1      0
     0      0      0      0      1      0      0      0      0      0      1      0      0      0      0     -1      0      0
     0      0      0      0      0      1      0      0      0      0      0      0      0      0      0      0      0      0
     0      0      0      0      0      0      0      0      0      1      0      0      0      0      0      0      0      0
     0      0      0      0      0      0      0      0      0      0      0      0      0      0      0      1      0      1
     0      0      0      0      0      1      0      0      0      0      1      0      0      0     -1      0      0      0

Reduced Row Echelon Form Matrix
     1      0      0      0      0      0      0      0      0      0      0      0      0      0      0      0      0  17/39
     0      1      0      0      0      0      0      0      0      0      0      0      0      0      0      0      0   4/13
     0      0      1      0      0      0      0      0      0      0      0      0      0      0      0      0      0  20/39
     0      0      0      1      0      0      0      0      0      0      0      0      0      0      0      0      0  28/39
     0      0      0      0      1      0      0      0      0      0      0      0      0      0      0      0      0  19/39
     0      0      0      0      0      1      0      0      0      0      0      0      0      0      0      0      0      0
     0      0      0      0      0      0      1      0      0      0      0      0      0      0      0      0      0   8/39
     0      0      0      0      0      0      0      1      0      0      0      0      0      0      0      0      0  11/39
     0      0      0      0      0      0      0      0      1      0      0      0      0      0      0      0      0    1/3
     0      0      0      0      0      0      0      0      0      1      0      0      0      0      0      0      0      0
     0      0      0      0      0      0      0      0      0      0      1      0      0      0      0      0      0  20/39
     0      0      0      0      0      0      0      0      0      0      0      1      0      0      0      0      0  25/39
     0      0      0      0      0      0      0      0      0      0      0      0      1      0      0      0      0  28/39
     0      0      0      0      0      0      0      0      0      0      0      0      0      1      0      0      0  10/13
     0      0      0      0      0      0      0      0      0      0      0      0      0      0      1      0      0  20/39
     0      0      0      0      0      0      0      0      0      0      0      0      0      0      0      1      0      1
     0      0      0      0      0      0      0      0      0      0      0      0      0      0      0      0      1  32/39

```

### Row operations, procedural code

Re-implemented as elementary matrix row operations. Follow links for background on
row operations
and
reduced row echelon form

```
sub    scale-row ( @M, \scale, \r       ) { @M[r]  =              @M[r]  »×» scale   }
sub    shear-row ( @M, \scale, \r1, \r2 ) { @M[r1] = @M[r1] »+» ( @M[r2] »×» scale ) }
sub   reduce-row ( @M,         \r,  \c  ) { scale-row @M, 1/@M[r;c], r }
sub clear-column ( @M,         \r,  \c  ) { shear-row @M, -@M[$_;c], $_, r for @M.keys.grep: * != r }

my @M = (
    [<  1   2   -1    -4 >],
    [<  2   3   -1   -11 >],
    [< -2   0   -3    22 >],
);

my $column-count = @M[0];
my $col = 0;
for @M.keys -> $row {
      reduce-row( @M, $row, $col );
    clear-column( @M, $row, $col );
    last if ++$col == $column-count;
}

say @$_».fmt(' %4g') for @M;

```

Output:

```
[    1     0     0    -8]
[    0     1     0     1]
[    0     0     1    -2]
```

### Row operations, object-oriented code

The same code as previous section, recast into OO. Also, scale and shear are recast as unscale and unshear, which fit the problem better.

```
class Matrix is Array {
    method  unscale-row ( @M: \scale, \row       ) { @M[row] =            @M[row] »/» scale }
    method  unshear-row ( @M: \scale, \r1,  \r2  ) { @M[r1]  = @M[r1] »-» @M[r2]  »×» scale }
    method   reduce-row ( @M:         \row, \col ) { @M.unscale-row( @M[row;col], row ) }
    method clear-column ( @M:         \row, \col ) { @M.unshear-row( @M[$_;col], $_, row ) for @M.keys.grep: * != row }

    method reduced-row-echelon-form ( @M: ) {
        my $column-count =  @M[0];
        my $col = 0;
        for @M.keys -> $row {
            @M.reduce-row(   $row, $col );
            @M.clear-column( $row, $col );
            return if ++$col == $column-count;
        }
    }
}

my $M = Matrix.new(
    [<  1   2   -1    -4 >],
    [<  2   3   -1   -11 >],
    [< -2   0   -3    22 >],
);

$M.reduced-row-echelon-form;
say @$_».fmt(' %4g') for @$M;

```

Output:

```
[    1     0     0    -8]
[    0     1     0     1]
[    0     0     1    -2]
```


[User]
Task

The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.11

A full path is provided for built-in routines/methods. However for routines exported by pre-compiled modules a precompilation hash is returned, not a proper file path.

```
say &sum.file;
say Date.^find_method("day-of-week").file;

```

Output:

```
SETTING::src/core/Any.pm
SETTING::src/core/Dateish.pm

```


[User]
Task

The goal is to get the methods of an object, as names, values or both.

Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.

[Assistant]
(formerly Perl 6)

You can get a list of an object's methods using .^methods, which is part of the Meta Object Protocol.
Each is represented as a Method object that contains a bunch of info:

```
class Foo {
    method foo ($x)      { }
    method bar ($x, $y)  { }
    method baz ($x, $y?) { }
}

my $object = Foo.new;

for $object.^methods {
    say join ", ", .name, .arity, .count, .signature.gist
}

```

Output:

```
foo, 2, 2, (Foo $: $x, *%_)
bar, 3, 3, (Foo $: $x, $y, *%_)
baz, 2, 3, (Foo $: $x, $y?, *%_)

```


[User]
Task

The goal is to get the properties of an object, as names, values or both.

Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.

[Assistant]
(formerly Perl 6)

You can get a list of an object's attributes (instance variables) using .^attributes, which is part of the Meta Object Protocol..
Each is represented as an Attribute object that contains a bunch of info:

```
class Foo {
    has $!a = now;
    has Str $.b;
    has Int $.c is rw;
}

my $object = Foo.new: b => "Hello", c => 42;

for $object.^attributes {
    say join ", ", .name, .readonly, .container.^name, .get_value($object);
}

```

Output:

```
$!a, True, Any, Instant:1470517602.295992
$!b, True, Str, Hello
$!c, False, Int, 42

```

Public attributes (in this case, $.b and $.c) are really just attributes for which the compiler also auto-generates a method of the same name. See Reflection/List\_methods#Raku.


[User]
Task
:   * match a string against a regular expression
    * substitute part of a string using a regular expression

[Assistant]
(formerly Perl 6)

```
if 'a long string' ~~ /string$/ {
   say "It ends with 'string'";
}

# substitution has a few nifty features

$_ = 'The quick Brown fox';
s:g:samecase/\w+/xxx/;
.say;
# output:
# Xxx xxx Xxx xxx

```


[User]
Given an Array, derive a sequence of elements in which all duplicates are removed.

There are basically three approaches seen here:

* Put the elements into a hash table which does not allow duplicates. The complexity is O(*n*) on average, and O(*n*2) worst case. This approach requires a hash function for your type (which is compatible with equality), either built-in to your language, or provided by the user.
* Sort the elements and remove consecutive duplicate elements. The complexity of the best sorting algorithms is O(*n* log *n*). This approach requires that your type be "comparable", i.e., have an ordering. Putting the elements into a self-balancing binary search tree is a special case of sorting.
* Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does. The complexity is O(*n*2). The up-shot is that this always works on any type (provided that you can test for equality).

[Assistant]
(formerly Perl 6)

```
my @unique = [1, 2, 3, 5, 2, 4, 3, -3, 7, 5, 6].unique;
```

Or just make a set of it.

```
set(1,2,3,5,2,4,3,-3,7,5,6).list
```


[User]
Task

Remove a specific line or a number of lines from a file.

This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).

For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2

Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.

An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.

[Assistant]
(formerly Perl 6)

```
sub MAIN ($filename, $beg, $len) {
    my @lines = split /^^/, slurp $filename;
    unlink $filename;  # or rename
    splice(@lines,$beg,$len) == $len or warn "Too few lines";
    spurt $filename, @lines;
}

```

Output:

```
$ cal >foo
$ ./rmlines
 Usage:
   rmlines <filename> <beg> <len>
$ ./rmlines foo 1 2
$ cat foo
  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 31

```


[User]
Remove vowels from a string

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]
**Works with**: Rakudo version 2020.07

Not going to bother with 'y', it's too touchy feely (How many vowels are in the word my? why? any?) and subject to interpretation.

Otherwise, this should work for *most* Latinate languages.

Apropos of nothing; reminds me of one of my favorite Between the Lions performances: Sloppy Pop - Sometimes Y

Spec is 'Remove vowels from a string'; nothing about what they should be replaced with. I chose to replace them with spaces.

Strings from http://mylanguages.org/. No affiliation, but it's a nice resource. (note: these are not all the same sentence but are all from the same paragraph. They frankly were picked based on their vowel load.)

```
my @vowels = (0x20 .. 0x2fff).map: { .chr if .chr.samemark('x') ~~ m:i/<[aæeiıoœu]>/ }

my $text = q:to/END/;
   Norwegian, Icelandic, German, Turkish, French, Spanish, English:
   Undervisningen skal være gratis, i det minste på de elementære og grunnleggende trinn.
   Skal hún veitt ókeypis, að minnsta kosti barnafræðsla og undirstöðummentu.
   Hochschulunterricht muß allen gleichermaßen entsprechend ihren Fähigkeiten offenstehen.
   Öğrenim hiç olmazsa ilk ve temel safhalarında parasızdır. İlk öğretim mecburidir.
   L'éducation doit être gratuite, au moins en ce qui concerne l'enseignement élémentaire et fondamental.
   La instrucción elemental será obligatoria. La instrucción técnica y profesional habrá de ser generalizada.
   Education shall be free, at least in the elementary and fundamental stages.
   END

put $text.subst(/@vowels/, ' ', :g);

```

Output:

```
N rw g  n,  c l nd c, G rm n, T rk sh, Fr nch, Sp n sh,  ngl sh:
 nd rv sn ng n sk l v r  gr t s,   d t m nst  p  d   l m nt r   g gr nnl gg nd  tr nn.
Sk l h n v  tt  k yp s,  ð m nnst  k st  b rn fr ðsl   g  nd rst ð mm nt .
H chsch l nt rr cht m ß  ll n gl  ch rm ß n  ntspr ch nd  hr n F h gk  t n  ff nst h n.
 ğr n m h ç  lm zs   lk v  t m l s fh l r nd  p r s zd r.  lk  ğr t m m cb r d r.
L' d c t  n d  t  tr  gr t  t ,    m  ns  n c  q   c nc rn  l' ns  gn m nt  l m nt  r   t f nd m nt l.
L   nstr cc  n  l m nt l s r   bl g t r  . L   nstr cc  n t cn c  y pr f s  n l h br  d  s r g n r l z d .
 d c t  n sh ll b  fr  ,  t l  st  n th   l m nt ry  nd f nd m nt l st g s.
```


[User]
Task

Rename:

:   :   :   * a file called     **input.txt**     into     **output.txt**     and
            * a directory called     **docs**     into     **mydocs**.

This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.

It can be assumed that the user has the rights to do so.

(In unix-type systems, only the user root would have
sufficient permissions in the filesystem root.)

[Assistant]
(formerly Perl 6)

```
rename 'input.txt', 'output.txt';
rename 'docs', 'mydocs';
rename '/input.txt', '/output.txt';
rename '/docs', '/mydocs';

```


[User]
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.

## Detailed Description of Programming Task

Rendezvous is a synchronization mechanism based on procedural decomposition. Rendezvous is similar to a procedure call with the difference that the caller and the callee belong to different tasks. The called procedure is usually called an **entry point** of the corresponding task. A call to an entry point is synchronous, i.e. the caller is blocked until completion. For the caller a call to the entry point is indivisible. Internally it consists of:

* Waiting for the callee ready to accept the rendezvous;
* Engaging the rendezvous (servicing the entry point).

The caller may limit the waiting time to the callee to accept the rendezvous. I.e. a rendezvous request can be aborted if not yet accepted by the callee. When accepted the rendezvous is processed until its completion. During this time the caller and the callee tasks stay synchronized. Which context is used to process the rendezvous depends on the implementation which may wish to minimize context switching.

The callee task may accept several rendezvous requests:

* Rendezvous to the same entry point from different tasks;
* Rendezvous to different entry points.

The callee accepts one rendezvous at a time.

Language mechanism of exceptions (if any) has to be consistent with the rendezvous. In particular when an exception is propagated out of a rendezvous it shall do in both tasks. The exception propagation is synchronous within the rendezvous and asynchronous outside it.

An engaged rendezvous can be requeued by the callee to another entry point of its task or to another task, transparently to the caller.

Differently to messages which are usually asynchronous, rendezvous are synchronous, as it was stated before. Therefore a rendezvous does not require marshaling the parameters and a buffer to keep them. Further, rendezvous can be implemented without context switch. This makes rendezvous a more efficient than messaging.

Rendezvous can be used to implement monitor synchronization objects. A monitor guards a shared resource. All users of the resource request a rendezvous to the monitor in order to get access to the resource. Access is granted by accepting the rendezvous for the time while the rendezvous is serviced.

### Language task

Show how rendezvous are supported by the language. If the language does not have rendezvous, provide an implementation of them based on other primitives.

### Use case task

Implement a printer monitor. The monitor guards a printer. There are two printers *main* and *reserve*. Each has a monitor that accepts a rendezvous Print with a text line to print of the printer. The standard output may serve for printing purpose. Each character of the line is printed separately in order to illustrate that lines are printed indivisibly. Each printer has ink for only 5 lines of text. When the *main* printer runs out of ink it redirects its requests to the *reserve* printer. When that runs out of ink too, Out\_Of\_Ink exception propagates back to the caller. Create two writer tasks which print their plagiarisms on the printer. One does *Humpty Dumpty*, another *Mother Goose*.

[Assistant]
(formerly Perl 6)

Raku has no built-in support for rendezvous. Simulated using message passing and a lock. May be slightly bogus.

**Works with**: Rakudo version 2016.08

```
class X::OutOfInk is Exception {
    method message() { "Printer out of ink" }
}

class Printer {
    has Str      $.id;
    has Int      $.ink = 5;
    has Lock     $!lock .= new;
    has ::?CLASS $.fallback;

    method print ($line) {
        $!lock.protect: {
            if    $!ink      { say "$!id: $line"; $!ink-- }
            elsif $!fallback { $!fallback.print: $line }
            else             { die X::OutOfInk.new }
        }
    }
}

my $printer =
    Printer.new: id => 'main', fallback =>
    Printer.new: id => 'reserve';

sub client ($id, @lines) {
    start {
        for @lines {
            $printer.print: $_;
            CATCH {
                when X::OutOfInk { note "<$id stops for lack of ink>"; exit }
            }
        }
        note "<$id is done>";
    }
}

await
    client('Humpty', q:to/END/.lines),
        Humpty Dumpty sat on a wall.
        Humpty Dumpty had a great fall.
        All the king's horses and all the king's men,
        Couldn't put Humpty together again.
        END
    client('Goose', q:to/END/.lines);
        Old Mother Goose,
        When she wanted to wander,
        Would ride through the air,
        On a very fine gander.
        Jack's mother came in,
        And caught the goose soon,
        And mounting its back,
        Flew up to the moon.
        END

```

Output:

```
main: Humpty Dumpty sat on a wall.
main: Old Mother Goose,
main: Humpty Dumpty had a great fall.
main: When she wanted to wander,
main: All the king's horses and all the king's men,
reserve: Would ride through the air,
reserve: Couldn't put Humpty together again.
reserve: On a very fine gander.
<Humpty is done>
reserve: Jack's mother came in,
reserve: And caught the goose soon,
<Goose stops for lack of ink>

```


[User]
Given a series of ones and zeroes in a string, define a repeated string or *rep-string* as a string which is created by repeating a substring of the *first* N characters of the string *truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original*.

For example, the string **10011001100** is a rep-string as the leftmost four characters of **1001** are repeated three times and truncated on the right to give the original string.

Note that the requirement for having the repeat occur two or more times means that the repeating unit is *never* longer than half the length of the input string.

Task

* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice).
* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
* Use the function to indicate the repeating substring if any, in the following:

:   ```
    1001110011
    1110111011
    0010010010
    1010101010
    1111111111
    0100101101
    0100100
    101
    11
    00
    1

    ```

* Show your output on this page.

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)

```
for <1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1> {
    if /^ (.+) $0+: (.*$) <?{ $0.substr(0,$1.chars) eq $1 }> / {
	my $rep = $0.chars;
	say .substr(0,$rep), .substr($rep,$rep).trans('01' => '𝟘𝟙'), .substr($rep*2);
    }
    else {
	say "$_ (no repeat)";
    }
}

```

Output:

```
10011𝟙𝟘𝟘𝟙𝟙
1110𝟙𝟙𝟙𝟘11
001𝟘𝟘𝟙0010
1010𝟙𝟘𝟙𝟘10
11111𝟙𝟙𝟙𝟙𝟙
0100101101 (no repeat)
010𝟘𝟙𝟘0
101 (no repeat)
1𝟙
0𝟘
1 (no repeat)
```

Here's a technique that relies on the fact that XORing the shifted binary number
should set all the lower bits to 0 if there are repeats.
(The cool thing is that shift will automatically
throw away the bits on the right that you want thrown away.)
This produces the same output as above.

```
sub repstr(Str $s) {
    my $bits = :2($s);
    for reverse 1 .. $s.chars div 2 -> $left {
	my $right = $s.chars - $left;
	return $left if $bits +^ ($bits +> $left) == $bits +> $right +< $right;
    }
}

for '1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1'.words {
    if repstr $_ -> $rep {
	say .substr(0,$rep), .substr($rep,$rep).trans('01' => '𝟘𝟙'), .substr($rep*2);
    }
    else {
	say "$_ (no repeat)";
    }
}

```


[User]
Task

Write a procedure which accepts as arguments another procedure and a positive integer.

The latter procedure is executed a number of times equal to the accepted integer.

[Assistant]
(formerly Perl 6)

```
sub repeat (&f, $n) { f() xx $n };

sub example { say rand }

repeat(&example, 3);

```

Output:

```
0.435249779778396
0.647701200726486
0.279289335968417

```

Of course, we could have just written

```
example() xx 3;
```

or even

```
(say rand) xx 3;
```

directly – the custom `repeat` subroutine is just here to satisfy the task description.

Notes on the xx operator:

* Unlike other operators, it evaluates its left-hand-side argument lazily - that's why we can simply call `f()` there rather than passing it as a function object.
* The operator has a return value: A list consisting of the return values of the left-hand-side *(and building lists is in fact what `xx` is usually used for)*.

General notes:

* The `&` sigil in the `repeat` subroutine signature restricts that parameter to types that implement the `Callable` role, and makes it available inside the `repeat` subroutine body as if it were a lexically scoped sub.
* The parentheses in the last line are necessary to disambiguate it as a call to our custom subroutine, rather than an attempt to use the built-in `repeat { ... } while ...` construct.


[User]
Take a string and repeat it some number of times.

Example: repeat("ha", 5)   =>   "hahahahaha"

If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("\*", 5) => "\*\*\*\*\*").

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)

```
print "ha" x 5
```

(Note that the `x` operator isn't quite the same as in Perl 5: it now only creates strings. To create lists, use `xx`.)


[User]
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, **1**. So 1, 11, 111, 1111 & 11111 are all repunits.

Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.

In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)

In base three: 111, 1111111, 1111111111111, etc.

*Repunit primes, by definition, are also circular primes.*

Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits *might* be prime.

Rather than expanding the repunit out as a giant list of **1**s or converting to base 10, it is common to just list the *number* of **1**s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.

Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.

Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.

Task

* For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.

Stretch

* Increase the limit to 2700 (or as high as you have patience for.)

See also

* Wikipedia: Repunit primes * OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2) * OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3) * OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5) * OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6) * OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7) * OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10) * OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11) * OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12) * OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13) * OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14) * OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15) * Related task: Circular primes

[Assistant]
```
my $limit = 2700;

say "Repunit prime digits (up to $limit) in:";

.put for (2..16).hyper(:1batch).map: -> $base {
    $base.fmt("Base %2d: ") ~ (1..$limit).grep(&is-prime).grep( (1 x *).parse-base($base).is-prime )
}

```

Output:

```
Repunit prime digits (up to 2700) in:
Base  2: 2 3 5 7 13 17 19 31 61 89 107 127 521 607 1279 2203 2281
Base  3: 3 7 13 71 103 541 1091 1367 1627
Base  4: 2
Base  5: 3 7 11 13 47 127 149 181 619 929
Base  6: 2 3 7 29 71 127 271 509 1049
Base  7: 5 13 131 149 1699
Base  8: 3
Base  9:
Base 10: 2 19 23 317 1031
Base 11: 17 19 73 139 907 1907 2029
Base 12: 2 3 5 19 97 109 317 353 701
Base 13: 5 7 137 283 883 991 1021 1193
Base 14: 3 7 19 31 41 2687
Base 15: 3 43 73 487 2579
Base 16: 2
```

*And for my own amusement, also tested up to 2700.*

```
Base 17: 3 5 7 11 47 71 419
Base 18: 2
Base 19: 19 31 47 59 61 107 337 1061
Base 20: 3 11 17 1487
Base 21: 3 11 17 43 271
Base 22: 2 5 79 101 359 857
Base 23: 5
Base 24: 3 5 19 53 71 653 661
Base 25:
Base 26: 7 43 347
Base 27: 3
Base 28: 2 5 17 457 1423
Base 29: 5 151
Base 30: 2 5 11 163 569 1789
Base 31: 7 17 31
Base 32:
Base 33: 3 197
Base 34: 13 1493
Base 35: 313 1297
Base 36: 2
```


[User]
Introduction

* Calculate the resistance of a network of resistors.
* The resistors can be connected in series or parallel.
* Use infix or RPN to state the network.
* Calculate resistance, voltage, current and power for every resistor and operation.

Background

* Serial Resistors: the sum of the resistors gives the equivalent resistor
* Parallel Resistors: the inverse of the sum of the inverse of the resistors
* The voltage drops over the resistors
* Current = Resistance / Voltage
* Power = Current \* Voltage

Input

Resistance Calculator

* Infix: ((((10 + 2) \* 6 + 8) \* 6 + 4) \* 8 + 4) \* 8 + 6
* RPN: 10 2 + 6 \* 8 + 6 \* 4 + 8 \* 4 + 8 \* 6 +
* Voltage = 18.0 V

Output

* 10.000 ohms in the upper left corner is the equivalent resistance.
* The first operation is 10 + 2 = 12 which can be found in the three middle rows.

```
    Ohm     Volt   Ampere     Watt  Network tree
 10.000   18.000    1.800   32.400  +
  4.000    7.200    1.800   12.960  | *
  8.000    7.200    0.900    6.480  | | +
  4.000    3.600    0.900    3.240  | | | *
  8.000    3.600    0.450    1.620  | | | | +
  4.000    1.800    0.450    0.810  | | | | | *
 12.000    1.800    0.150    0.270  | | | | | | +
  4.000    0.600    0.150    0.090  | | | | | | | *
 12.000    0.600    0.050    0.030  | | | | | | | | +
 10.000    0.500    0.050    0.025  | | | | | | | | | r
  2.000    0.100    0.050    0.005  | | | | | | | | | r
  6.000    0.600    0.100    0.060  | | | | | | | | r
  8.000    1.200    0.150    0.180  | | | | | | | r
  6.000    1.800    0.300    0.540  | | | | | | r
  4.000    1.800    0.450    0.810  | | | | | r
  8.000    3.600    0.450    1.620  | | | | r
  4.000    3.600    0.900    3.240  | | | r
  8.000    7.200    0.900    6.480  | | r
  6.000   10.800    1.800   19.440  | r

```

[Assistant]
(formerly Perl 6)

### Infix

**Translation of**: Nim

```
class Resistor {
    has Str        $.symbol;
    has Numeric  ( $.voltage, $.resistance );
    has Resistor ( $.a, $.b );

    method res ( ) {
        given $.symbol {
            when '+' { return $.a.res + $.b.res }
            when '*' { return 1 / (1 / $.a.res  +  1 / $.b.res) }
            default  { return $.resistance }
        }
    }

    method set-voltage ( Numeric $voltage ) {
        given $.symbol {
            when '+' {
                my $ra = $.a.res;
                my $rb = $.b.res;
                $.a.set-voltage( $ra / ($ra+$rb) * $voltage );
                $.b.set-voltage( $rb / ($ra+$rb) * $voltage );
            }
            when '*' {
                $.a.set-voltage( $voltage );
                $.b.set-voltage( $voltage );
            }
        }
        $!voltage = $voltage;
    }
    method current ( ) { return $.voltage / self.res     }
    method effect  ( ) { return $.voltage * self.current }

    method report ( Int $level = 1 ) {
        my $pad = '| ' x $level;
        my $f = ( self.res, $.voltage, self.current, self.effect ).fmt('%8.3f');
        say "$f $pad$.symbol";
        $.a.report( $level+1 ) if $.a;
        $.b.report( $level+1 ) if $.b;
    }
}
multi sub infix:<+> (Resistor $a, Resistor $b) { $a.new( symbol => '+', :$a, :$b ) }
multi sub infix:<*> (Resistor $a, Resistor $b) { $a.new( symbol => '*', :$a, :$b ) }

my Resistor ($R1, $R2, $R3, $R4, $R5, $R6, $R7, $R8, $R9, $R10) =
    map { Resistor.new: symbol => 'r', resistance => $_ },
    6, 8, 4, 8, 4, 6, 8, 10, 6, 2;

my $node = (((($R8 + $R10) * $R9 + $R7) * $R6 + $R5)
                           * $R4 + $R3) * $R2 + $R1;
$node.set-voltage(18);

say '     Ohm     Volt   Ampere     Watt  Network tree';
$node.report;

```

Output:

```
     Ohm     Volt   Ampere     Watt  Network tree
  10.000   18.000    1.800   32.400 | +
   4.000    7.200    1.800   12.960 | | *
   8.000    7.200    0.900    6.480 | | | +
   4.000    3.600    0.900    3.240 | | | | *
   8.000    3.600    0.450    1.620 | | | | | +
   4.000    1.800    0.450    0.810 | | | | | | *
  12.000    1.800    0.150    0.270 | | | | | | | +
   4.000    0.600    0.150    0.090 | | | | | | | | *
  12.000    0.600    0.050    0.030 | | | | | | | | | +
  10.000    0.500    0.050    0.025 | | | | | | | | | | r
   2.000    0.100    0.050    0.005 | | | | | | | | | | r
   6.000    0.600    0.100    0.060 | | | | | | | | | r
   8.000    1.200    0.150    0.180 | | | | | | | | r
   6.000    1.800    0.300    0.540 | | | | | | | r
   4.000    1.800    0.450    0.810 | | | | | | r
   8.000    3.600    0.450    1.620 | | | | | r
   4.000    3.600    0.900    3.240 | | | | r
   8.000    7.200    0.900    6.480 | | | r
   6.000   10.800    1.800   19.440 | | r
```


[User]
Introduction

Calculate the resistance of any resistor network.

* The network is stated with a string.
* The resistors are separated by a vertical dash.
* Each resistor has
  + a starting node
  + an ending node
  + a resistance

Background

Arbitrary Resistor Grid

Regular 3x3 mesh, using twelve one ohm resistors

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

```

Battery connection nodes: 0 and 8

```
assert 3/2 == network(9,0,8,"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1")

```

Regular 4x4 mesh, using 24 one ohm resistors

```
 0 - 1 - 2 - 3
 |   |   |   |
 4 - 5 - 6 - 7
 |   |   |   |
 8 - 9 -10 -11
 |   |   |   |
12 -13 -14 -15

```

Battery connection nodes: 0 and 15

```
assert 13/7 == network(16,0,15,"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1")

```

Ten resistor network

Picture

Battery connection nodes: 0 and 1

```
assert 10 == network(7,0,1,"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8")

```

Wheatstone network

Picture

This network is not possible to solve using the previous Resistance Calculator
as there is no natural starting point.

```
assert 180 == network(4,0,3,"0 1 150|0 2 50|1 3 300|2 3 250")

```

[Assistant]
(formerly Perl 6)

**Translation of**: Python

```
sub gauss ( @m is copy ) {
    for @m.keys -> \i {
        my \k = max |(i .. @m.end), :by({ @m[$_][i].abs });

        @m[i, k] .= reverse if \k != i;

        .[i ^.. *] »/=» .[i] given @m[i];

        for i ^.. @m.end -> \j {
            @m[j][i ^.. *] »-=« ( @m[j][i] «*« @m[i][i ^.. *] );
        }
    }
    for @m.keys.reverse -> \i {
        @m[^i]».[*-1] »-=« ( @m[^i]».[i] »*» @m[i][*-1] );
    }
    return @m».[*-1];
}
sub network ( Int \n, Int \k0, Int \k1, Str \grid ) {
    my @m = [0 xx n+1] xx n;

    for grid.split('|') -> \resistor {
        my ( \a, \b, \r_inv ) = resistor.split(/\s+/, :skip-empty);
        my \r = 1 / r_inv;

        @m[a][a] += r;
        @m[b][b] += r;
        @m[a][b] -= r if a > 0;
        @m[b][a] -= r if b > 0;
    }
    @m[k0][k0]  = 1;
    @m[k1][*-1] = 1;

    return gauss(@m)[k1];
}
use Test;
my @tests =
    (   10,   7, 0,     1, '0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8' ),
    (  3/2, 3*3, 0, 3*3-1, '0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1' ),
    ( 13/7, 4*4, 0, 4*4-1, '0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1' ),
    (  180,   4, 0,     3, '0 1 150|0 2 50|1 3 300|2 3 250' ),
;
plan +@tests;
is .[0], network( |.[1..4] ), .[4].substr(0,10)~'…' for @tests;

```


[User]
Task

Given    10×10    grid nodes   (as shown in the image)   interconnected by    1Ω    resistors as shown,

find the resistance between points   **A**   and   **B**.

See also

* (humor, nerd sniping)   xkcd.com cartoon (you can solve that for extra credits)
* An article on how to calculate this and an implementation in Mathematica

[Assistant]
(formerly Perl 6)

**Translation of**: C

```
my $*TOLERANCE = 1e-12;

sub set-boundary(@mesh,@p1,@p2) {
    @mesh[ @p1[0] ; @p1[1] ] =  1;
    @mesh[ @p2[0] ; @p2[1] ] = -1;
}

sub solve(@p1, @p2, Int \w, Int \h) {
    my @d     = [0 xx w] xx h;
    my @V     = [0 xx w] xx h;
    my @fixed = [0 xx w] xx h;
    set-boundary(@fixed,@p1,@p2);

    loop {
        set-boundary(@V,@p1,@p2);
        my $diff = 0;
        for (flat ^h X ^w) -> \i, \j {
            my @neighbors = (@V[i-1;j], @V[i;j-1], @V[i+1;j], @V[i;j+1]).grep: *.defined;
            @d[i;j] = my \v = @V[i;j] - @neighbors.sum / @neighbors;
            $diff += v × v unless @fixed[i;j];
        }
        last if $diff =~= 0;

        for (flat ^h X ^w) -> \i, \j {
            @V[i;j] -= @d[i;j];
        }
    }

    my @current;
    for (flat ^h X ^w) -> \i, \j {
        @current[ @fixed[i;j]+1 ] += @d[i;j] × (?i + ?j + (i < h-1) + (j < w-1) );
    }
    (@current[2] - @current[0]) / 2
}

say 2 / solve (1,1), (6,7), 10, 10;

```

Output:

```
1.60899124172989
```


[User]
Task

Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.

Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.

This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.

Related task

* Send an unknown method call.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

```
class Farragut {
    method FALLBACK ($name, *@rest) {
        say "{self.WHAT.raku}: $name.tc() the @rest[], full speed ahead!";
    }
}

class Sparrow is Farragut { }

Farragut.damn: 'torpedoes';
Sparrow.hoist: <Jolly Roger mateys>;

```

Output:

```
Farragut: Damn the torpedoes, full speed ahead!
Sparrow: Hoist the Jolly Roger mateys, full speed ahead!
```

FALLBACK will be called for any method that is not defined. Since any class inherits from Any, there will be plenty of already defined methods. Those which are not defined can also be used as L-Values by the magic of is rw.

```
class L-Value {
    our $.value = 10;
    method FALLBACK($name, |c) is rw { $.value }
}

my $l = L-Value.new;
say $l.any-odd-name; # 10
$l.some-other-name = 42;
say $l.i-dont-know; # 42

```