in reply to Re: Divide array of integers into most similar value halves
in thread Divide array of integers into most similar value halves

Sorry to disappoint you BrowserUk,
your sub does not work if a number is repeated in the array.
Try @array = (33,33,37);
The solution is good in every other case, though. Only need that to be fixed.
Thanks a lot for your effort, anyways.
Pepe
  • Comment on Re^2: Divide array of integers into most similar value halves

Replies are listed 'Best First'.
Re^3: Divide array of integers into most similar value halves
by BrowserUk (Patriarch) on Sep 03, 2008 at 17:32 UTC

    Thanks. That is indeed a bug. The (lightly tested) fix is to change the last line of the sub to:

    return \@best, [ grep{ !exists $seen{ $_ } or !$seen{ $_ }-- } @$a +Ref ];

    Basically, because the sub only stores one best partition, when it runs out of iterations, it needs to filter the input array to generate teh other half. The filter was a sloppy variation on a theme that works for other purposes but not this. I think the above corrects it, but I will need to give more thought once my brain has awoken.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      BrowserUk,
      Your algorithm is the best I found so far, but it still has the bug with repeated numbers.
      I came out with a suboptimal solution, but in more than 100.000 arrays your code wins in every case the answer are different and there are no repeated elements.
      Now it does it only with more than 2 repetitions as in @array = (57,57,57,43,32). Would there be any way of solving that bug for any array no matter how many repeated elements it contains?
      I've tried but I don't seem to be able to do it. Your code is really tight and it's difficult for me to modify it.
      Sorry for the bugging. I really appreciate your efforts.
      Pepe
        Did you try my algorithm at Re^2: NP-complete sometimes isn't (A benchmark)? It is guaranteed to always find the best possible answer. It has no bug with repeated numbers. It is not the fastest option, but it may well be fast enough for your purposes.

        Sorry. I never got back to checking the fix properly.

        Would you please try replacing the last line with this (note:pre-decrement not post-decrement).

        return \@best, [ grep{ !exists $seen{ $_ } or !--$seen{ $_ } } @$a +Ref ];

        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
      I'll try it for you and report on it when I'm done.
      Maybe tomorrow.
      Thanks again fro your effort