[User]
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.

So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt

```
cat Traceback.txt :

2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
    result = plugin.run()
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
    for process_info in info.get_all_process_info():
  File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
    process_info = self.get_process_info(process_id)
  File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
    cmd_line = file.readline()
  File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)

2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }

[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.

[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757]   File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757]     from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app

2021-04-23 17:13:14,425 ERROR    Network plugin raised an exception.
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
    result = plugin.run()
  File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
    device_info = self._get_device_info()
  File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
    speed, duplex = get_network_interface_speed(
  File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
    res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'

11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable

12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory

Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }

```

The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :

```
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------

```

[Assistant]
Generalized. Pipe in the file from the shell, user definable search term and entry point.

```
unit sub MAIN ( :$for, :$at = 0 );

put slurp.split( /\n\n+/ ).grep( { .contains: $for } )
         .map( { .substr: .index: $at } )
         .join: "\n----------------\n"

```

Example output using command line:

```
   raku search.raku --for='SystemError' --at='Traceback' < traceback.txt

```

*Matches expected except for not having a extraneous trailing paragraph separator.*

```
Traceback (most recent call last):
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
    File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
    WaitForTask(task)
    File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
    raise task.info.error
    vmodl.fault.SystemError: (vmodl.fault.SystemError) {
    dynamicType = ,
    dynamicProperty = (vmodl.DynamicProperty) [],
    msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
    faultCause = ,
    faultMessage = (vmodl.LocalizableMessage) [],
    reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
    }
```


[User]
Task

Create a temporary file, **securely and exclusively** (opening it such that there are no possible race conditions).

It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).

The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.09

This is something best done with a module which is heavily tested, tries to account for all corner cases and automatically cleans up after itself.

Almost verbatim from the synopsis:

```
use File::Temp;

# Generate a temp file in a temp dir
my ($filename0,$filehandle0) = tempfile;

# specify a template for the filename
#  * are replaced with random characters
my ($filename1,$filehandle1) = tempfile("******");

# Automatically unlink files at DESTROY (this is the default)
my ($filename2,$filehandle2) = tempfile("******", :unlink);

# Specify the directory where the tempfile will be created
my ($filename3,$filehandle3) = tempfile(:tempdir("/path/to/my/dir"));

# don't unlink this one
my ($filename4,$filehandle4) = tempfile(:tempdir('.'), :!unlink);

# specify a prefix, a suffix, or both for the filename
my ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(".txt"));

```


[User]
Task

For each number list of **6**-digit SEDOLs, calculate and append the checksum digit.

That is, given this input:

```
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030

```

Produce this output:

```
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300

```

Extra credit

Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.

Related tasks

* Luhn test
* ISIN

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

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

```
sub sedol( Str $s ) {
    die 'No vowels allowed' if $s  ~~ /<[AEIOU]>/;
    die 'Invalid format'    if $s !~~ /^ <[0..9B..DF..HJ..NP..TV..Z]>**6 $ /;

    my %base36 = (flat 0..9, 'A'..'Z') »=>« ^36;
    my @weights = 1, 3, 1, 7, 3, 9;

    my @vs = %base36{ $s.comb };
    my $checksum = [+] @vs Z* @weights;
    my $check_digit = (10 - $checksum % 10) % 10;
    return $s ~ $check_digit;
}

say sedol($_) for <
    710889
    B0YBKJ
    406566
    B0YBLH
    228276
    B0YBKL
    557910
    B0YBKR
    585284
    B0YBKT
    B00030
>;

```


[User]
In epidemiology, retrospective analyses have well-known limitations compared to prospective studies.

One such limitation is the occurrence of *selection bias* in the choice of subjects between treated
and untreated groups about whom the data is collected. For example, a treatment may have only been
given to persons who were less severely ill, which would bias the results in favor of such subjects
appearing to have done better because of the treatment when the biased group is then compared to those
who who did not receive the study treatment. Or, in a retrospective study, there may a choice to place
subjects in a particular study group using a method which is inadvertently biased by the outcome being
measured. Creating a programming example of a simulation of such selection bias in the design of a
retrospective study is the topic of this task.

The genuine, historical example (only partially approximated in this task) is of a study done of persons who, over a course
of 180 days, may or may not have become infected with Covid-19. Prior to becoming ill, these subjects may or may not have taken an available medication, which was actually taken on a particular schedule not used here, but is approximated by stating the medication was taken in doses of 3, 6, or 9 mg daily. The historical study then divided its subjects into three groups based on their cumulative dosage of the study medication:

* Group UNTREATED were those who did not take the study medication at all before they got Covid-19, including those who exited the study period without Covid-19 and having never taken the study medication.

* Group IRREGULAR is those who took the study medication but whose cumulative dose was less than a certain amount (approximated for our purposes as 100 mg) before they either came down with Covid-19 during the study or the study period ended.

* Group REGULAR is those who took (our approximation is >= 100 mg) of the study medication either before they came down with Covid-19 or took >= 100 mg by the end of the study and never became infected during the study.

Assumptions for the study simulation programming task

* Daily risk of getting Covid-19 infection for each subject was 0.1% per day, or 18% over the 180 cumulative days of the study.

* The probability of starting treatment medication for anyone not already taking it was 0.5% per day. For those who started medication, the chance of continuing the treatment was increased 50-fold to 25% each day, since most who started the medication continued to take it to some extent.

* Study dose per day is random between the approximation for the simulation of 3, 6 and 9 mg. The daily cumulative dosage is used to determine the group the subject is in, unless a subject develops Covid-19. If a subject was diagnosed with Covid-19, their group at the time of that diagnosis is used in the statistical analysis of that group.

Task

* Create a simulation of the subjects, keeping track of their medication dosages, group membership, and Covid-19 status during the study.

* Use at least 1000 subjects in the simulation over the 180 days (historically, the study size was 80,000).

* Statistics used are to be the Kruskal statistic for the analysis of multiple groups, with the boolean study outcome variable whether the subject got Covid-19 during the study period, analyzed versus category. If the programming language does not have a statistical package for such a test, calculation of the Kruskal H statistic may be used, since any values of H over about 50 are considered very highly indicative of significant group difference. A description of that test is found at Kruskal-Wallis test.

* You should get a statistical result highly favoring the REGULAR group.

Stretch task

* Show monthly outcomes.

A note regarding outcome: Note that by simulation design all subjects must have an IDENTICAL risk, that is 0.1 per cent or p = 0.001 per day, of developing Covid-19. Because of the design, any statistical differences between the groups CANNOT come from an influence of the treatment on that risk, but must come from some other feature of the study design.

See also
:   * Wikipedia - Selection Bias * Wikipedia - Retrospective studies * UCDavis (pdf) Challenges in Retrospective studies

[Assistant]
**Translation of**: Phix

```
# 20221025 Raku programming solution

enum <UNTREATED REGULAR IRREGULAR>;
my \DOSE_FOR_REGULAR = 100;
my ($nSubjects,$duration,$interval) = 10000, 180, 30;
my (@dosage,@category,@hadcovid) := (0,UNTREATED,False)>>.&{($_ xx $nSubjects).Array};

sub update($pCovid=1e-3, $pStartTreatment=5e-3, $pRedose=¼, @dRange=<3 6 9>) {
   for 0 ..^ @dosage.elems -> \i {
      unless @hadcovid[i] {
         if rand < $pCovid {
            @hadcovid[i] = True
         } else {
            my $dose = @dosage[i];
            if $dose==0 && rand < $pStartTreatment or $dose > 0 && rand < $pRedose {
	           @dosage[i]   = $dose += @dRange.roll;
               @category[i] = ($dose > DOSE_FOR_REGULAR) ?? REGULAR !! IRREGULAR
            }
         }
      }
   }
}

sub kruskal (@sets) {
   my $n          = ( my @ranked = @sets>>.List.flat.sort ).elems;
   my @sr         = 0 xx @sets.elems;
   my $ix         = (@ranked.first: * == True, :k)+1,
   my ($arf,$art) = ($ix, $ix+$n) >>/>> 2;

   for @sets.kv -> \i,@set { for @set -> $b { @sr[i] += $b ?? $art !! $arf } }

   my $H = [+] @sr.kv.map: -> \i,\s { s*s/@sets[i].elems }
   return 12/($n*($n+1)) * $H - 3 * ($n + 1)
}

say "Total subjects: $nSubjects\n";

my ($midpoint,$unt,$irr,$reg,$hunt,$hirr,$hreg,@sunt,@sirr,@sreg)=$duration div 2;

for 1 .. $duration -> \day {
   update();
   if day %% $interval or day == $duration or day == $midpoint {
      @sunt = @hadcovid[ @category.grep: UNTREATED,:k ];
      @sirr = @hadcovid[ @category.grep: IRREGULAR,:k ];
      @sreg = @hadcovid[ @category.grep: REGULAR,  :k ];
      ($unt,$hunt,$irr,$hirr,$reg,$hreg)=(@sunt,@sirr,@sreg).map:{|(.elems,.sum)}
   }
   if day %% $interval {
      printf "Day %d:\n",day;
      printf "Untreated:     N = %4d, with infection = %4d\n",  $unt,$hunt;
      printf "Irregular Use: N = %4d, with infection = %4d\n",  $irr,$hirr;
      printf "Regular Use:   N = %4d, with infection = %4d\n\n",$reg,$hreg
   }
   if day == $midpoint | $duration {
      my $stage = day == $midpoint ?? 'midpoint' !! 'study end';
      printf "At $stage, Infection case percentages are:\n";
      printf "  Untreated : %f\n",  100*$hunt/$unt;
      printf "  Irregulars: %f\n",  100*$hirr/$irr;
      printf "  Regulars  : %f\n\n",100*$hreg/$reg
   }
}

printf "Final statistics: H = %f\n", kruskal ( @sunt, @sirr, @sreg )

```

