27 November 2014

Quiz 54: Change duplicate names by appending with number

Problem:
There is a list of N students with their first names. Now if 2 or more students have same name, you need to change 2nd name to "name1", 3rd name to "name2" and so on. If there is only 1 occurrence of particular name, then it will remain as it is.

Input Format: 
N(number of students)
N lines with 1 name each

Output Format: 
n lines with modified names

Constraints: 
None

Sample Input
10
priya
satyam
shikha
sid
amit
shikha
amit
amit
amit
satyam

Sample Output:
priya
satyam
shikha
sid
amit
shikha1
amit1
amit2
amit3
satyam1

Explanations:
As soon as name "shikha" came for 2nd time, change it to "shikha1" and so on.


Solution:

chomp($n=<STDIN>);
%count=();
for($i=0;$i<$n;$i++) 
{
chomp($name=<STDIN>);
if($count{$name}) 
{
$name2=$name . $count{$name};
$count{$name}++;
push(@out,$name2);

else 
{
$count{$name}=1;
push(@out,$name);
}
}
foreach(@out)
{
print "$_\n";
}



Tips:
use of PERL hashes

No comments:

Post a Comment