Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Fast Way to Return Unique Array of Array

by pg (Canon)
on Sep 05, 2005 at 04:05 UTC ( [id://489135]=note: print w/replies, xml ) Need Help??


in reply to Re: Fast Way to Return Unique Array of Array
in thread Fast Way to Return Unique Array of Array

There are some risks here: (I can easily come up some data to make this fail.)

use strict; use Data::Dumper; my @AoA = (['a,','b','c'], ['a',',b','c'], ); my $uAoA = uniqAoA(\@AoA); print Dumper $uAoA; sub uniqAoA { my ($array) = @_; my %res; foreach my $ar (@{$array}) { my $str = join (",",@{$ar}); $res{$str} = 1; } my @kys = keys(%res); my @final; foreach(@kys) { my @a = split(",",$_); push @final, [ @a ]; } return \@final; }

This should return the orginal AoA, but it returns:

$VAR1 = [ [ 'a', '', 'b', 'c' ] ];

Problems are:

  • It thought the two level 2 arrays are the same, when they are different.
  • The element contained in the returned array was not originally there.

Replies are listed 'Best First'.
Re^3: Fast Way to Return Unique Array of Array
by monkfan (Curate) on Sep 05, 2005 at 04:13 UTC
    Hi pg,
    my @AoA = (['a,','b','c'], ['a',',b','c'], );
    Your example above is problematic: Shouldn't it be this:
    my @AoA = (['a','b','c'], ['a','b','c'], );
    With the latest modification of your example my code still return the correct answer.

    Regards,
    Edward

      No, your program does not return the correct answer all the time. The problem is that your code would not work with data that contains ','.

      Testing is not to prove one's code is correct, but rather to find out the exceptions.

      There is no problem with my input. By readng your code, I knew that it would fail if the data contains ',', as your program first concat elements with ',', and then split by ','. When the data contains ',', the problem arises, as:

      • Your code cannot split the concated string back to the orginal elements correctly any more.
      • Also, that two concated strings are the same, does not mean that the two original arrays before concat are the same. In my example, the two different arrays will both concat to "a,,b,c", and that fails your code.

      You cannot say that the input is wrong, because your code cannot handle it. In this thread, the correct solutions should be able to handle any two dimentional AoA. Your program does not satisfy this.

      Your code is not bad, but it certainly can be better.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-03-28 16:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found