aboutsummaryrefslogtreecommitdiff
path: root/challenge-080/arne-sommer/perl/count-candies-sort-perl
blob: c019e9391d4233f5a4dafa0d16fbdda0f74c66be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#! /usr/bin/env perl

use strict;
use bigrat;   # -> inf
use feature 'signatures';

use Perl6::Junction 'all';
use List::Util qw/sum max/;
use Getopt::Long;
use feature 'say';

no warnings qw(experimental::signatures);

my $verbose = 0;

GetOptions("verbose"  => \$verbose);

my @N = @ARGV;

die "Please specify at least one element" unless @N;

die "Integers only" unless all(@N) == qr/^\d+$/;

push(@N, inf); unshift(@N, inf);

my %M = map { $_ => $N[$_] } 0 .. (@N -1);

my @C = (); ##  x (length(@N));

my $N_end = @N -2;

for my $index (sort { $M{$a} <=> $M{$b} } keys %M)
{
  $C[$index] = candy_count($index);
  say ": Index $index with value $M{$index} and candies $C[$index]" if $verbose;
}

if ($verbose)
{
  say ": Ranking w/border: " . join(", ", @N);
  say ": Candies w/border: " . join(", ", @C);

  say ": Ranking: " . join(", ", @N[1..$N_end]);
  say ": Candies: " . join(", ", @C[1..$N_end]);
}

say sum(@C);

sub candy_count ($index)
{
  return 0 if $index == 0 || $index == @N -1;

  return max($C[$index-1], $C[$index+1]) +1 if $N[$index] > $N[$index-1] || $N[$index] > $N[$index+1];

  return 1;
}