# RogerBW's Blog

 Perl Weekly Challenge 106: Maximum Decimal 31 March 2021 I’ve been doing the Perl Weekly Challenges. The latest involved integer differences and decimal expansion. (Note that this is open until 4 April 2021.) TASK #1 › Maximum Gap 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. I can't see any short-cuts here: we have to subtract every pair of numbers. (I mean, given a sorted list I suppose one might be able to bracket it and skip some comparisons, but it would probably be more work than just doing the calculation.) A straightforward procedure, therefore: sort the input list, set max-difference to zero, do each subtraction, set max-difference to it if it's higher. Let's have that in Raku: ``````sub mg(**@aa) { my @a=@aa.sort; my \$g=0; for (0..@a.elems-2) -> \$i { my \$d=abs(@a[\$i]-@a[\$i+1]); if (\$d>\$g) { \$g=\$d; } } return \$g; } `````` and the other languages all look very much the same. TASK #2 › Decimal String 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. Clearly the hard part here is working out whether you have a recurring decimal. I had a look at prime-factoring the numbers (any remaining factors that aren't 2 or 5 means an infinite expansion) but then came across this convenient algorithm – so I reimplemented that in Perl (with some tweaks, like using arrays rather than strings where it made sense), then translated the Perl version in the other languages. (It does assume the inputs are positive.) Let's have that in Perl: ``````sub ds { my \$n=shift; my \$d=shift; my \$quotient=sprintf('%d.',\$n/\$d); my \$c=10*(\$n % \$d); while (\$c > 0 && \$c < \$d) { \$c *= 10; \$quotient .= "0"; } my @digits; my %passed; my \$i=0; while (1) { if (exists \$passed{\$c}) { my @cycle=@digits[\$passed{\$c}..\$#digits]; my \$result=\$quotient . join('',@digits[0..\$passed{\$c}-1]); if (scalar @cycle > 1 || \$cycle[0] != 0) { \$result .= '('.join('',@cycle).')'; } if (substr(\$result,-1,1) eq '.') { substr(\$result,-1,1)=''; } return \$result; } my \$q=int(\$c/\$d); my \$r=\$c % \$d; \$passed{\$c}=\$i; push @digits,\$q; \$i++; \$c=10*\$r; } } `````` The other versions look much the same, except for the tweaks needed to shift around between digits and strings. Full code on github. Posted by RogerBW at 01:28pm on 05 April 2021 Looking at other people's blog posts… In part 1, my `abs` was unnecessary, but otherwise nobody came up with anything terribly different except for one rather odd (but effective) recursive approach. One can get cunning with hashes and the zip operator but it all just takes more space. For part 2, Raku has a base-repeating function which is essentially defined to solve this problem. (Of course it does!) Someone finished off the prime-factorisation approach that I'd considered, but I don't think their solution was notably simpler than mine. Some people looked at the string expansion, but I think this would fail in too many cases given the limitations of floating-point arithmetic. Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one. Search 10 per page 20 per page 50 per page 100 per page Archive Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2022 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult Special All book reviews, All film reviews
Produced by aikakirja v0.1