Output:

```
Total subjects: 10000

Day 30:
Untreated:     N = 8616, with infection =  314
Irregular Use: N = 1383, with infection =   27
Regular Use:   N =    1, with infection =    0

Day 60:
Untreated:     N = 7511, with infection =  561
Irregular Use: N = 2308, with infection =   87
Regular Use:   N =  181, with infection =    1

Day 90:
Untreated:     N = 6571, with infection =  760
Irregular Use: N = 2374, with infection =  141
Regular Use:   N = 1055, with infection =   19

At midpoint, Infection case percentages are:
  Untreated : 11.565972
  Irregulars: 5.939343
  Regulars  : 1.800948

Day 120:
Untreated:     N = 5757, with infection =  909
Irregular Use: N = 2097, with infection =  189
Regular Use:   N = 2146, with infection =   61

Day 150:
Untreated:     N = 5092, with infection = 1054
Irregular Use: N = 1832, with infection =  238
Regular Use:   N = 3076, with infection =  132

Day 180:
Untreated:     N = 4530, with infection = 1172
Irregular Use: N = 1615, with infection =  282
Regular Use:   N = 3855, with infection =  229

At study end, Infection case percentages are:
  Untreated : 25.871965
  Irregulars: 17.461300
  Regulars  : 5.940337

Final statistics: H = 248.419454
```


[User]
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.

Copy part of input records to an output file.

Show how file processing as known from PL/I or COBOL can be implemented in the
language of your choice.

Here, a file is not 'just' a sequence of bytes or lines but a sequence of *records* (structured data).

The structure is usually described by declarations contained in an *INCLUDE* file (PL/I) or *COPY BOOK* (COBOL).

The *by name* assignment is a little extra available in PL/I.

Data conversions may be necessary (as shown here for data element *c* in the Go listing).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.10

I have no idea how PL/I or COBOL store records and little enthusiasm to research it. If the task author can't be bothered to spell out what the format should look like, then I have no compunction about just making something up out of whole cloth. In the absence of better guidance I am going to make a binary encoded data file format with fixed sized fields consisting of a mix of ISO-8859-1 encoded text and raw binary (hex) encoded integers.

This is WAY more complicated than it could be. Could achieve the same effect in one or two lines of code, but this explicitly shows some of the possible mechanics.

Since the sfc.dat file is binary encoded, I can't include it here easily as text so here is a link to an online copy instead.

```
my @format = ( # arbitrary and made up record format
    'field a' => { offset => 0,  length => 5, type => 'Str' },
    'field b' => { offset => 5,  length => 5, type => 'Str' },
    'field c' => { offset => 10, length => 4, type => 'Int' },
    'field d' => { offset => 14, length => 1, type => 'Str' },
    'field e' => { offset => 15, length => 5, type => 'Str' }
);

my $record-length = @format[*]».value».<length>.sum;

my $in = './sfc.dat'.IO.open :r :bin;

say "Input data as read from $in:";
my @records;
@records.push: get-record($in, $record-length) until $in.eof;
.perl.say for @records;

# not going to bother to actually write out to a file, if you really want to,
# supply a file handle to a local file
say "\nOutput:";
my $outfile = $*OUT; # or some other filename, whatever.

for @records -> $r {
    $outfile.printf( "%-5s%s%08x%5s\n", flat $r.{'field a','field d','field c'}, 'xxxxx' );
}

sub get-record($fh, $bytes) {
    my $record = $fh.read($bytes);
    return ().Slip unless $record.elems == $bytes;
    my %r = @format.map: {
        .key => do given $_.value.<type> -> $type
        {
            when $type eq 'Str' { $record.subbuf($_.value.<offset>, $_.value.<length>).decode }
            when $type eq 'Int' { sum $record.subbuf($_.value.<offset>, $_.value.<length>) Z+< (24,16,8,0) }
            default             { $record.subbuf($_.value.<offset>, $_.value.<length>) } # Buf
        }
    }
}

```

Output:

```
Input data as read from ./sfc.dat:
${"field a" => "A    ", "field b" => "bbbbB", "field c" => 1, "field d" => "+", "field e" => "d2345"}
${"field a" => "AA   ", "field b" => "bbbBB", "field c" => 2, "field d" => "+", "field e" => "1d345"}
${"field a" => "AAA  ", "field b" => "bbBBB", "field c" => 3, "field d" => "+", "field e" => "12d45"}
${"field a" => "AAAA ", "field b" => "bBBBB", "field c" => 4, "field d" => "-", "field e" => "123d5"}
${"field a" => "AAAAA", "field b" => "BBBBB", "field c" => 3729368837, "field d" => "-", "field e" => "1234d"}

Output:
A    +00000001xxxxx
AA   +00000002xxxxx
AAA  +00000003xxxxx
AAAA -00000004xxxxx
AAAAA-de49a705xxxxx
```


[User]
Task

This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.

Given the string: "abracadabra", replace programatically:

* the first 'a' with 'A'
* the second 'a' with 'B'
* the fourth 'a' with 'C'
* the fifth 'a' with 'D'
* the first 'b' with 'E'
* the second 'r' with 'F'

Note that there is no replacement for the third 'a', second 'b' or first 'r'.

The answer should, of course, be : "AErBcadCbFD".

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]
Set up to not particularly rely on absolute structure of the word. Demonstrate with both the original 'abracadabra' and with a random shuffled instance.

```
sub mangle ($str is copy) {
    $str.match(:ex, 'a')».from.map: { $str.substr-rw($_, 1) = 'ABaCD'.comb[$++] };
    $str.=subst('b', 'E');
    $str.substr-rw($_, 1) = 'F' given $str.match(:ex, 'r')».from[1];
    $str
}

say $_, ' -> ', .&mangle given 'abracadabra';

say $_, ' -> ', .&mangle given 'abracadabra'.comb.pick(*).join;

```

Output:

```
abracadabra -> AErBcadCbFD
caarabadrab -> cABraECdFDb
```


[User]
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.

The task is:

```
 Display the first 50 self numbers;
 I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.

```

224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.

See also

* OEIS: A003052 - Self numbers or Colombian numbers * Wikipedia: Self numbers

[Assistant]
Translated the low memory version of the Go entry but showed only the first 50 self numbers. The machine for running this task (a Xeon E3110+8GB memory) is showing its age as, 1) took over 6 minutes to complete the Go entry, 2) not even able to run the other two Go alternative entries and 3) needed over 47 minutes to reach 1e6 iterations here. Anyway I will try this on an i5 box later to see how it goes.

**Translation of**: Go

```
# 20201127 Raku programming solution

my ( $st, $count, $i, $pow, $digits, $offset, $lastSelf, $done, @selfs) =
     now,      0,  1,   10,       1,       9,         0, False;

# while ( $count < 1e8 ) {
until $done {
   my $isSelf = True;
   my $sum    = (my $start = max ($i-$offset), 0).comb.sum;
   loop ( my $j = $start; $j < $i; $j+=1 ) {
      if $j+$sum == $i { $isSelf = False and last }
      ($j+1)%10 != 0 ?? ( $sum+=1 ) !! ( $sum = ($j+1).comb.sum ) ;
   }
   if $isSelf {
      $count+=1;
      $lastSelf = $i;
      if $count ≤ 50 {
         @selfs.append: $i;
         if $count == 50 {
            say "The first 50 self numbers are:\n", @selfs;
            $done = True;
         }
      }
   }
   $i+=1;
   if $i % $pow == 0 {
      $pow *= 10;
      $digits+=1 ;
      $offset = $digits * 9
   }
}

# say "The 100 millionth self number is ", $lastSelf;
# say "Took ", now - $st, " seconds."

```

Output:

```
The first 50 self numbers are:
[1 3 5 7 9 20 31 42 53 64 75 86 97 108 110 121 132 143 154 165 176 187 198 209 211 222 233 244 255 266 277 288 299 310 312 323 334 345 356 367 378 389 400 411 413 424 435 446 457 468]
```


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

There are several so-called "self-describing" or "self-descriptive" integers.

An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.

For example,   **2020**   is a four-digit self describing number:

* position   0   has value   2   and there are two 0s in the number;
* position   1   has value   0   and there are no 1s in the number;
* position   2   has value   2   and there are two 2s;
* position   3   has value   0   and there are zero 3s.

Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000.

Task Description

1. Write a function/routine/method/... that will check whether a given positive integer is self-describing.
2. As an optional stretch goal - generate and display the set of self-describing numbers.

Related tasks

* Fours is the number of letters in the ...
* Look-and-say sequence
* Number names
* Self-referential sequence
* Spelling of ordinal numbers

[Assistant]
(formerly Perl 6)

```
my @values = <1210 2020 21200 3211000
42101000 521001000 6210001000 27 115508>;

for @values -> $test {
    say "$test is {sdn($test) ?? '' !! 'NOT ' }a self describing number.";
}

sub sdn($n) {
    my $s = $n.Str;
    my $chars = $s.chars;
    my @a = +«$s.comb;
    my @b;
    for @a -> $i {
        return False if $i >= $chars;
        ++@b[$i];
    }
    @b[$_] //= 0 for ^$chars;
    @a eqv @b;
}

.say if .&sdn for ^9999999;

```

Output:

