Hello,

Are you supposed to read the previously generated numbers list from the file each time ? Or are you allowed to cache these results ?

I mean, if you have to read 300.000 numbers from a text file, each and every time you run your script, then generate a number, check that it's not already generated, loop until you have an "original" number, then write down all the previously generated numbers AND the new, original one, yes, it would be costly.

However, you may use a hash to store the generated numbers. One hash is enough, with the numbers being the keys (you don't even need anything as the values, 1 or undef will work just as well). This should make the search for previous occurences happen in constant time (and I mean FAST).

You might index the previously generated numbers in a "clever" way, maybe bitwise, in your TXT, so that you do NOT have to read a whole, huge, file each time (you may store 8 bits per byte, each of them could represent one of the combinations).

You could sort your file, but that would only be relevant if you had to search through it for each number - which you really shouldn't do, whether you generate only ONE new number per run, or a whole batch of them, as you might have to reroll each of them based on previously generated numbers, you might as well put them all in memory.

As for writing your file, you really should append the new result to the end of it, without rewriting previous entries, unless you wish to keep it sorted.


In reply to Re: Check randomly generated numbers have not been used before by kzwix
in thread Check randomly generated numbers have not been used before by R3search3R

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.