Thursday, May 16, 2024

TWC269

Challenge Link

Task1

We count the number of even numbers because an even number's right most bit is 0, and see if that count is greater than one:

#!/usr/bin/env perl
use strict;
use warnings;

sub bitwise_or{
  (grep{($_ & 1) == 0} @{$_[0]}) > 1
}

printf "%d\n",bitwise_or([1,2,3,4,5]);
printf "%d\n",bitwise_or([2,3,8,16]);
printf "%d\n",bitwise_or([1,2,5,7,9]);

Task2

We keep pushing elements into two arrays as the requirements and concatenate and return the results:


#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub distribute_elements{
  my @ret1 = shift @{$_[0]};
  my @ret2 = shift @{$_[0]};
  while(@{$_[0]}){
    my $e = shift @{$_[0]};
    $ret1[-1] > $ret2[-1] ? push @ret1,$e : push @ret2,$e;
  }
  @ret1,@ret2
}

print show distribute_elements([2,1,3,4,5]);
print show distribute_elements([3,2,4]);
print show distribute_elements([5,4,3,8]);

Sunday, May 5, 2024

TWC268

Challenge Link

Task1

We take the absolute value of the first elements of arrays after sorting them:

#!/usr/bin/env perl
use strict;
use warnings;

sub magic_number{
  my @x = sort{$a <=> $b} @{$_[0]};
  my @y = sort{$a <=> $b} @{$_[1]};
  abs($x[0] - $y[0])
}

printf "%d\n",magic_number([3,7,5],[9,5,7]);
printf "%d\n",magic_number([1,2,1],[5,4,4]);
printf "%d\n",magic_number([2],[5]);

Task2

After sorting the array, we keep removing pairs of elements and push its reverse to the array that we want to return:

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub number_game{
  my @arr = sort{$a <=> $b} @{$_[0]};
  my @ret;
  push @ret,reverse splice @arr,0,2 while(@arr);
  @ret
}

print show number_game([2,5,3,4]);
print show number_game([9,4,1,3,6,4,6,1]);
print show number_game([1,2,2,3]);