DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 160

Challenge, My solutions

Two straight forward tasks, so lets get stuck into it.

TASK #1 › Four Is Magic

Task

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.

Solutions

So both Python and Perl have modules that can convert integers to numbers in English (and other languages), but since we are only dealing with 10 numbers (zero to nine), I just hard code the strings.

I have a loop where I calculate l being the length of the word representing the number n, and add the phrase word[n] is word[l] to the phrases list (array in Perl), and then set n to the value l. The loop exits when n == 4.

Then it's a matter of capitalizing the first letter, and adding the final phrase and printing the string.

Examples

$ ./ch-1.py 5
Five is four, four is magic.

$ ./ch-1.py 7
Seven is five, five is four, four is magic.

$ ./ch-1.py 6
Six is three, three is five, five is four, four is magic.
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Equilibrium Index

Task

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].

Solution

As we don't know the order of the string, I just brute force the solution (if one exists). Starting at 1 (the 2nd element) and ending at n-1 (the second last element), I see if the sum of digits to the left is equal to the sum of digits to the right. If it does, I set the value idx, and exit the loop.

Examples

$ ./ch-2.py 1 3 5 7 9
3

$ ./ch-2.py 1 2 3 4 5
-1

$ ./ch-2.py 2 4 2
1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)