Saturday, November 4, 2023

TWC127

Challenge Link

Task1

Two sets are disjoint if they have no common elements, which means the count of the items in both sets are all 1.
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(all);

sub disjoint_sets{
  my ($s1,$s2) = @_;
  my %h;
  map{$h{$s1->[$_]}++; $h{$s2->[$_]}++} 0..$#$s1;
  all{$_ == 1} values %h;
}

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

Task2

Two intervals conflict if x1 >= x2 and x1 <= y2 where (x1,y1),(x2,y2) are our intervals:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub conflict_intervals{
  my ($arr) = @_;
  my @ret;
  foreach my $i(1..$#$arr){
    my $b = 0;
    foreach my $j(0..$i-1){
      $b = 1 if $arr->[$i][0] >= $arr->[$j][0] &&
	$arr->[$i][0] <= $arr->[$j][1];
    }
    push @ret, $arr->[$i] if $b;
  }
  @ret
}

print show conflict_intervals([[1,4],[3,5],[6,8],[12,13],[3,20]]);
print show conflict_intervals([[3,4],[5,7],[6,9],[10,12],[13,15]]);

No comments:

Post a Comment