Peter’s blog ✴ Week 304 ✴ 13 January 2025
THE WEEKLY CHALLENGE
Adding ones and maxing the mean
You are given an array of integers, @ints and an integer, $n which is less than or equal to total
elements in the given array.
Write a script to find the contiguous subarray whose length is the given integer, $n, and has the maximum average. It should return the average.
Example 1 Input: @ints = (1, 12, -5, -6, 50, 3), $n = 4 Output: 12.75 Subarray: (12, -5, -6, 50) Average: (12 - 5 - 6 + 50) / 4 = 12.75 Example 2 Input: @ints = (5), $n = 1 Output: 5
The easy way to do this is just to calculate the average of all the possible subarrays,
of which there will only be length(@ints) - $n + 2. Even if @ints contains
10 000 integers this takes less than a second.
So that's what I am submitting.
Nice hack to make the task easier. DIY tool lets you play with it too.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-01-13 use utf8; # Week 304 - task 2 - Maximum average use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; maximum_average([1, 12, -5, -6, 50, 3], 4); maximum_average([5, 5, 5, 5, 0, 0, 0], 4); maximum_average([0, 0, 0, 0, 0, 6, 6], 5); my @ints; push @ints, int(rand(100)) - 50 for 1 .. 100; maximum_average(\@ints, 10); sub maximum_average { my (@ints, $n, $max_average, $max_suum, $start, $sum, $average, $subarray); # initialise @ints = @{$_[0]}; $n = $_[1]; $max_average = 0; # loop over staring points for $start (0 .. $#ints - $n + 1) { $sum = 0; $sum += $_ for @ints[$start .. $start + $n - 1]; $average = $sum / $n; # potential answer if ($average > $max_average) { $max_average = $average; $subarray = join(', ', @ints[$start .. $start + $n - 1]); } } # report say qq[\nInput: \@ints = (] . join(', ', @ints) . qq[), \$n = $n]; say qq[Output: $max_average - ($subarray)]; }
14 lines of code
Input: @ints = (1, 12, -5, -6, 50, 3), $n = 4 Output: 12.75 - (12, -5, -6, 50) Input: @ints = (5, 5, 5, 5, 0, 0, 0), $n = 4 Output: 5 - (5, 5, 5, 5) Input: @ints = (0, 0, 0, 0, 0, 6, 6), $n = 5 Output: 2.4 - (0, 0, 0, 6, 6) Input: @ints = (-37, -1, -20, -28, -34, 33, -28, 27, -39, 13, -12, -23, 9, -8, 6, -16, 47, -43, 40, -25, 23, -42, -34, 28, -31, 31, 28, -11, 10, -26, 18, 6, -32, -11, 42, 46, 16, -40, 34, -18, -49, 47, 16, -21, 17, 30, -32, 28, -32, -25, 31, 34, 4, -39, 13, -35, -41, -31, 37, -48, -31, -8, -3, -49, 30, -23, 39, 7, -47, 40, 41, 21, -36, -49, 33, -13, -39, -39, 9, 40, 47, 23, 49, -20, -4, 4, 16, 48, 32, -37, 35, -25, -2, 33, -43, -33, -9, -21, -40, 40), $n = 10 Output: 23.5 - (40, 47, 23, 49, -20, -4, 4, 16, 48, 32)
Any content of this website which has been created by Peter Campbell Smith is in the public domain