Advertisement

removing doubles from an array

Started by May 27, 2000 08:23 PM
1 comment, last by dj9781 24 years, 7 months ago
How can I remove all double occurences of a value from an array? Is there a function that does this for me?
quote: Original post by dj9781

How can I remove all double occurences of a value from an array? Is there a function that does this for me?


Since you are asking for a predefined function, what language are you using?

However, there are several techinques you could use to strip the double occurrences out. Basically you can do it with two nested loops as in the following (crappy) code:

    /*     *  Strips double occurrences from the ''nSrcLength'' elements     *  long array ''pnSrc'', storing the singletons in     *  the array ''pnDst''. Returns the length of the new     *  (stripped) array.     */    INT stripDoubleOccurrences(INT pnDst[], INT pnSrc[], INT nSrcLength)    {        INT i, j, nDstLength = 0;        BOOL bFound;        for (i = 0; i < n; i++) {            bFound = FALSE;            for (j = 0; j < nDstLength; j++) {                if (pnDst[j] == pnSrc) {                    bFound == TRUE;                    break;                }            }            if (bFound == FALSE) {                pnDst[nDstLength] = pnSrc;<br>                nDstLength += 1;<br>            }<br>        }<br><br>        return(nDstLength);<br>    }<br><br> </pre> <br><br>I''ve tried to keep the code as simple as possible. Obviously, it can be optimized a lot. The code above it''s meant to be used with small arrays. With huge arrays you could sort it (e.g. with a fast algorithm such as quick-sort) then scan it. Moreover, if you know in advance the range of the elements of the array (and it''s not too big) you can use a binary-search tecnique to access the array content.<br><br>Hope to be useful.<br><br><br>Karmalaa  </i>   <br><br> 
---[home page] [[email=karmalaa@inwind.it]e-mail[/email]]
Advertisement
quote: Original post by karmalaa

        for (i = 0; i < n; i++) { 




Opps... sweety tiny errata corrige... this should be

        for (i = 0; i < nSrcLength; i++) { 



Karmalaa

---[home page] [[email=karmalaa@inwind.it]e-mail[/email]]

This topic is closed to new replies.

Advertisement