in reply to Don't-Repeat-Myself code for improvement

If the IDs are fixed and known in advance, you could take the set of IDs, shuffle them, and print them to a file. Then in the cron job, you open the file, take the first one, and rewrite the the file (excluding the first one), and then deal with the ID. This gives you a guarantee that all IDs will be visited before any are repeated.

Eventually you'll clean the file out completely. At that point, you generate a new shuffled list of IDs, print them to a file and begin all over again. This has the advantage that you can edit the seed file as needed in order to test out certain IDs explicitly, without having to wait for randomness to deal you the right cards.

• another intruder with the mooring in the heart of the Perl

  • Comment on Re: Don't-Repeat-Myself code for improvement

Replies are listed 'Best First'.
Re^2: Don't-Repeat-Myself code for improvement (REsort)
by tye (Sage) on Feb 27, 2007 at 23:27 UTC

    If it is important to cycle through all IDs, then this meets that requirement. But it can easily result in the same ID being used twice in a row (as I noted in my other reply to BrowserUk's proposal of nearly the same method).

    If this "use all IDs before repeating" is an important criteria, then I'd modify this proposal to include the offset to the next item in said file. Then you rewrite just the offset when you use an item.

    Then the trick is shuffling the items after they have all been used such that you don't get any of the recently used ones being near the top of the list.

    One way to do that would be to assign the items values of 1..$N ($N is the number of items) and then add1 rand($N/$F) to each value (where $F controls how random things are vs the minimum distance between repeats) and then sort the items based on the assigned values. For example:

    my( @items )= <FILE>; pop @items; # Remove the "offset" chomp @items; my %value; @value{ @items }= 1 .. @items; $_ += rand(@items/3) for @value{ keys %value }; @items= sort { $value{$a} <=> $value{$b} } @items; print NEWFILE join "\n", @items, 0, ''; # move NEWFILE to replace FILE

    - tye        

    1 Updated to add missing word.