1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
#+title: Challenge 160
#+date: 2022-04-12
#+html_link_up: ../
#+export_file_name: index
#+options: toc:nil
#+setupfile: ~/.emacs.d/org-templates/level-2.org
* 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.
#+begin_src
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.
#+end_src
** 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.
#+begin_src raku
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;
#+end_src
* 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.
#+begin_quote
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].
#+end_quote
#+begin_src
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
#+end_src
** 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.
#+begin_src raku
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;
#+end_src
|