Forum Moderators: coopster

Message Too Old, No Replies

Difference Algo

         

dmorison

4:48 pm on Dec 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You have 4 variables: $a, $b, $c and $d.

What's most efficient way to check that they ALL contain different values?

I'll post my entry once i've had a crack at it... :)

justageek

5:51 pm on Dec 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Maybe this:

$myarray[] = $a;
$myarray[] = $b;
$myarray[] = $c;
$myarray[] = $d;

$myuniquearray = array_unique($myarray);

if(count($myarray) <> count($myuniquearray)){
// There are dupes
}else{
// They are all different
}

JAG

surfin2u

5:56 pm on Dec 17, 2005 (gmt 0)

10+ Year Member



how about:

$arr = array();
$arr[$a] = 1;
$arr[$b] = 1;
$arr[$c] = 1;
$arr[$d] = 1;
if (count($arr) == 4)
echo "all different";

FalseDawn

11:31 pm on Dec 17, 2005 (gmt 0)

10+ Year Member



With only 4 values, I'd just do a straight compare:

if ($a!=$b && $a!=$c && $a!=$d && $b!=$c && $b!=d && $c!=$d) {all different}

surfin2u

3:04 pm on Dec 18, 2005 (gmt 0)

10+ Year Member



...and I thought my solution was so clever, but FalseDawn I think that you've hit the nail on the head!

justageek

3:12 pm on Dec 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I guess I'm always thinking scalability ;-)

JAG

surfin2u

5:08 pm on Dec 18, 2005 (gmt 0)

10+ Year Member



I guess I'm always thinking scalability ;-)

requirements first, scalability only if required... ;-)

I think my solution is fastest when a larger amount of data is involved.

ergophobe

5:58 am on Dec 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



How about this if you want it to scale *and* you have lots of data in each variable.

$size = count($data_array);

for ($i=0; $i<$size; $i++)
{
$key = md5($data_array[$i]);
$unique_array[$key] = 1;
}

At least that way you won't end up trying to create a 600 character array key.

surfin2u

11:20 pm on Dec 20, 2005 (gmt 0)

10+ Year Member



At least that way you won't end up trying to create a 600 character array key.

What's wrong with a 600 character array key?

ergophobe

1:47 am on Dec 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Okay, you won't be trying to make a 1.2MB array key.

Raises an interesting question: what is the limit on the size of an array key? Is it just a function of system memory? An array index is merely a string and the manual says


Note: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.

So I take it back. Go ahead and index your arrays using the contents of a volume of the Encyclopedia Britannica. Looks like it should be okay ;-)

surfin2u

12:47 am on Dec 22, 2005 (gmt 0)

10+ Year Member



PHP arrays are the greatest!