I wonder if you've overlooked my solution, or if there's anything wrong with it.

Not only is it simpler (both less lines of code and conceptually easier to understand, IMHO), it's also consistently faster than what you found to be the fastest:

$ ./846784.pl Rate salva almut salva 881/s -- -15% almut 1037/s 18% --

(tested with v5.10.1, x86_64-linux-thread-multi)

#!/usr/bin/perl use Benchmark "cmpthese"; my $len = shift @ARGV || 12; my $max_reps = shift @ARGV || 2; sub almut { my @set = qw( A B C D E F ); for (1..100) { my $result = ''; while (length($result) < $len) { my $char = $set[ rand @set ]; next if substr($result, -$max_reps) eq $char x $max_reps; $result .= $char; } } } sub salva { my $set = [ qw( A B C D E F ) ]; for (1..100) { my $out = ''; my $last_ix = -1; my $reps = 0; for (1..$len) { my $ix; if ($reps >= $max_reps) { $ix = int rand(@$set - 1); $ix++ if $ix >= $last_ix; } else { $ix = int rand(@$set); } if ($ix == $last_ix) { $reps++; } else { $last_ix = $ix; $reps = 1; } $out .= $set->[$ix]; } } } cmpthese(-1, { almut => \&almut, salva => \&salva, });

In reply to Re^3: Random data generation. by almut
in thread Random data generation. by BrowserUk

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.