# PERL WEEKLY CHALLENGE – 040

This is my tenth week participating into the weekly challenge.

## Easy Challenge

### Show multiple arrays content

Show multiple arrays content

You are given two or more arrays. Write a script to display values of each list at a given index.

For example:
Array 1: [ I L O V E Y O U ]
Array 2: [ 2 4 0 3 2 0 1 9 ]
Array 3: [ ! ? £ \$ % ^ & * ]

In perl5, I solved this by first calculating the size of the largest array and looping through each element with a for loop. Then using the map function to display the elements of each array.

In Raku, I pretty much did the same thing.

#### Perl 5 solution

``````#!/usr/bin/perl
# Test: ./ch1.pl
use strict;
use warnings;
use feature qw /say/;

my \$arrays = [
[ qw (I L O V E Y O U) ],
[ qw (2 4 0 3 2 0 1 9) ],
[ qw (! ? £ \$ % ^ & *) ],
];

# Sizes of the array
my @sizes =
sort { \$b <=> \$a }
map { scalar(@\$_) } @\$arrays;

# Loop through each array
for my \$i (0 .. \$sizes - 1) {
say join ' ',
map { \$_->[\$i] // ' ' }
@\$arrays;
}``````

Output

``````I 2 !
L 4 ?
O 0 £
V 3 \$
E 2 %
Y 0 ^
O 1 &
U 9 *``````

#### Raku solution

``````# Test: perl6 ch1.p6
use v6.d;

sub MAIN() {
my @arrays = (
<I L O V E Y O U>,
<2 4 0 3 2 0 1 9>,
<! ? £ \$ % ^ & *>,
);

my \$max = @arrays.sort({\$^b.elems <=> \$^a.elems})
.first
.elems;

for (0 .. \$max - 1) ->\$i {
say @arrays.map({\$_[\$i] // ' '})
.join(" ");
}
}
``````

Output

``````I 2 !
L 4 ?
O 0 £
V 3 \$
E 2 %
Y 0 ^
O 1 &
U 9 *``````

## Hard Challenge

Sort SubList
You are given a list of numbers and set of indices belong to the list. Write a script to sort the values belongs to the indices.

For example,
List: [ 10, 4, 1, 8, 12, 3 ]
Indices: 0,2,5
We would sort the values at indices 0, 2 and 5 i.e. 10, 1 and 3.

Final List would look like below:
List: [ 1, 4, 3, 8, 12, 10 ]

In perl 5, I used an array slice to generate a sublist, then I sorted the sublist and overrode the values in the correct position of the original list.

In Raku, I pretty much did the same thing.

#### Perl 5 solution

``````#!/usr/bin/perl
# test: ./ch2.pl
use strict;
use warnings;
use feature qw /say/;

my @list = (10, 4, 1, 8, 12, 3);
my @indices = (0, 2, 5);

# Create a sublist
my @sublist =
sort {\$a <=> \$b} @list[@indices];

# Override the original array
my \$i = 0;
for my \$index (@indices) {
\$list[\$index] = \$sublist[\$i++];
}

say join ',', @list;``````

Output
1,4,3,8,12,10

#### Raku solution

``````# Test: perl6 ./ch2.p6
use v6.d;

sub MAIN () {
my @list = (10, 4, 1, 8, 12, 3);
my @indices = (0, 2, 5);

my @sublist = @list[@indices].sort;

# Override the original array
my \$i = 0;
for (@indices) -> \$index {
@list[\$index] = @sublist[\$i++];
}

say @list;
}
``````

Output
[1 4 3 8 12 10]