I really don't see any big improvements that could be made in that code. I did some benchmarking and I was able to get a small improvement for really large strings (at the expense of a small performance degredation for short strings) by computing the string length only once. i.e.
my $len=length($my_astr); $c1 = substr($my_astr, $p1 = int rand($len), 1); $c2 = substr($my_astr, $p2 = int rand($len), 1);

I was able to get another small performance boost by doing away with the temp variables $c1 and $c2. However, this code should be viewed with suspicion because it would really misbehave if you were moving more than 1 character blocks and the blocks happened to overlap.

$p1 = int rand(length($my_astr)); $p2 = int rand(length($my_astr)); substr($my_astr, $p1, 1, substr($my_astr, $p2, 1)); substr($my_astr, $p2, 1, substr($my_astr, $p1, 1));

When you say "flipping more than 2 characters at a time" do you mean "flipping 2 blocks of more than 1 character each" at a time or "flipping more than 2 blocks of 1 character each"?

flipping 2 blocks of more than 1 character at a time - would require either a check to prevent the blocks overlapping or special code to handle overlapping blocks properly (depending on how you define properly).

flipping more than 2 blocks of 1 character each - implementation of this depends on how you define flipping. If you pick A, B, C, and D to flip do you exchange A with B, B with A, C with D and D with A or do you replace A with B, B with C, C with D, and D with A?


In reply to Re: character flipping by lhoward
in thread character flipping by ar0n

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.