Page 1 of 1

Finding duplicate in an array

Posted: Wed Oct 24, 2007 9:53 am
by kkonline
I have an array of positive integers.
The length of array is known "n".
The maximum and the minimum values in the arrays are known (thay are unique for simplicity)

The aim: to display/remove the duplicate entries in array

I cannot make out what to do with the minimum and maximum values to make the algorithm efficient

Posted: Wed Oct 24, 2007 9:55 am
by Zoxive
To remove the duplicates you can use the built in function, array_unique.

Posted: Wed Oct 24, 2007 10:01 am
by kkonline
Zoxive wrote:To remove the duplicates you can use the built in function, array_unique.
Hi, thanks for that but i am looking for an algorithm using all the given info

Posted: Wed Oct 24, 2007 10:17 am
by onion2k
How are you doing it at the moment?

Posted: Wed Oct 24, 2007 10:24 am
by kkonline
onion2k wrote:How are you doing it at the moment?
Note :the values are not sorted and

Just taking the 1st value comparing with all array elements, if found in array then duplicate else not...

but in this case max. and min. values are not used what to do

or another algo

subtract each value from max and then store the difference if difference same then duplicate.

in this min. value is not used

Posted: Wed Oct 24, 2007 10:40 am
by Stryks
Sorry, does this relate to a previous thread?

You stated your aim ...
The aim: to display/remove the duplicate entries in array
And I'm pretty sure that array_unique() does just that. The removal part anyhow. As for the display, I guess you could find the duplicates for whatever purpose by, say ...

Code: Select all

$arr_old = array('cat', 'dog', 'monkey', 'dog');
$arr_new = array_unique($arr_old);
$arr_dupes = array_diff_assoc($arr_old, $arr_new);
I haven't tested it, but $arr_new should hold all values with just duplicates removed, and $arr_dupes should hold all of the discarded duplicate items, so you can display it or whatever.

This should take care of the items you specify as your aim. If there is some other requirement, perhaps you need to give more info, or an updated aim.

Cheers

EDIT | You replied while I was posting, so sorry if my answer seems a bit disjointed. Any reason why you dont just sort the array before looping. You could just call it a dupe if the current one matches the last.