```
1210 is a self describing number.
2020 is a self describing number.
21200 is a self describing number.
3211000 is a self describing number.
42101000 is a self describing number.
521001000 is a self describing number.
6210001000 is a self describing number.
27 is NOT a self describing number.
115508 is NOT a self describing number.
1210
2020
21200
3211000

```


[User]
This task has been flagged for clarification due to it being believed to be too difficult to implement in a reasonable amount of effort in more than one (usually very specialised) language. It may need to be divided into multiple tasks or modified substantially so that multiple implementations are practical, and that may cause code on this page in its current state to be flagged incorrect afterwards. See this page's Talk page for discussion.

Implement a self-hosting compiler for your language, i.e.:   create a compiler that is implemented in the language it's supposed to compile.

Extra credit for any solution that can compile in an online compiler such as Ideone.

If this isn't feasible due to language complexity, link to external projects that achieve this task.

[Assistant]
(formerly Perl 6)

```
use MONKEY-SEE-NO-EVAL;
EVAL slurp

```


[User]
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.

**Semiprimes**   are also known as:

:   :   :   * **semi-primes**
            * **biprimes**
            * **bi-primes**
            * ***2-almost***    primes
            * or simply:    ***P2***

Example

```
   1679  =  23 × 73

```

(This particular number was chosen as the length of the Arecibo message).

Task

Write a function determining whether a given number is semiprime.

See also

* The Wikipedia article:  semiprime.
* The Wikipedia article:  almost prime.
* The OEIS sequence:  A001358: semiprimes  which has a shorter definition: *the product of two primes*.

[Assistant]
(formerly Perl 6)
Here is a naive, grossly inefficient implementation.

```
sub is-semiprime (Int $n --> Bool) {
    not $n.is-prime and
        .is-prime given
        $n div first $n %% *, flat grep &is-prime, 2 .. *;
}

use Test;
my @primes = flat grep &is-prime, 2 .. 100;
for ^5 {
    nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1;
    ok  is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2;
    nok is-semiprime([*] my @f3 = @primes.roll(3)), ~@f3;
    nok is-semiprime([*] my @f4 = @primes.roll(4)), ~@f4;
}

```

Output:

```
ok 1 - 17
ok 2 - 47 23
ok 3 - 23 37 41
ok 4 - 53 37 67 47
ok 5 - 5
ok 6 - 73 43
ok 7 - 13 53 71
ok 8 - 7 79 37 71
ok 9 - 41
ok 10 - 71 37
ok 11 - 37 53 43
ok 12 - 3 2 47 67
ok 13 - 17
ok 14 - 41 61
ok 15 - 71 31 79
ok 16 - 97 17 73 17
ok 17 - 61
ok 18 - 73 47
ok 19 - 13 19 5
ok 20 - 37 97 11 31
```

### More efficient example

Here is a more verbose, but MUCH more efficient implementation. Demonstrating using it to find an infinite list of semiprimes and to check a range of integers to find the semiprimes.

**Works with**: Rakudo version 2017.02

```
sub is-semiprime ( Int $n where * > 0 ) {
    return False if $n.is-prime;
    my $factor = find-factor( $n );
    return True if $factor.is-prime && ( $n div $factor ).is-prime;
    False;
}

sub find-factor ( Int $n, $constant = 1 ) {
    my $x      = 2;
    my $rho    = 1;
    my $factor = 1;
    while $factor == 1 {
        $rho *= 2;
        my $fixed = $x;
        for ^$rho {
            $x = ( $x * $x + $constant ) % $n;
            $factor = ( $x - $fixed ) gcd $n;
            last if 1 < $factor;
        }
    }
    $factor = find-factor( $n, $constant + 1 ) if $n == $factor;
    $factor;
}

INIT my $start = now;

# Infinite list of semiprimes
constant @semiprimes = lazy gather for 4 .. * { .take if .&is-semiprime };

# Show the semiprimes < 100
say 'Semiprimes less than 100:';
say @semiprimes[^ @semiprimes.first: * > 100, :k ], "\n";

# Check individual integers, or in this case, a range
my $s = 2⁹⁷ - 1;
say "Is $_ semiprime?: ", .&is-semiprime for $s .. $s + 30;

say 'elapsed seconds: ', now - $start;

```

Output:

```
Semiprimes less than 100:
(4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95)

Is 158456325028528675187087900671 semiprime?: True
Is 158456325028528675187087900672 semiprime?: False
Is 158456325028528675187087900673 semiprime?: False
Is 158456325028528675187087900674 semiprime?: False
Is 158456325028528675187087900675 semiprime?: False
Is 158456325028528675187087900676 semiprime?: False
Is 158456325028528675187087900677 semiprime?: False
Is 158456325028528675187087900678 semiprime?: False
Is 158456325028528675187087900679 semiprime?: False
Is 158456325028528675187087900680 semiprime?: False
Is 158456325028528675187087900681 semiprime?: False
Is 158456325028528675187087900682 semiprime?: False
Is 158456325028528675187087900683 semiprime?: False
Is 158456325028528675187087900684 semiprime?: False
Is 158456325028528675187087900685 semiprime?: False
Is 158456325028528675187087900686 semiprime?: False
Is 158456325028528675187087900687 semiprime?: False
Is 158456325028528675187087900688 semiprime?: False
Is 158456325028528675187087900689 semiprime?: False
Is 158456325028528675187087900690 semiprime?: False
Is 158456325028528675187087900691 semiprime?: False
Is 158456325028528675187087900692 semiprime?: False
Is 158456325028528675187087900693 semiprime?: False
Is 158456325028528675187087900694 semiprime?: False
Is 158456325028528675187087900695 semiprime?: False
Is 158456325028528675187087900696 semiprime?: False
Is 158456325028528675187087900697 semiprime?: False
Is 158456325028528675187087900698 semiprime?: False
Is 158456325028528675187087900699 semiprime?: False
Is 158456325028528675187087900700 semiprime?: False
Is 158456325028528675187087900701 semiprime?: True
elapsed seconds: 0.0574433
```


[User]
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.

Example: *lager* and *regal*

Task

This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as *lager* and *regal*, should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
(formerly Perl 6)

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

```
my $words = set slurp("unixdict.txt").lines;

my @sems = gather for $words.flat -> $word {
    my $drow = $word.key.flip;
    take $drow if $drow ∈ $words and $drow lt $word;
}

say $_ ~ ' ' ~ $_.flip for @sems.pick(5);

```

Output:

```
abut tuba
avid diva
bard drab
loot tool
part trap
```


[User] Write a program in your language to solve SEND + MORE = MONEY: A Great Puzzle.

[Assistant]
### Idiomatic

```
enum <D E M N O R S Y>;

sub find_solution ( ) {
    for ('0'..'9').combinations(8) -> @c {
        .return with @c.permutations.first: -> @p {
            @p[M] !== 0 and

            @p[  S,E,N,D].join
          + @p[  M,O,R,E].join
         == @p[M,O,N,E,Y].join
        }
    }
}

my @s = find_solution();
say "    {@s[  S,E,N,D].join}";
say " +  {@s[  M,O,R,E].join}";
say "== { @s[M,O,N,E,Y].join}";

```

Output:

```
    9567
 +  1085
== 10652

```

### Fast

Alternately, a version written in 2015 by Carl Mäsak. Not very concise but quite speedy. Applying the observation that M must be 1 and S must be either 8 or 9 gets the runtime under a tenth of a second.

```
my $s = 7;
while ++$s ≤ 9 {
    my $e = -1;
    while ++$e ≤ 9 {
        next if $e == $s;

        my $n = -1;
        while ++$n ≤ 9 {
            next if $n == $s|$e;

            my $d = -1;
            while ++$d ≤ 9 {
                next if $d == $s|$e|$n;

                my $send = $s×10³ + $e×10² + $n×10 + $d;
                my ($m, $o) = 1, -1;
                while ++$o ≤ 9 {
                    next if $o == $s|$e|$n|$d|$m;

                    my $r = -1;
                    while ++$r ≤ 9 {
                        next if $r == $s|$e|$n|$d|$m|$o;

                        my $more = $m×10³ + $o×10² + $r×10 + $e;
                        my $y = -1;
                        while ++$y ≤ 9 {
                            next if $y == $s|$e|$n|$d|$m|$o|$r;

                            my $money = $m×10⁴ + $o×10³ + $n×10² + $e×10 + $y;
                            next unless $send + $more == $money;
                            say 'SEND + MORE == MONEY' ~ "\n$send + $more == $money";
                        }
                    }
                }
            }
        }
    }
}
printf "%.3f elapsed seconds", now - INIT now;

```

Output:

```
SEND + MORE == MONEY
9567 + 1085 == 10652
0.080 elapsed seconds
```


[User]
Task

Invoke an object method where the name of the method to be invoked can be generated at run time.

Related tasks

* Respond to an unknown method call.
* Runtime evaluation

[Assistant]
(formerly Perl 6)
Just for the fun of it, we'll mix in an anonymous role into an integer instead of defining a class.

```
my $object = 42 but role { method add-me($x) { self + $x } }
my $name = 'add-me';
say $object."$name"(5);  # 47

```

The double quotes are required, by the way; without them the variable would be interpreted as a hard ref to a method.


[User]
Task

Write a function to send an email.

The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.

* If appropriate, explain what notifications of problems/success are given.
* Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
* Note how portable the solution given is between operating systems when multi-OS languages are used.

(Remember to obfuscate any sensitive data used in examples)

[Assistant]
(formerly Perl 6)

