in reply to Random data generation.

Is this what you looking for?

#!/usr/bin/perl use strict; my @set = ('A', 'B', 'C', 'D', 'E', 'F'); my $length = 12; my $result; my $last_char; while(length($result) < $length) { my $char = $set[int(rand()*(scalar(@set)-1))]; next if ( $last_char eq $char); $result .= $char; $last_char = $char; } print $result;

Replies are listed 'Best First'.
Re^2: Random data generation.
by almut (Canon) on Jun 26, 2010 at 07:10 UTC

    Your approach could be made to work by simply checking the last two characters:

    my @set = qw( A B C D E F ); my $len = 12; my $result = ''; while (length($result) < $len) { my $char = $set[ rand @set ]; next if substr($result, -2) eq $char x 2; $result .= $char; } print $result;

    Also, there's no need to use an extra variable (like $last_char), as $result already stores all the previous characters.

      Absolutely it was a quick-&-dirty script, probably to much :D, I knew that instead of $last_char I could have used substr(), but premature optimization made me do that.

      Anyway this sort of social coding brought an interesting result

Re^2: Random data generation.
by ikegami (Patriarch) on Jun 26, 2010 at 03:35 UTC

    You made the same error I did originally, you attempted to solve "no repeating characters" rather than "no more than two repeating characters".

    Furthermore, your code never uses the last character of the set.

Re^2: Random data generation.
by BrowserUk (Patriarch) on Jun 26, 2010 at 03:29 UTC

    Not quite. I have to allow two consecutive chars, but not tripled or more...