Perl weekly challenge 205

Third Highest

Task

You are given an array of integers.

Write a script to find out the Third Highest if found otherwise return the maximum.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env raku

use v6.d;

sub third-highest(Int @list where @list.elems > 1 --> Int) {
    my Int @sorted = @list.unique.sort;
    @sorted.elems  3 ?? @sorted[* - 3] !! @sorted[* - 1];
}

#| Run test cases
multi sub MAIN('test') {
    use Test;
    plan 3;

    is third-highest(Array[Int].new([5, 3, 4])), 3, 'works for (5, 3, 4)';
    is third-highest(Array[Int].new([5, 6])), 6, 'works for (5, 6)';
    is third-highest(Array[Int].new([5, 4, 4, 3])), 3, 'works for (5, 4, 4, 3)';
}

#| Take user provided list like 1 2 2 3
multi sub MAIN(*@elements where @elements.elems  1 && all(@elements) ~~ /^<[+-]>?<[0..9]>+$/) {
    my Int @int_elements = @elements;
    say third-highest(@int_elements);
}

#| Run test cases if no argument is supplied
multi sub MAIN() {
    MAIN('test');
}

Discussion

The task does not state that the list consists of unique numbers, so it makes sense to create a list of unique elements before sorting:

6
    my Int @sorted = @list.unique.sort;

After sorting we need to check the number of elements in the list. This is done using the ternary operator:

7
    @sorted.elems  3 ?? @sorted[* - 3] !! @sorted[* - 1];

The rest of the script uses Raku’s special handling of the MAIN subroutine. Supplying no arguments or test runs the examples from the challenge website The third multi sub MAIN accepts an arbitrary number of integers which the user can supply on the command line.

Maximum XOR

Task

You are given an array of integers.

Write a script to find the highest value obtained by XORing any two distinct members of the array.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env raku

use v6.d;

sub maximum-xor(Int @list where @list.elems > 1 --> Int) {
    my Int @unique-list = @list.unique;
    my @pairs = map({ $_[0] +^ $_[1] }, @unique-list.combinations(2));
    return max(@pairs);
}

#| Run test cases
multi sub MAIN('test') {
    use Test;
    plan 3;

    is maximum-xor(Array[Int].new([1 , 2, 3, 4, 5, 6, 7])), 7, 'works for (1, 2, 3, 4, 5, 6, 7)';
    is maximum-xor(Array[Int].new([2 , 4, 1, 3])), 7, 'works for (2, 4, 1, 3)';
    is maximum-xor(Array[Int].new([10 , 5, 7, 12, 8])), 15, 'works for (10, 5, 7, 12, 8)';
}

#| Take user provided list like 1 2 2 3
multi sub MAIN(*@elements where @elements.elems  1 && all(@elements) ~~ /^<[+-]>?<[0..9]>+$/) {
    my Int @int_elements = @elements;
    say maximum-xor(@int_elements);
}
Related
Raku · Perl