Tuesday, September 19, 2023

TWC235

Challenge Link

Task1

We are asked to see if by removing only one integer we can make the array to be in increasing order. We remove an element each time and check if without it the array is in ascending order or not:


 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
#!/usr/bin/env perl
use strict;
use warnings;

sub is_ascending{
  my ($arr) = @_;
  my $cursor = 0;
  map{$cursor++ if $arr->[$_] < $arr->[$_+1]} 0..$#$arr-1;
  $cursor == $#$arr
}

sub remove_one{
  my @arr = @{$_[0]};
  my $res = 0;
  foreach my $i(0..$#arr){
    my @ret = @arr[0..$i-1,$i+1..$#arr];
    if($i == 0){@ret = @arr[1..$#arr]}
    elsif($i == $#arr){@ret = @arr[0..$#arr-1]}
    $res = 1 if is_ascending(\@ret);
  }
  $res
}

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


Task2

We are asked to duplicate any zero seen and stop when the array's length is equal to that of the original:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/env perl
use strict;
use warnings;

sub duplicate_zeros{
  my ($arr) = @_;
  my @ret;
  foreach(@$arr){
    last if @ret == @$arr;
    $_ == 0 ? splice @ret,@ret,0,0,0 : push @ret,$_;
  }
  @ret
}

printf "(%s)\n", join ',',duplicate_zeros([1,0,2,3,0,4,5,0]);
printf "(%s)\n", join ',',duplicate_zeros([1,2,3]);
printf "(%s)\n", join ',',duplicate_zeros([0,3,0,4,5]);

No comments:

Post a Comment