4 January 2015

Quiz 75: Change array to have unique elements only

Problem:

Given an array, you have to print another array containing only unique elements ie removing duplicate elements

Input Format: 

Array->Each element separated by space


Output Format: 

Unique Array->Each element separated by space


Constraints: 

None

Sample Input

1 3 4 2 3 5 7 7 7 4 9 0 0 2

Sample Output:

1 3 4 2 5 7 9 0

Explanations:

removed duplicate elements from original array



Solution:

use strict;
use warnings;

sub unique {
    my %found;
    grep !$found{$_}++, @_;
}

chomp(my $in=<STDIN>);
my @array = split(" ",$in);
@array = unique(@array);
foreach(@array)
{
print "$_ ";
}


Tips:

Learn use of Hash and Grep

No comments:

Post a Comment