```
use Email::Simple;

my $to      = 'mail@example.com';
my $from    = 'me@example.com';
my $subject = 'test';
my $body    = 'This is a test.';

my $email = Email::Simple.create(
    :header[['To', $to], ['From', $from], ['Subject', $subject]],
    :body($body)
);

say ~$email;

# Note that the following will fail without an actual smtp server that
# will accept anonymous emails on port 25 (Not very common anymore).
# Most public email servers now require authentication and encryption.

my $smtp-server = 'smtp.example.com';
my $smtp-port   = 25;

await IO::Socket::Async.connect($smtp-server, $smtp-port).then(
    -> $smtp {
        if $smtp.status {
            given $smtp.result {
                react {
                    whenever .Supply() -> $response {
                        if $response ~~ /^220/ {
                            .print( join "\r\n",
                                "EHLO $smtp-server",
                                "MAIL FROM:<{$email.from}>",
                                "RCPT TO:<{$email.to}>",
                                "DATA", $email.body,
                                '.', ''
                            )
                        }
                        elsif $response ~~ /^250/ {
                            .print("QUIT\r\n");
                            done
                        }
                        else {
                           say "Send email failed with: $response";
                           done
                        }
                    }
                    .close
                }
            }
        }
    }
)

```


[User]
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.

In Germany and the Netherlands postal addresses have the form: street name, followed by the house number, in accordance with the national standards DIN 5008 respectively NEN 5825. The problem is that some street names have numbers (e.g. special years) and some house numbers have characters as an extension. It's a real life problem and difficult because in the Netherlands some street names are a tribute to our liberators. The street names have the numbers 40 and 45 indicating the years of war between 1940 and 1945.

Task

Write code that correctly separates the house number from the street name and presents them both.
*No static data must be shown, only processed data.*

The suggested approach is to either use the regular expression in the Scala entry or to devise an equivalent algorithm.

The test-set:

```
Plataanstraat 5
Straat 12
Straat 12 II
Dr. J. Straat   12
Dr. J. Straat 12 a
Dr. J. Straat 12-14
Laan 1940 – 1945 37
Plein 1940 2
1213-laan 11
16 april 1944 Pad 1
1e Kruisweg 36
Laan 1940-’45 66
Laan ’40-’45
Langeloërduinen 3 46
Marienwaerdt 2e Dreef 2
Provincialeweg N205 1
Rivium 2e Straat 59.
Nieuwe gracht 20rd
Nieuwe gracht 20rd 2
Nieuwe gracht 20zw /2
Nieuwe gracht 20zw/3
Nieuwe gracht 20 zw/4
Bahnhofstr. 4
Wertstr. 10
Lindenhof 1
Nordesch 20
Weilstr. 6
Harthauer Weg 2
Mainaustr. 49
August-Horch-Str. 3
Marktplatz 31
Schmidener Weg 3
Karl-Weysser-Str. 6
```

Reference The Netherlands - Addresses

[Assistant]
(formerly Perl 6)
An unquestioning translation of the Scala example's regex to show how we lay out such regexes for readability in Raku, except that we take the liberty of leaving the space out of the house number.
(Hard constants like 1940 and 1945 are a code smell,
and the task should probably not require such constants unless there is a standard to point to that mandates them.)
So expect this solution to change if the task is actually defined reasonably, such as by specifying that four-digit house numbers are excluded in Europe.
(In contrast, four- and five-digit house numbers are not uncommon
in places such as the U.S. where each block gets a hundred house numbers
to play with, and there are cities with hundreds of blocks along a street.)

```
say m[
    ( .*? )

    [
        \s+
        (
        | \d+ [ \- | \/ ] \d+
        | <!before 1940 | 1945> \d+ <[ a..z I . / \x20 ]>* \d*
        )
    ]?

    $
] for lines;

```

Output:

```
｢Plataanstraat 5｣
 0 => ｢Plataanstraat｣
 1 => ｢5｣

｢Straat 12｣
 0 => ｢Straat｣
 1 => ｢12｣

｢Straat 12 II｣
 0 => ｢Straat｣
 1 => ｢12 II｣

｢Dr. J. Straat   12｣
 0 => ｢Dr. J. Straat｣
 1 => ｢12｣

｢Dr. J. Straat 12 a｣
 0 => ｢Dr. J. Straat｣
 1 => ｢12 a｣

｢Dr. J. Straat 12-14｣
 0 => ｢Dr. J. Straat｣
 1 => ｢12-14｣

｢Laan 1940 – 1945 37｣
 0 => ｢Laan 1940 – 1945｣
 1 => ｢37｣

｢Plein 1940 2｣
 0 => ｢Plein 1940｣
 1 => ｢2｣

｢1213-laan 11｣
 0 => ｢1213-laan｣
 1 => ｢11｣

｢16 april 1944 Pad 1｣
 0 => ｢16 april 1944 Pad｣
 1 => ｢1｣

｢1e Kruisweg 36｣
 0 => ｢1e Kruisweg｣
 1 => ｢36｣

｢Laan 1940-’45 66｣
 0 => ｢Laan 1940-’45｣
 1 => ｢66｣

｢Laan ’40-’45｣
 0 => ｢Laan ’40-’45｣

｢Langeloërduinen 3 46｣
 0 => ｢Langeloërduinen｣
 1 => ｢3 46｣

｢Marienwaerdt 2e Dreef 2｣
 0 => ｢Marienwaerdt 2e Dreef｣
 1 => ｢2｣

｢Provincialeweg N205 1｣
 0 => ｢Provincialeweg N205｣
 1 => ｢1｣

｢Rivium 2e Straat 59.｣
 0 => ｢Rivium 2e Straat｣
 1 => ｢59.｣

｢Nieuwe gracht 20rd｣
 0 => ｢Nieuwe gracht｣
 1 => ｢20rd｣

｢Nieuwe gracht 20rd 2｣
 0 => ｢Nieuwe gracht｣
 1 => ｢20rd 2｣

｢Nieuwe gracht 20zw /2｣
 0 => ｢Nieuwe gracht｣
 1 => ｢20zw /2｣

｢Nieuwe gracht 20zw/3｣
 0 => ｢Nieuwe gracht｣
 1 => ｢20zw/3｣

｢Nieuwe gracht 20 zw/4｣
 0 => ｢Nieuwe gracht｣
 1 => ｢20 zw/4｣

｢Bahnhofstr. 4｣
 0 => ｢Bahnhofstr.｣
 1 => ｢4｣

｢Wertstr. 10｣
 0 => ｢Wertstr.｣
 1 => ｢10｣

｢Lindenhof 1｣
 0 => ｢Lindenhof｣
 1 => ｢1｣

｢Nordesch 20｣
 0 => ｢Nordesch｣
 1 => ｢20｣

｢Weilstr. 6｣
 0 => ｢Weilstr.｣
 1 => ｢6｣

｢Harthauer Weg 2｣
 0 => ｢Harthauer Weg｣
 1 => ｢2｣

｢Mainaustr. 49｣
 0 => ｢Mainaustr.｣
 1 => ｢49｣

｢August-Horch-Str. 3｣
 0 => ｢August-Horch-Str.｣
 1 => ｢3｣

｢Marktplatz 31｣
 0 => ｢Marktplatz｣
 1 => ｢31｣

｢Schmidener Weg 3｣
 0 => ｢Schmidener Weg｣
 1 => ｢3｣

｢Karl-Weysser-Str. 6｣
 0 => ｢Karl-Weysser-Str.｣
 1 => ｢6｣

```


[User]
Task

Show that the following remarkable formula gives the sequence of non-square natural numbers:

```
            n + floor(1/2 + sqrt(n))

```

* Print out the values for    n    in the range   **1**   to   **22**
* Show that no squares occur for    n    less than one million

This is sequence   A000037   in the **OEIS** database.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.07

```
sub nth-term (Int $n) { $n + round sqrt $n }

# Print the first 22 values of the sequence
say (nth-term $_ for 1 .. 22);

# Check that the first million values of the sequence are indeed non-square
for 1 .. 1_000_000 -> $i {
    say "Oops, nth-term($i) is square!" if (sqrt nth-term $i) %% 1;
}

```

Output:

```
(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
```


[User]
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.

Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.

Task

Generate and show here the first ten values of the sequence.

Optional extended task

Show the first twenty members of the series.

Notes

* This task asks for the primorial *indices* that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers *will* be needed for intermediate results).
* There is some confusion in the references, but for the purposes of this task the **sequence begins with n = 1**.
* Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.

Related tasks

* Primorial numbers
* Factorial

See also

* Primorial prime Wikipedia.
* Primorial prime from The Prime Glossary.
* Sequence A088411 from The On-Line Encyclopedia of Integer Sequences

[Assistant]
(formerly Perl 6)

```
constant @primes     = |grep *.is-prime, 2..*;
constant @primorials = [\*] 1, @primes;

my @pp_indexes := |@primorials.pairs.map: {
    .key if ( .value + any(1, -1) ).is-prime
};

say ~ @pp_indexes[ 0 ^.. 20 ]; # Skipping bogus first element.

```

Output:

```
1 2 3 4 5 6 11 13 24 66 68 75 167 171 172 287 310 352 384 457
```

### Alternate implementation

merged from another removed draft task.

```
my @primorials = 1, |[\*] (2..*).grep: &is-prime;
sub abr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '..' ~ .substr(*-20) ~ " ({.chars} digits)" }

my $limit;

for ^∞ {
    my \p = @primorials[$_];
    ++$limit and printf "%2d: %5s - 1 = %s\n", $limit, "p$_#", abr p -1 if (p -1).is-prime;
    ++$limit and printf "%2d: %5s + 1 = %s\n", $limit, "p$_#", abr p +1 if (p +1).is-prime;
    exit if $limit >= 30
}

```

Output:

