Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
more useful options
 
PerlMonks  

Re: compare two strings and return only he unique values.

by blue_cowdawg (Prior)
on Feb 03, 2013 at 19:33 UTC ( #1016853=note: print w/ replies, xml ) Need Help??


in reply to compare two strings and return only he unique values.

      I am trying to display unique values from two strings "ABCDE", "BCDEO" to return "AO" with the below code

#!/usr/bin/perl -w use strict; use warnings; my $string1="abcdef"; my $string2="defghi"; my @ary=split(//,$string1); push @ary,split(//,$string2); my %een=(); map{ $een{$_}++ } @ary; my @unique=(); foreach (@ary){ next unless $een{$_} == 1; push @unique,$_; } printf "%s\n",join(",",@unique);
Hashes are our friends....


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg


Comment on Re: compare two strings and return only he unique values.
Download Code
Re^2: compare two strings and return only he unique values.
by Kenosis (Priest) on Feb 03, 2013 at 21:24 UTC

    Won't show "a" when:

    my $string1="abcdefa"; my $string2="defghi";
          Won't show "a" when:

      That's because "a" isn't unique. :)

      printf "%s\n",join(",", keys %een);
      would show "a" and all the other letters once.


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

        Your code quite effectively forms a union of the two strings' characters. However, the OP's request was to 1) compare two strings, and 2) return only the unique values. Where does your code compare the two strings? Forming a union of their characters does not compare the two strings. In fact, if we strictly regard their union as a non-multiset of characters, "a" is unique, since (set notation): {a} = {a,a} = {a,a,a}. Thus, "a" should still appear in their union--even with two occurrences within one string.

        As has been point out, the OP's specs are equivocal, yet I tend to favor "unique" as meaning a character (replicated or not) that only belongs to one or the other string (i.e., "unique to")--and is not in both.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016853]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (21)
As of 2014-04-16 14:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (431 votes), past polls