DEV Community

loading...

Weekly Challenge 106

simongreennet profile image Simon Green ・2 min read

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

Discussion (1)

pic
Editor guide
Collapse
simongreennet profile image
Simon Green Author

After looking at other peoples solutions (which I only do after I submit my solution), it appears I don't handle the case of one negative number correct. -5 ÷ 74 results in 0.0(-6-7-5). I stuffed this one up, so Colin might consider this an invalid solution in his weekly write up, and I wouldn't disagree with that :)

I'm not afraid to admit when I am wrong.