```
 1:   p0# + 1 = 2
 2:   p1# + 1 = 3
 3:   p2# - 1 = 5
 4:   p2# + 1 = 7
 5:   p3# - 1 = 29
 6:   p3# + 1 = 31
 7:   p4# + 1 = 211
 8:   p5# - 1 = 2309
 9:   p5# + 1 = 2311
10:   p6# - 1 = 30029
11:  p11# + 1 = 200560490131
12:  p13# - 1 = 304250263527209
13:  p24# - 1 = 23768741896345550770650537601358309
14:  p66# - 1 = 19361386640700823163..29148240284399976569 (131 digits)
15:  p68# - 1 = 21597045956102547214..98759003964186453789 (136 digits)
16:  p75# + 1 = 17196201054584064334..62756822275663694111 (154 digits)
17: p167# - 1 = 19649288510530675457..35580823050358968029 (413 digits)
18: p171# + 1 = 20404068993016374194..29492908966644747931 (425 digits)
19: p172# + 1 = 20832554441869718052..12260054944287636531 (428 digits)
20: p287# - 1 = 71488723083486699645..63871022000761714929 (790 digits)
21: p310# - 1 = 40476351620665036743..10663664196050230069 (866 digits)
22: p352# - 1 = 13372477493552802137..21698973741675973189 (1007 digits)
23: p384# + 1 = 78244737296323701708..84011652643245393971 (1115 digits)
24: p457# + 1 = 68948124012218025568..25023568563926988371 (1368 digits)
25: p564# - 1 = 12039145942930719470..56788854266062940789 (1750 digits)
26: p590# - 1 = 19983712295113492764..61704122697617268869 (1844 digits)
27: p616# + 1 = 13195724337318102247..85805719764535513291 (1939 digits)
28: p620# - 1 = 57304682725550803084..81581766766846907409 (1953 digits)
29: p643# + 1 = 15034815029008301639..38987057002293989891 (2038 digits)
30: p849# - 1 = 11632076146197231553..78739544174329780009 (2811 digits)
```


[User]
Calculate the sequence where each term **an** is the **nth** that has **n** divisors.

Task

Show here, on this page, at least the first **15** terms of the sequence.

See also

:   * OEIS:A073916

Related tasks

:   * Sequence: smallest number greater than previous term with exactly n divisors
    * Sequence: smallest number with exactly n divisors

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

Try it online!

```
sub div-count (\x) {
    return 2 if x.is-prime;
    +flat (1 .. x.sqrt.floor).map: -> \d {
        unless x % d { my \y = x div d; y == d ?? y !! (y, d) }
    }
}

my $limit = 20;

my @primes = grep { .is-prime }, 1..*;
@primes[$limit]; # prime the array. SCNR

put "First $limit terms of OEIS:A073916";
put (1..$limit).hyper(:2batch).map: -> $n {
    ($n > 4 and $n.is-prime) ??
    exp($n - 1, @primes[$n - 1]) !!
    do {
        my $i = 0;
        my $iterator = $n %% 2 ?? (1..*) !! (1..*).map: *²;
        $iterator.first: {
            next unless $n == .&div-count;
            next unless ++$i == $n;
            $_
        }
    }
};

```

```
First 20 terms of OEIS:A073916
1 3 25 14 14641 44 24137569 70 1089 405 819628286980801 160 22563490300366186081 2752 9801 462 21559177407076402401757871041 1044 740195513856780056217081017732809 1520
```


[User]
Calculate the sequence where each term **an** is the **smallest natural number** greater than the previous term, that has exactly **n** divisors.

Task

Show here, on this page, at least the first **15** terms of the sequence.

See also
:   * OEIS:A069654

Related tasks
:   * Sequence: smallest number with exactly n divisors
    * Sequence: nth number with exactly n divisors

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

```
sub div-count (\x) {
    return 2 if x.is-prime;
    +flat (1 .. x.sqrt.floor).map: -> \d {
        unless x % d { my \y = x div d; y == d ?? y !! (y, d) }
    }
}

my $limit = 15;

my $m = 1;
put "First $limit terms of OEIS:A069654";
put (1..$limit).map: -> $n { my $ = $m = first { $n == .&div-count }, $m..Inf };

```

Output:

```
First 15 terms of OEIS:A069654
1 2 4 6 16 18 64 66 100 112 1024 1035 4096 4288 4624

```


[User]
Calculate the sequence where each term   **an**   is the **smallest natural number** that has exactly   **n**   divisors.

Task

Show here, on this page, at least the first  **15**  terms of the sequence.

Related tasks
:   * Sequence: smallest number greater than previous term with exactly n divisors
    * Sequence: nth number with exactly n divisors

See also
:   * OEIS:A005179

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

```
sub div-count (\x) {
    return 2 if x.is-prime;
    +flat (1 .. x.sqrt.floor).map: -> \d {
        unless x % d { my \y = x div d; y == d ?? y !! (y, d) }
    }
}

my $limit = 15;

put "First $limit terms of OEIS:A005179";
put (1..$limit).map: -> $n { first { $n == .&div-count }, 1..Inf };

```

Output:

```
First 15 terms of OEIS:A005179
1 2 4 6 16 12 64 24 36 48 1024 60 4096 192 144
```


[User]
A   **set**  is a collection of elements, without duplicates and without order.

Task

Show each of these set operations:

* Set creation
* Test m ∈ S -- "m is an element in set S"
* A ∪ B -- *union*; a set of all elements either in set A or in set B.
* A ∩ B -- *intersection*; a set of all elements in *both* set A and set B.
* A ∖ B -- *difference*; a set of all elements in set A, except those in set B.
* A ⊆ B -- *subset*; true if every element in set A is also in set B.
* A = B -- *equality*; true if every element of set A is in set B and vice versa.

As an option, show some other set operations.

(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)

As another option, show how to modify a mutable set.

One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).

One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).

The basic test, m ∈ S, is O(n) with a sequential list of elements, O(*log* n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.

See also

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

[Assistant]
(formerly Perl 6)

```
use Test;

my $a = set <a b c>;
my $b = set <b c d>;
my $c = set <a b c d e>;

ok 'c' ∈ $a, "c is an element in set A";
nok 'd' ∈ $a, "d is not an element in set A";

is-deeply $a ∪ $b, set(<a b c d>), "union; a set of all elements either in set A or in set B";
is-deeply $a ∩ $b, set(<b c>), "intersection; a set of all elements in both set A and set B";
is $a (-) $b, set(<a>), "difference; a set of all elements in set A, except those in set B";

ok $a ⊆ $c, "subset; true if every element in set A is also in set B";
nok $c ⊆ $a, "subset; false if every element in set A is not also in set B";
ok $a ⊂ $c, "strict subset; true if every element in set A is also in set B";
nok $a ⊂ $a, "strict subset; false for equal sets";
ok $a === set(<a b c>), "equality; true if every element of set A is in set B and vice-versa";
nok $a === $b, "equality; false for differing sets";

```

Output:

```
ok 1 - c is an element in set A
ok 2 - d is not an element in set A
ok 3 - union; a set of all elements either in set A or in set B
ok 4 - intersection; a set of all elements in both set A and set B
ok 5 - difference; a set of all elements in set A, except those in set B
ok 6 - subset; true if every element in set A is also in set B
ok 7 - subset; false if every element in set A is not also in set B
ok 8 - strict subset; true if every element in set A is also in set B
ok 9 - strict subset; false for equal sets
ok 10 - equality; true if every element of set A is in set B and vice-versa
ok 11 - equality; false for differing sets
```


[User]
Given two sets of items then if any item is common to any set then the result of applying *consolidation* to those sets is a set of sets whose contents is:

* The two input sets if no common item exists between the two input sets of items.
* The single set that is the union of the two input sets if they share a common item.

Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.

**Example 1:**
:   Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.

**Example 2:**
:   Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).

**Example 3:**
:   Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}

