Just a quick note... this was throwing exceptions for me, I believe
because you can't increment a map element that doesn't already exist.
Here's the solution I went with, which also returns the size of the
new slice (FYI, it's ok if I throw away duplicate strings, even if
they manage to show up twice in one slice but zero in the other).
func diffSlice (first, second []string) ([]string, int) {
count := make(map[string]int);
for _, x := range first {
_, present := count[x];
if !present {
count[x] = 0;
}
count[x]++;
}
for _, x := range second {
_, present := count[x];
if !present {
count[x] = 0;
}
count[x]++;
}
var result vector.StringVector;
for k, v := range count {
if v < 2 {
result.Push(k);
}
}
return result.Data(), len(result.Data());
> It seems pretty straightforward to port your Perl to Go.
>
> import (
> "container/vector"
> )
>
> func diff_array(first, second []string) []string {
> count := make(map[string]int)
> for _, ary := range [][]string{first, second} {
> for _, elem := range ary {
> count[elem]++
> }
> }
> var result vector.StringVector
> for k, v := range count {
> if v < 2 {
> result.Push(k)
> }
> }
> return result.Data()
>
>
>
>
>
> }
> On Fri, May 21, 2010 at 4:25 PM, Peter Allen <
pacdra...@gmail.com> wrote:
> > I'm having trouble trying to wrap my head around this...
>
> > I have two, unsorted, slices of strings and need to write a func that
> > will return the difference between the two. Something like this:
>
> > func diffSlice (firstSlice []string, secondSlice []string) []string {
>
> > I'd like it to return aslicethat only contains the strings NOT
> > present in both slices. I can do this pretty easily in perl using
> > hashes, but need a way to do it in go.
>
> > #Diffan array in perl
> > sub diff_array {
> > my $first = $_[0]; # A reference to the first array
> > my $second = $_[1]; # A reference to the second array
> > my @diff; # Thediffof the two arrays
> > my %count; # A hash to count the occurance of
> > each value
>
> > foreach my $value (@$first, @$second) {
> > $count{$value}++;
> > }
>
> > foreach my $value (keys %count) {
> > if ($count{$value} < 2) {
> > push(@diff, $value);
> > }
> > }
>
> > return(@diff);
> > }
>
> --
> Kevin Ballardhttp://
kevin.sb.org
>
kball...@gmail.com