Weekly Challenge 106

Simon Green - Apr 4 '21 - - Dev Community

I'm back after a few weeks away on holiday. Hope you haven't missed me :)

Tasks, My solutions

TASK #1 › Maximum Gap

Task

You are given an array of integers @N.

Write a script to display the maximum difference between two successive elements once the array is sorted.

If the array contains only 1 element then display 0.

My solution

This is relatively straight forward. After checking that all inputs are integers, I sort the array numerically. Then I use a foreach loop to find the maximum difference between each number.

One liner

or as a one liner

» perl -E 'use List::Util "max"; my @a = sort { $a <=> $b } @ARGV; say max(0, map { $a[$_] - $a[$_-1] } (1 .. $#a) )' 1 3 8 2 0
5
Enter fullscreen mode Exit fullscreen mode

Examples

» ./ch-1.pl 2 9 3 5
4

» ./ch-1.pl 1 3 8 2 0
5

» ./ch-1.pl 5
0
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Decimal String

Task

You are given numerator and denominator i.e. $N and $D.

Write a script to convert the fraction into decimal string. If the fractional part is recurring then put it in parenthesis.

My solution

As I mentioned in a previous blog post, the last time I did serious algebra was in college about 25 years ago. These days there is a Wikipedia link on repeating decimals to help me.

For this task, I'm following the principle of doing long division to get to a point where we've already found a remainder. This indicates that we've found where a repetition pattern starts, and can add the parenthesis in the correct place. The Wikipedia page has an example of this, so I won't repeat it here.

Examples

» ./ch-2.pl 1 3
0.(3)

» ./ch-2.pl 1 2
0.5

» ./ch-2.pl 5 66
0.0(75)
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .