Reading the clarified question in
random negative toggle function reminded me of an question that's been bothering me for a while. Say I have an array with N elements, which I want to randomly set to either 0 or 1 but have a total of M (<=N). I know I can loop M times finding a random 0-element to switch to a 1 element (or if M > N/2, initializing all to 1 and setting N-M elements to 0), but is there a way to do it sequentially
and yet insure a random distribution?
If I just loop through, giving each element a chance to be set of (how many ones left to assign) over (how many elements are left), it seems to me that that will distort the distribution toward the end.
Update: Many thanks to all who replied. What I was looking for was a random distribution, not an even distribution, and with a total of M, not an total averaging M, determined sequentially. Abigail-II's answer fits. Using the List::Util::shuffle to prepare a sequence and pulling elements off of it as I go through the real data also would fit the bill.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.