UP / HOME

Challenge 160

Task 1 - Four Is Magic

You are given a positive number, $n < 10.

Write a script to generate english text sequence starting with the English cardinal representation of the given number, the word ‘is’ and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue until you reach four.

Input: $n = 5
Output: Five is four, four is magic.

Input: $n = 7
Output: Seven is five, five is four, four is magic.

Input: $n = 6
Output: Six is three, three is five, five is four, four is magic.

Raku

Take a positive number, less than 10 as input from MAIN. Then we define an array that holds the string representation of integers. The multi sub four-is-magic is called on the input. It runs recursively until 4 is called.

.tc is called on the result to make the first character uppercase.

unit sub MAIN(
    UInt $n where * < 10, #= positive number, less than 10
);

my @num-to-str = <zero one two three four five six seven eight nine>;

multi sub four-is-magic(4 --> Str) {
    return "four is magic.";
}

multi sub four-is-magic(Int $n where * < 10 --> Str) {
    my $n-str = @num-to-str[$n];
    return "$n-str is { @num-to-str[$n-str.chars] }, " ~ four-is-magic($n-str.chars);
}

put four-is-magic($n).tc;

Task 2 - Equilibrium Index

You are give an array of integers, @n.

Write a script to find out the Equilibrium Index of the given array, if found.

For an array A consisting n elements, index i is an equilibrium index if the sum of elements of subarray A[0…i-1] is equal to the sum of elements of subarray A[i+1…n-1].

Input: @n = (1, 3, 5, 7, 9)
Output: 3

Input: @n = (1, 2, 3, 4, 5)
Output: -1 as no Equilibrium Index found.

Input: @n = (2, 4, 2)
Output: 1

Raku

Takes an array of integers as input. Then it loops over the array by index and does as the problem states, takes sum of all elements before the index and compares it with the sum of all elements after the index, if they're equal it prints the index and exits. If there is no Equilibrium Index then it prints -1.

unit sub MAIN(
    *@n, #= array of integers
);

for 0 .. @n.end -> $i {
    if @n[0 .. $i - 1].sum == @n[$i + 1 .. *].sum {
        put $i;
        exit;
    }
}
put -1;

Andinus / 2022-04-12 / Modified: 2022-10-04 Tue 21:37 Emacs 27.2 (Org mode 9.4.4)