**Example 4:**
:   The consolidation of the five sets:

    :   {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:   Is the two sets:

    :   {A, C, B, D}, and {G, F, I, H, K}

**See also**

* Connected component (graph theory)
* Range consolidation

[Assistant]
(formerly Perl 6)

```
multi consolidate() { () }
multi consolidate(Set \this is copy, *@those) {
    gather {
        for consolidate |@those -> \that {
            if this ∩ that { this = this ∪ that }
            else           { take that }
        }
        take this;
    }
}

enum Elems <A B C D E F G H I J K>;
say $_, "\n    ==> ", consolidate |$_
    for [set(A,B), set(C,D)],
        [set(A,B), set(B,D)],
        [set(A,B), set(C,D), set(D,B)],
        [set(H,I,K), set(A,B), set(C,D), set(D,B), set(F,G,H)];

```

Output:

```
set(A, B) set(C, D)
    ==> set(C, D) set(A, B)
set(A, B) set(B, D)
    ==> set(A, B, D)
set(A, B) set(C, D) set(D, B)
    ==> set(A, B, C, D)
set(H, I, K) set(A, B) set(C, D) set(D, B) set(F, G, H)
    ==> set(A, B, C, D) set(H, I, K, F, G)
```


[User]
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.

There are 81 cards in a deck.
Each card contains a unique variation of the following four features: *color, symbol, number and shading*.

* there are three colors:
      *red, green, purple*

* there are three symbols:
      *oval, squiggle, diamond*

* there is a number of symbols on the card:
      *one, two, three*

* there are three shadings:
      *solid, open, striped*

Three cards form a *set* if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.

There are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.

When creating sets you may use the same card more than once.

Task

Write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.

For instance:

**DEALT 9 CARDS:**

:   green, one, oval, striped

:   green, one, diamond, open

:   green, one, diamond, striped

:   green, one, diamond, solid

:   purple, one, diamond, open

:   purple, two, squiggle, open

:   purple, three, oval, open

:   red, three, oval, open

:   red, three, diamond, solid

**CONTAINING 4 SETS:**

:   green, one, oval, striped

:   purple, two, squiggle, open

:   red, three, diamond, solid

:   green, one, diamond, open

:   green, one, diamond, striped

:   green, one, diamond, solid

:   green, one, diamond, open

:   purple, two, squiggle, open

:   red, three, oval, open

:   purple, one, diamond, open

:   purple, two, squiggle, open

:   purple, three, oval, open

[Assistant]
(formerly Perl 6)

The trick here is to allocate three different bits for each enum, with the result that the cards of a matching set OR together to produce a 4-digit octal number that contains only the digits 1, 2, 4, or 7. This OR is done by funny looking [+|], which is the reduction form of +|, which is the numeric bitwise OR. (Because Raku stole the bare | operator for composing junctions instead.)

```
enum Color (red => 0o1000, green =>  0o2000, purple => 0o4000);
enum Count (one =>  0o100, two =>     0o200, three =>   0o400);
enum Shape (oval =>  0o10, squiggle => 0o20, diamond =>  0o40);
enum Style (solid =>  0o1, open =>      0o2, striped =>   0o4);

my @deck = Color.enums X Count.enums X Shape.enums X Style.enums;

sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) {
    sub show-cards(@c) { { printf "%9s%7s%10s%9s\n", @c[$_;*]».key } for ^@c }

    my @combinations = [^$DRAW].combinations(3);

    my @draw;
    repeat until (my @sets) == $GOAL {
        @draw = @deck.pick($DRAW);
        my @bits = @draw.map: { [+] @^enums».value }
        @sets = gather for @combinations -> @c {
            take @draw[@c].item when /^ <[1247]>+ $/ given ( [+|] @bits[@c] ).base(8);
        }
    }

    say "Drew $DRAW cards:";
    show-cards @draw;
    for @sets.kv -> $i, @cards {
        say "\nSet {$i+1}:";
        show-cards @cards;
    }
}

```

Output:

```
Drew 9 cards:
   purple    two   diamond     open
      red    two  squiggle  striped
   purple  three  squiggle     open
   purple    two  squiggle  striped
      red  three      oval  striped
      red    one   diamond  striped
   purple    two      oval    solid
    green  three   diamond    solid
      red    two  squiggle     open

Set 1:
   purple    two   diamond     open
   purple    two  squiggle  striped
   purple    two      oval    solid

Set 2:
   purple    two   diamond     open
      red    one   diamond  striped
    green  three   diamond    solid

Set 3:
      red    two  squiggle  striped
      red  three      oval  striped
      red    one   diamond  striped

Set 4:
   purple  three  squiggle     open
      red  three      oval  striped
    green  three   diamond    solid
```


[User]
Given a left-to-right ordered collection of `e` bits, `b`, where `1 <= e <= 10000`,
and a zero or more integer `n` :

* Output the result of setting the `n` bits to the right of any set bit in `b`

(if those bits are present in b and therefore also preserving the width, `e`).

**Some examples:**

```
   Set of examples showing how one bit in a nibble gets changed:

       n = 2; Width e = 4:

            Input b: 1000
             Result: 1110

            Input b: 0100
             Result: 0111

            Input b: 0010
             Result: 0011

            Input b: 0000
             Result: 0000

   Set of examples with the same input with set bits of varying distance apart:

       n = 0; Width e = 66:

            Input b: 010000000000100000000010000000010000000100000010000010000100010010
             Result: 010000000000100000000010000000010000000100000010000010000100010010

       n = 1; Width e = 66:

            Input b: 010000000000100000000010000000010000000100000010000010000100010010
             Result: 011000000000110000000011000000011000000110000011000011000110011011

       n = 2; Width e = 66:

            Input b: 010000000000100000000010000000010000000100000010000010000100010010
             Result: 011100000000111000000011100000011100000111000011100011100111011111

       n = 3; Width e = 66:

            Input b: 010000000000100000000010000000010000000100000010000010000100010010
             Result: 011110000000111100000011110000011110000111100011110011110111111111

```

**Task:**

* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width `e`.
* Use it to show, here, the results for the input examples above.
* Print the output aligned in a way that allows easy checking by eye of the binary input vs output.

[Assistant]
A left-to-right ordered collection of bits is more commonly referred to as an Integer in Raku.

```
sub rab (Int $n, Int $b = 1) {
    my $m = $n;
    $m +|= ($n +> $_) for ^ $b+1;
    $m
}

sub lab (Int $n, Int $b = 1) {
    my $m = $n;
    $m +|= ($n +< $_) for ^ $b+1;
    $m
}

say "Powers of 2 ≤ 8, 0 - Right-adjacent-bits: 2";
.&rab(2).base(2).fmt('%04s').say for <8 4 2 1 0>;

# Test with a few integers.
for 8,4, 18455760086304825618,5, 5444684034376312377319904082902529876242,15 -> $integer, $bits {

    say "\nInteger: $integer - Right-adjacent-bits: up to $bits";

    .say for ^$bits .map: -> $b { $integer.&rab($b).base: 2 };

    say "\nInteger: $integer - Left-adjacent-bits: up to $bits";

    .say for ^$bits .map: -> $b { $integer.&lab($b).fmt("%{0~$bits+$integer.msb}b") };

}

```

Output:

```
Powers of 2 ≤ 8, 0 - Right-adjacent-bits: 2
1110
0111
0011
0001
0000

Integer: 8 - Right-adjacent-bits: up to 4
1000
1100
1110
1111

Integer: 8 - Left-adjacent-bits: up to 4
0001000
0011000
0111000
1111000

Integer: 18455760086304825618 - Right-adjacent-bits: up to 5
10000000000100000000010000000010000000100000010000010000100010010
11000000000110000000011000000011000000110000011000011000110011011
11100000000111000000011100000011100000111000011100011100111011111
11110000000111100000011110000011110000111100011110011110111111111
11111000000111110000011111000011111000111110011111011111111111111

Integer: 18455760086304825618 - Left-adjacent-bits: up to 5
000010000000000100000000010000000010000000100000010000010000100010010
000110000000001100000000110000000110000001100000110000110001100110110
001110000000011100000001110000001110000011100001110001110011101111110
011110000000111100000011110000011110000111100011110011110111111111110
111110000001111100000111110000111110001111100111110111111111111111110

Integer: 5444684034376312377319904082902529876242 - Right-adjacent-bits: up to 15
1000000000000001000000000000010000000000000100000000000010000000000010000000000100000000010000000010000000100000010000010000100010010
1100000000000001100000000000011000000000000110000000000011000000000011000000000110000000011000000011000000110000011000011000110011011
1110000000000001110000000000011100000000000111000000000011100000000011100000000111000000011100000011100000111000011100011100111011111
1111000000000001111000000000011110000000000111100000000011110000000011110000000111100000011110000011110000111100011110011110111111111
1111100000000001111100000000011111000000000111110000000011111000000011111000000111110000011111000011111000111110011111011111111111111
1111110000000001111110000000011111100000000111111000000011111100000011111100000111111000011111100011111100111111011111111111111111111
1111111000000001111111000000011111110000000111111100000011111110000011111110000111111100011111110011111110111111111111111111111111111
1111111100000001111111100000011111111000000111111110000011111111000011111111000111111110011111111011111111111111111111111111111111111
1111111110000001111111110000011111111100000111111111000011111111100011111111100111111111011111111111111111111111111111111111111111111
1111111111000001111111111000011111111110000111111111100011111111110011111111110111111111111111111111111111111111111111111111111111111
1111111111100001111111111100011111111111000111111111110011111111111011111111111111111111111111111111111111111111111111111111111111111
1111111111110001111111111110011111111111100111111111111011111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111001111111111111011111111111110111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111

Integer: 5444684034376312377319904082902529876242 - Left-adjacent-bits: up to 15
000000000000001000000000000001000000000000010000000000000100000000000010000000000010000000000100000000010000000010000000100000010000010000100010010
000000000000011000000000000011000000000000110000000000001100000000000110000000000110000000001100000000110000000110000001100000110000110001100110110
000000000000111000000000000111000000000001110000000000011100000000001110000000001110000000011100000001110000001110000011100001110001110011101111110
000000000001111000000000001111000000000011110000000000111100000000011110000000011110000000111100000011110000011110000111100011110011110111111111110
000000000011111000000000011111000000000111110000000001111100000000111110000000111110000001111100000111110000111110001111100111110111111111111111110
000000000111111000000000111111000000001111110000000011111100000001111110000001111110000011111100001111110001111110011111101111111111111111111111110
000000001111111000000001111111000000011111110000000111111100000011111110000011111110000111111100011111110011111110111111111111111111111111111111110
000000011111111000000011111111000000111111110000001111111100000111111110000111111110001111111100111111110111111111111111111111111111111111111111110
000000111111111000000111111111000001111111110000011111111100001111111110001111111110011111111101111111111111111111111111111111111111111111111111110
000001111111111000001111111111000011111111110000111111111100011111111110011111111110111111111111111111111111111111111111111111111111111111111111110
000011111111111000011111111111000111111111110001111111111100111111111110111111111111111111111111111111111111111111111111111111111111111111111111110
000111111111111000111111111111001111111111110011111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111110
001111111111111001111111111111011111111111110111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110
011111111111111011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110
```


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

In mathematics, **sexy primes** are prime numbers that differ from each other by six.

For example, the numbers **5** and **11** are both sexy primes, because **11** minus **6** is **5**.

The term "sexy prime" is a pun stemming from the Latin word for six: *sex*.

**Sexy prime pairs:** Sexy prime pairs are groups of two primes that differ by **6**. e.g. **(5 11), (7 13), (11 17)**
See sequences: OEIS:A023201 and OEIS:A046117

**Sexy prime triplets:** Sexy prime triplets are groups of three primes where each differs from the next by **6**. e.g. **(5 11 17), (7 13 19), (17 23 29)**
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120

**Sexy prime quadruplets:** Sexy prime quadruplets are groups of four primes where each differs from the next by **6**. e.g. **(5 11 17 23), (11 17 23 29)**
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124

**Sexy prime quintuplets:** Sexy prime quintuplets are groups of five primes with a common difference of **6**. One of the terms must be divisible by **5**, because **5** and **6** are relatively prime. Thus, the only possible sexy prime quintuplet is **(5 11 17 23 29)**

Task

:   :   * For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (**1,000,035**).
        * Display at most the **last** **5**, less than one million thirty-five, of each sexy prime group type.
        * Find and display the count of the unsexy primes less than one million thirty-five.
        * Find and display the **last 10** unsexy primes less than one million thirty-five.
        * Note that 1000033 **SHOULD NOT** be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also **SHOULD NOT** be listed in the unsexy primes since it is sexy.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.08

```
use Math::Primesieve;
my $sieve = Math::Primesieve.new;

my $max = 1_000_035;
my @primes = $sieve.primes($max);

my $filter = @primes.Set;
my $primes = @primes.categorize: &sexy;

say "Total primes less than {comma $max}: ", comma +@primes;

for <pair 2 triplet 3 quadruplet 4 quintuplet 5> -> $sexy, $cnt {
    say "Number of sexy prime {$sexy}s less than {comma $max}: ", comma +$primes{$sexy};
    say "   Last 5 sexy prime {$sexy}s less than {comma $max}: ",
      join ' ', $primes{$sexy}.tail(5).grep(*.defined).map:
      { "({ $_ «+« (0,6 … 24)[^$cnt] })" }
    say '';
}

say "Number of unsexy primes less than {comma $max}: ", comma +$primes<unsexy>;
say "  Last 10 unsexy primes less than {comma $max}: ", $primes<unsexy>.tail(10);

sub sexy ($i) {
    gather {
        take 'quintuplet' if all($filter{$i «+« (6,12,18,24)});
        take 'quadruplet' if all($filter{$i «+« (6,12,18)});
        take 'triplet'    if all($filter{$i «+« (6,12)});
        take 'pair'       if $filter{$i + 6};
        take (($i >= $max - 6) && ($i + 6).is-prime) ||
          (so any($filter{$i «+« (6, -6)})) ?? 'sexy' !! 'unsexy';
    }
}

sub comma { $^i.flip.comb(3).join(',').flip }

```

Output:

```
Total primes less than 1,000,035: 78,500
Number of sexy prime pairs less than 1,000,035: 16,386
   Last 5 sexy prime pairs less than 1,000,035: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)

Number of sexy prime triplets less than 1,000,035: 2,900
   Last 5 sexy prime triplets less than 1,000,035: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)

Number of sexy prime quadruplets less than 1,000,035: 325
   Last 5 sexy prime quadruplets less than 1,000,035: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)

Number of sexy prime quintuplets less than 1,000,035: 1
   Last 5 sexy prime quintuplets less than 1,000,035: (5 11 17 23 29)

Number of unsexy primes less than 1,000,035: 48,627
  Last 10 unsexy primes less than 1,000,035: (999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003)
```


[User]
**SHA-1** or **SHA1** is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.

A US government standard, FIPS 180-1, defines SHA-1.

Find the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.

|  |
| --- |
| **Warning:** SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3. |

[Assistant]
(formerly Perl 6)

### Pure Raku

A pure Raku implementation that closely follows the description of SHA-1 in FIPS 180-1. Slow.

```
sub postfix:<mod2³²> { $^x % 2**32 }
sub infix:<⊕>        { ($^x + $^y)mod2³² }
sub S                { ($^x +< $^n)mod2³² +| ($x +> (32-$n)) }

my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D)   },
        -> \B,\C,\D { B +^ C +^ D                      },
        -> \B,\C,\D { (B +& C) +| (B +& D) +| (C +& D) },
        -> \B,\C,\D { B +^ C +^ D                      };

my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6;

sub sha1-pad(Blob $msg)
{
    my \bits = 8 * $msg.elems;
    my @padded = flat $msg.list, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64);
    flat @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²;
}

sub sha1-block(@H, @M is copy)
{
    @M.push: S(1, [+^] @M[$_ «-« <3 8 14 16>] ) for 16 .. 79;

    my ($A,$B,$C,$D,$E) = @H;
    for 0..79 -> \t {
        ($A, $B, $C, $D, $E) =
        S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @M[t] ⊕ K[t div 20],
        $A, S(30,$B), $C, $D;
    }
    @H »⊕=« ($A,$B,$C,$D,$E);
}

sub sha1(Blob $msg) returns Blob
{
    my @M = sha1-pad($msg);
    my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0;
    sha1-block(@H,@M[$_..$_+15]) for 0, 16...^ +@M;
    Blob.new: flat map { reverse .polymod(256 xx 3) }, @H;
}

say sha1(.encode('ascii')), "  $_"
   for 'abc',
       'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
       'Rosetta Code',
       'Ars longa, vita brevis';

```

Output:

```
Buf:0x<a9 99 3e 36 47 06 81 6a ba 3e 25 71 78 50 c2 6c 9c d0 d8 9d>  abc
Buf:0x<84 98 3e 44 1c 3b d2 6e ba ae 4a a1 f9 51 29 e5 e5 46 70 f1>  abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq
Buf:0x<48 c9 8f 7e 5a 6e 73 6d 79 0a b7 40 df c3 f5 1a 61 ab e2 b5>  Rosetta Code
Buf:0x<e6 40 d2 85 24 28 86 eb 96 ab 80 cb f8 58 38 9b 3d f5 2f 43>  Ars longa, vita brevis
```

### Library based implementation

Quite speedy.

```
use Digest::SHA1::Native;

# use sha1-hex() if you want a hex string

say sha1($_), "  $_" for
  'abc',
  'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
  'Rosetta Code',
  'Ars longa, vita brevis'
;

```

Output:

```
Blob:0x<A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D>  abc
Blob:0x<84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1>  abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq
Blob:0x<48 C9 8F 7E 5A 6E 73 6D 79 0A B7 40 DF C3 F5 1A 61 AB E2 B5>  Rosetta Code
Blob:0x<E6 40 D2 85 24 28 86 EB 96 AB 80 CB F8 58 38 9B 3D F5 2F 43>  Ars longa, vita brevis
```


[User]
**SHA-256** is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.

Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

[Assistant]
(formerly Perl 6)

### Pure Raku

The following implementation takes all data as input. Ideally, input should be given lazily or something.

```
say sha256 "Rosetta code";

our proto sha256($) returns blob8 {*}

multi sha256(Str $str) { samewith $str.encode }
multi sha256(blob8 $data) {
  sub rotr { $^a +> $^b +| $a +< (32 - $b) }
  sub init { ^Inf .grep(&is-prime).map: { (($_ - .Int)*2**32).Int } o &^f }
  sub   Ch { $^x +& $^y +^ +^$x +& $^z }
  sub  Maj { $^x +& $^y +^ $x +& $^z +^ $y +& $z }
  sub   Σ0 { rotr($^x,  2) +^ rotr($x, 13) +^ rotr($x, 22) }
  sub   Σ1 { rotr($^x,  6) +^ rotr($x, 11) +^ rotr($x, 25) }
  sub   σ0 { rotr($^x,  7) +^ rotr($x, 18) +^ $x +>  3 }
  sub   σ1 { rotr($^x, 17) +^ rotr($x, 19) +^ $x +> 10 }

  return blob8.new:
    map |*.polymod(256 xx 3).reverse,
	|reduce -> $H, $block {
	  blob32.new: $H[] Z+
	    reduce -> $h, $j {
	      my uint32 ($T1, $T2) =
		$h[7] + Σ1($h[4]) + Ch(|$h[4..6])
		+ (BEGIN init(* **(1/3))[^64])[$j] +
		(
		 (state buf32 $w .= new)[$j] = $j < 16 ?? $block[$j] !!
		 σ0($w[$j-15]) + $w[$j-7] + σ1($w[$j-2]) + $w[$j-16]
		),
	      Σ0($h[0]) + Maj(|$h[0..2]);
	      blob32.new: $T1 + $T2, |$h[0..2], $h[3] + $T1, |$h[4..6];
	    }, $H, |^64;
	},
	(BEGIN init(&sqrt)[^8]),
	|blob32.new(
	    blob8.new(
	      @$data,
	      0x80,
	      0 xx (-($data + 1 + 8) mod 64),
	      (8*$data).polymod(256 xx 7).reverse
	      ).rotor(4)
	    .map: { :256[@$_] }
	  ).rotor(16)
}

```

Output:

```
Blob[uint8]:0x<76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF>
```

### Native implementation

```
use Digest::SHA256::Native;

# If you want a string
say sha256-hex 'Rosetta code';

# If you want a binary Blob
say sha256 'Rosetta code';

```

Output:

```
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Blob:0x<76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF>
```


[User]
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.

Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).

Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.

