diff options
| author | user-person <60802990+user-person@users.noreply.github.com> | 2020-03-08 15:41:37 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-03-08 15:41:37 -0400 |
| commit | 6b9b40509bc743c8c2edd318284861e8e92e93de (patch) | |
| tree | db92f9980154b20e8ec8edcd4fecbf86373c2b69 | |
| parent | 0db39263ec06f9daa6c5e4badac018abfb53c0ea (diff) | |
| download | perlweeklychallenge-club-6b9b40509bc743c8c2edd318284861e8e92e93de.tar.gz perlweeklychallenge-club-6b9b40509bc743c8c2edd318284861e8e92e93de.tar.bz2 perlweeklychallenge-club-6b9b40509bc743c8c2edd318284861e8e92e93de.zip | |
Create ch-1.pl
| -rw-r--r-- | challenge-050/user-person/perl/ch-1.pl | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/challenge-050/user-person/perl/ch-1.pl b/challenge-050/user-person/perl/ch-1.pl new file mode 100644 index 0000000000..335abc3172 --- /dev/null +++ b/challenge-050/user-person/perl/ch-1.pl @@ -0,0 +1,77 @@ +#!/usr/bin/env perl + +########################################################################### +# script name: ch-1.pl # +# # +# https://github.com/user-person # +# # +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-050/ # +# # +# Merge Intervals # +# Write a script to merge the given intervals where ever possible. # +# # +# [2,7], [3,9], [10,12], [15,19], [18,22] # +# # +# The script should merge [2, 7] and [3, 9] together to return [2, 9]. # +# # +# Similarly it should also merge [15, 19] and [18, 22] together to # +# return [15, 22]. # +# # +# The final result should be something like below: # +# # +# [2, 9], [10, 12], [15, 22] # +# # +########################################################################### + +use strict; +use warnings; +use List::MoreUtils qw( minmax ); + +my $input = "[2,7], [3,9], [10,12], [15,19], [18,22]"; + +$input = "@ARGV" if @ARGV; + +$input =~ s{[][, ]+}{ }g; +$input =~ s{\A\s+|\s+\Z}{}; + +my @sets = split m{ }, $input; + +sub printSets { + for (my $i=0; $i < $#_; $i += 2) { + print "[$_[$i], $_[$i+1]]"; + print ", " if $i+1 < $#_; + } + print "\n"; +} + +sub mergeUnits { + my @indicies = @_; + my ($min, $max) = minmax ( $sets[$indicies[0]], $sets[$indicies[1]], $sets[$indicies[2]], $sets[$indicies[3]] ); + push @sets, $min; + push @sets, $max; + + foreach ( sort { $b <=> $a } @indicies ) { + splice @sets, $_, 1; + } +} + +print "UNMERGED:\n"; +printSets @sets; + +OUTER: +for (my $j=0; $j < $#sets; $j += 2) { + for ( my $k=$j+2; $k < $#sets; $k += 2) { + + if ( $sets[$k] >= $sets[$j] and $sets[$k] <= $sets[$j+1] + or $sets[$k+1] >= $sets[$j] and $sets[$k+1] <= $sets[$j+1] ) { + + mergeUnits $j, $j+1, $k, $k+1; + $j = -2; # This resets OUTER loop to 0 after its double increment + next OUTER; + } + } +} + +@sets = sort { $a <=> $b } @sets; +print "\nMERGED:\n"; +printSets @sets; |
