Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proficient way to check if 3 variables are all unique

I wanted to write a script that checks if 3 variables (A,B,C) are all unique and dont equal each other. I thought of just doing a big if statement like:

if (A != B) && (A != C) && (B != C){
    // do function }

I was just wondering if there is another way? Because the code looks kindof clunky. This is in Perl.

like image 373
user3767853 Avatar asked Jul 09 '14 14:07

user3767853


1 Answers

Abstracting complicated details (e.g. those that "look clunky") is the point of subs. Move the logic to a sub if you don't like seeing it. Personally, that looks fine for me for three variables.

Note that if you're moving the code to a sub, you might consider using an O(N) algorithm. Your current approach scales poorly (O(N2)).

sub are_distinct {
   my %seen;
   ++$seen{$_} for @_;
   return keys(%seen) == @_;
}

Optimized to exit as soon as possible:

sub are_distinct {
   my %seen;
   for (@_) {
      return 0 if $seen{$_}++;
   }

   return 1;
}
like image 147
ikegami Avatar answered Oct 30 '22 14:10

ikegami