[Assistant]
```
use Digest::SHA256::Native;

unit sub MAIN(Int :b(:$block-size) = 1024 × 1024, *@args);

my $in = @args ?? IO::CatHandle.new(@args) !! $*IN;

my @blocks = do while my $block = $in.read: $block-size { sha256 $block };

while @blocks > 1 {
  @blocks = @blocks.batch(2).map: { $_ > 1 ?? sha256([~] $_) !! .[0] }
}

say @blocks[0]».fmt('%02x').join;

```

Output:

```
$ sha256tree --block-size=1024 title.png
a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c
```


[User]
**Task**:

Get user input (or store the number somewhere if the programing langauge doesn't support input) and then add 3, multiply that 0.86 and repeat that over and over again.

Optionally, halt the loop when quiescence has been achieved, i.e. when the value does not change, and report that value and the corresponding number of iterations.

## See Also

* Esolangs.org page

[Assistant]
```
my $input = (+prompt()).FatRat;
my $previous = 0.FatRat;
my $count;
my $places = 36;
loop {
    $input += 3;
    $input ×= .86;
    last if $previous.substr(0,$places) eq $input.substr(0,$places);
    ++$count;
    say ($previous = $input).substr(0,$places);
}
say "$count repetitions";

```

Output with a 4 fed in at the prompt:

```
4
6.02
7.7572
9.251192
10.53602512
11.6409816032
12.591244178752
13.40846999372672
14.1112841946049792
14.715704407360282112
15.23550579032984261632
15.6825349796836646500352
16.066980082527951599030272

...
many, many lines omitted
...

18.428571428571428571428571428571416
18.428571428571428571428571428571418
18.428571428571428571428571428571419
18.428571428571428571428571428571420
18.428571428571428571428571428571421
18.428571428571428571428571428571422
18.428571428571428571428571428571423
18.428571428571428571428571428571424
512 repetitions

```

In the latest iteration of the task instructions, we are to optionally "halt the loop when quiescence has been achieved, i.e. when the value does not change". Unless a precision is specified, "quiescence" will never be achieved. This operation adds more places of precision with every iteration, and will never "quiesce". (Unless run on a processor or with a language that is unable to handle high precision.)

For instance, the 1000th iteration, starting with 4 is exactly equal to:

```
say (4.FatRat, (* + 3) × .86 … *)[999]

```

Output:

```
18.428571428571428571428571428571428571428571428571428571428571428518562611055257476711345657046077536086307719590805662205008932637290716748623508143778473712167435511145273975385354947408188479662139937380449451942842937179508680530588633892945763008511616379084707917069957275072200539351914273993965066030011194811876547904839025263224744832595386782011862097471389181893672211696726485532183264057134602403929706908123592993235863786859888156665186026179826816128847575831458378844885123366878611593252686593421606487555134444315938261367778063531536534964127098858136548553001526656285822374662510184388742700972850063038414950295895060044238800011827580857336812976758443609296077801146559738910594736606435132635929690920618270821813108173656217015589361779205162675360527035288967300528197729261443766412283716792164777168702168039406788952779919915570541752416260293860518467707548712088056167502132216420672641269104901942501949966581723902330182247134406759443834453985391637796764689461663270662662993088449741102622767088092813554110022083926515230853581817905105492221230813528825959115645642043759816744064849863722778041272156387348996418369338438534662612609987037043047038131221189442288876209762806085696386445408093086328602555139121446610496274119187899056474561873403444794760343168250250584159942711177776533259811971409762989699214055857046134462937025863660124732727323402691866232023863821613479844954718192492032583994808226027774091320595373377362720291094591511865887665392365641680216202349251077081257991823441611723818589067580880018475492672710607080810164651535155593521646027992098574736200877274039486002214250862949227962977243520217727369412523884625435318388719886
```

(Notice that that, while very **precise**, is only **accurate** to 64 decimal places.)


[User]
Task

Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.

Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version #22 "Thousand Oaks"

```
$ raku -e 'say "Hello, world!"'
Hello, world!

```


[User]
Task

Shift list elements to left by   **3**.

```
      shift  = [1,2,3,4,5,6,7,8,9]
      result = [4, 5, 6, 7, 8, 9, 1, 2, 3]

```

[Assistant]
```
# 20210315 Raku programming solution

say [1..9].rotate(3)

```

Output:

```
(4 5 6 7 8 9 1 2 3)

```


[User]
Given the `n + 1` vertices `x[0], y[0] .. x[N], y[N]` of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:

```
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
     (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
   ) / 2
```

(Where `abs` returns the absolute value)

Task

Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:

```
     (3,4), (5,11), (12,8), (9,5), and (5,6)

```

Show the answer here, on this page.

[Assistant]
(formerly Perl 6)

### Index and mod offset

**Works with**: Rakudo version 2017.07

```
sub area-by-shoelace(@p) {
    (^@p).map({@p[$_;0] * @p[($_+1)%@p;1] - @p[$_;1] * @p[($_+1)%@p;0]}).sum.abs / 2
}

say area-by-shoelace( [ (3,4), (5,11), (12,8), (9,5), (5,6) ] );

```

Output:

```
30
```

### Slice and rotation

**Works with**: Rakudo version 2017.07

```
sub area-by-shoelace ( @p ) {
    my @x := @p».[0];
    my @y := @p».[1];

    my $s := ( @x Z* @y.rotate( 1) ).sum
           - ( @x Z* @y.rotate(-1) ).sum;

    return $s.abs / 2;
}

say area-by-shoelace( [ (3,4), (5,11), (12,8), (9,5), (5,6) ] );

```

Output:

```
30
```


[User]
Assume functions   `a`   and   `b`   return boolean values,   and further, the execution of function   `b`   takes considerable resources without side effects, and is to be minimized.

If we needed to compute the conjunction   (`and`):

:   :   :   :   `x = a() and b()`

Then it would be best to not compute the value of   `b()`   if the value of   `a()`   is computed as   `false`,   as the value of   `x`   can then only ever be    `false`.

Similarly, if we needed to compute the disjunction (`or`):

:   :   :   :   `y = a() or b()`

Then it would be best to not compute the value of   `b()`   if the value of   `a()`   is computed as   `true`,   as the value of   `y`   can then only ever be   `true`.

Some languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions

Task

Create two functions named   `a`   and   `b`,   that take and return the same boolean value.

The functions should also print their name whenever they are called.

Calculate and assign the values of the following equations to a variable in such a way that function   `b`   is only called when necessary:

:   :   :   :   `x = a(i) and b(j)`
            :   `y = a(i) or b(j)`

If the language does not have short-circuit evaluation, this might be achieved with nested     **if**     statements.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
use MONKEY-SEE-NO-EVAL;

sub a ($p) { print 'a'; $p }
sub b ($p) { print 'b'; $p }

for 1, 0 X 1, 0 -> ($p, $q) {
    for '&&', '||' -> $op {
        my $s = "a($p) $op b($q)";
        print "$s: ";
        EVAL $s;
        print "\n";
    }
}

```

Output:

```
a(1) && b(1): ab
a(1) || b(1): a
a(1) && b(0): ab
a(1) || b(0): a
a(0) && b(1): a
a(0) || b(1): ab
a(0) && b(0): a
a(0) || b(0): ab
```


[User]
The   **shortest common supersequence**   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task.

Task

Given two strings

u
{\displaystyle {\displaystyle u}}
 and

v
{\displaystyle {\displaystyle v}}
, find the shortest possible sequence

s
{\displaystyle {\displaystyle s}}
, which is the shortest common super-sequence of

u
{\displaystyle {\displaystyle u}}
 and

v
{\displaystyle {\displaystyle v}}
 where both

u
{\displaystyle {\displaystyle u}}
 and

v
{\displaystyle {\displaystyle v}}
 are a subsequence of

s
{\displaystyle {\displaystyle s}}
. Defined as such,

s
{\displaystyle {\displaystyle s}}
 is not necessarily unique.

Demonstrate this by printing

s
{\displaystyle {\displaystyle s}}
 where

u
=
{\displaystyle {\displaystyle u=}}
“abcbdab” and

v
=
{\displaystyle {\displaystyle v=}}
“bdcaba”.

Also see

* Wikipedia: shortest common supersequence

[Assistant]
(formerly Perl 6)

Using 'lcs' routine from Longest common subsequence task

```
sub lcs(Str $xstr, Str $ystr) { # longest common subsequence
    return "" unless $xstr && $ystr;
    my ($x, $xs, $y, $ys) = $xstr.substr(0, 1), $xstr.substr(1), $ystr.substr(0, 1), $ystr.substr(1);
    return $x eq $y
        ?? $x ~ lcs($xs, $ys)
        !! max(:by{ $^a.chars }, lcs($xstr, $ys), lcs($xs, $ystr) );
}

sub scs ($u, $v) { # shortest common supersequence
    my @lcs = (lcs $u, $v).comb;
    my $pat = '(.*)' ~ join('(.*)',@lcs) ~ '(.*)';
    my $regex = "rx/$pat/".EVAL;
    my @u = ($u ~~ $regex).list;
    my @v = ($v ~~ $regex).list;
    my $scs = shift(@u) ~ shift(@v);
    $scs ~= $_ ~ shift(@u) ~ shift(@v) for @lcs;
    return $scs;
}

my $u = 'abcbdab';
my $v = 'bdcaba';
printf "Strings: %s %s\n", $u, $v;
printf "Longest common subsequence:   %s\n", lcs $u, $v;
printf "Shortest common supersquence: %s\n", scs $u, $v;

```

Output:

```
Strings: abcbdab bdcaba
Longest common subsequence:   bcba
Shortest common supersquence: abdcabdab
```