Monday, October 26, 2026

TWC397

Challenge Link

Task1

We find the smallest number greater than average of the array:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
use List::Util qw(max sum0);

sub absent_smallest_positive{
  my ($arr) = @_;
  my ($sum,%h);
  foreach(@$arr){
    $h{$_} = 1;
    $sum += $_;
  }
  my $ret = max(1,int($sum / @$arr) + 1);
  $ret++ while(exists $h{$ret});
  $ret
}

is absent_smallest_positive([1,2,4,5,6]),7,'Example 1';
is absent_smallest_positive([-5,-2,-1,3]),1,'Example 2';
is absent_smallest_positive([1..3]),4,'Example 3';
is absent_smallest_positive([2,3,7,8]),6,'Example 4';
is absent_smallest_positive([1,1,1,10]),4,'Example 5';

Task2

We first sort by binary representation, then by numbers themselves:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub binary_reflection{
  my $rb = sub{oct('0b' . reverse sprintf("%b",shift))};
  [sort{$rb->($a) <=> $rb->($b) || $a <=> $b} @{$_[0]}]
}

is_deeply binary_reflection([3,6,12]),[3,6,12],'Example 1';
is_deeply binary_reflection([1,2,4,8]),[1,2,4,8],'Example 2';
is_deeply binary_reflection([7,8,9,10]),[8,10,7,9],'Example 3';
is_deeply binary_reflection([5,9,15,17]),[5,9,15,17],'Example 4';
is_deeply binary_reflection([11,13,14,19]),[14,13,11,19],'Example 5';

No comments:

Post a Comment