Friday, 1 November 2019

perl - find missing numbers in array

Method 1:

@a = (1,3,4,6); @c = map $a[$_-1]+1..$a[$_]-1, 1..@a-1; print join(" ", @c);




Method 2:

@a = (1,3,4,6); @c = map { ( $a[ $_ - 1 ] + 1 ) .. ( $a[ $_ ] - 1 ) } 1 .. $#a; print @c;



Method 3:

@a = (1,2,4,6); push @b, $a[ $_ ] +1 .. $a[ $_+1 ] -1 for 0 .. $#a-1; print @b;



Method 4:

@a = (1,2,4,6); @b = do {$i = 0; print grep { $_ == $a[ $i ] ? ++$i && 0 : 1 } $a[ 0 ] .. $a[ -1 ]; }



Method 5:

@a = (1,9,4,6); $i = 0; for ($c=$a[0]; $c<=$a[$#a]; $c++) { if ($c == $a[$i) { $i++; } else { print " $c\n"; } }



Method 6:

@a = (1,9,4,6); @b = grep { $var=$_; not grep $var==$_, @a } $a[0]..$a[$#a]; print @b;



Method 7:

@a = ( 1, 3, 4); %h = map { $_ => 1 } @a; foreach $i ( $a[0]..$a[-1]) { if ( ! defined @h{$i} ) { push @b, $i; } } print @b;


Method 8:

@a = (1 .. 10); @b = (1, 2, 4, 7, 8, 9); @c = (); $i = 0; for (@a) { push @c, $_ unless $b[$i] == $_ and ++$i; } print @c;



Method 9:

@b=(); @a=(1,3,5); @h{@a} = (); foreach $i (11..15) { push(@b, $i) unless exists $h{$i}; } print @b;



Method 10:

perl -lne '@a=(1..6); @b=(1..2,5..6); @c{@a}=(); delete @c{@b}; print for keys %c;';



Labels:

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home