Wednesday, August 18, 2010

Find the missing element - There are 9 No's which are distinct and are within the range 1-10. How to find the missing element.

Solution 1:

#!/depot/perl-5.8.3/bin/perl

@array=(1, 2, 3, 4, 5, 6, 7, 8, 10);
foreach $n (1..10) {
if (!grep (/\b$n\b/,@array)) {
    print "$n \n";
}
}

Solution 2:

As the no's are in sequence and without repetition we can use the summation formula n (n + 1) /2.

 #!/depot/perl-5.8.3/bin/perl

@array=(1, 2, 3, 4, 5, 6, 7, 8, 10);
my $sum_of_10_consecutive_no=(10 * 11 / 2);
my $sum=0;
foreach (@array) {
    $sum += $_;
    }
print $sum_of_10_consecutive_no - $sum;

No comments:

Post a Comment