0

I'm doing a subroutine that takes a list of numbers as an argument. What I would like to do is check if there is a repeated value in that list. In case there are repeated numbers, print a message and stop the program. In case there are no repeated numbers, continue with the execution.

For example:

if (there_is_number_repeated){
    print "There is a number repeated";}
else{
    run this code...}

I was trying to do this creating a hash with the values of that list, and then check if there are values > 1.

    use strict;
    use warnings;

sub name_subroutine{
    my (@numbers)=@_;
    my $n=scalar(@numbers);

    my %table=();

    foreach my $i(@numbers){
    if (exists $tabla{$i}){
        $tabla{$i}+=1;}
    else{
        $tabla{$i} = 1;
    }
my @values = values %tabla;
}
}

It's here where I do not know to continue. Is there any way to do this in an amateurish way? I'm newbie in Perl.

Thanks!

1
  • Please note that you wrote both table and tabla. Presumably you tried to translate your variables name to English. For next times, you don't need to translate them, or make sure your script still behave the same after the translation. Commented Feb 15, 2017 at 7:19

2 Answers 2

8

I would just do:

my %uniq;
if ( grep ++$uniq{$_} > 1, @numbers ) {
     # some numbers are repeated
}

In your existing code (with a couple corrections):

my %table=();

foreach my $i(@numbers){
    if (exists $table{$i}){
        $table{$i}+=1;}
    else{
        $table{$i} = 1;
    }
}
my @values = values %table;

you don't need to check for exists; doing += 1 or ++ will set it to 1 if it didn't exist. And you don't want the values (those are just the counts of how many times each array value was found), you want the keys, specifically those for which the value is > 1:

my @repeated = grep $table{$_} > 1, keys %table;
Sign up to request clarification or add additional context in comments.

Comments

0
my @arr = @_; 
my $count = @arr;
for(my $i=0;$i<$count;$i++)
{
    my $num = $arr[$i];
    for(my $j=0; $j<$count,$j!=$i; $j++)
    {
        if($num == $arr[$j])
        {
           print "\n$num is repeated";
           last;
        }  
    }
}  

Tried and tested. Cheers.

2 Comments

You should mention the time complexity of your answer (O(n*n)), which is way more than ysth's one. (But your space complexity is lower than his)
Thank you sir for your review. I am actually newbie in coding. Will take care of it from now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.