Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Friday, November 28, 2008

Dealing With "Argument list too long" Errors on Linux and Unix

Hey There,

Here's a question that gets asked a lot (and, consequently, answered a lot ;) on the boards. How do you go about dealing with a situation in which you're trying to take care of some business on your Linux or Unix box and you get stopped with the "Argument list too long" error message? It's probably happened to all of us at some point, but it's fairly simple to avoid, and in more than one way. I'm almost positive, even though I know this stuff, that I'll get that error message again at some point in the future. My mind is a terrible thing ;)

The way I try to keep on top of avoiding that error (which, admittedly, isn't all that terrible, assuming its not a predicating factor in a script - like, you don't have any action is your script that might do something destructive if you don't check for errors) is a basic two-prong approach. First, I'll try to figure out what kind of limitations my system can stand. Secondly, I try to stick to some basic methods that guarantee I won't run into the issue no matter what my system's maximum argument length is. Of course, the second part obviates the first part, but I'm a curious guy (take that whatever way you want ;)

1. How can you figure out your systems command line argument length limitations?

The good news is that there a number of ways (and, most probably, much more than I'm going to list here today):

On almost all Unix and Linux systems you can use getconf to find out the answer very simply, like so (all examples today from OpenBSD 4.4-stable):

host # getconf ARG_MAX
262144


RedHat, SUSE, and BSD Linux (just to name a few) also support figuring this out using the sysctl command (for a more in-depth look at this command, check out our old post on using sysctl to work with kernel tunables on Linux:

host # sysctl kern.argmax
kern.argmax=262144


2. How can you avoid ever getting this error in the first place (not to be used as a substitute for doing error checking in your scripts to "make doubly sure" :)

This boils down to, very basically, using three methods: find, xargs or using your shell's basic looping constructs.

For the purposes of all of our examples below we'll assume that you've done something like:

host # ls *

in a directory, with 564,321 files in it, and have received the titular error.

xargs and find work because, used properly, they can reduce that huge list of file names to 564,321 separate lists of one filename each (that's putting it a little simply, but I'm trying to paint a picture here. And, believe me, painting is a lot harder to do while you're typing than it looks ;)

The find command can be used with the -exec option to iterate through the elements of your ls output, like so:

host # find /that/directory -exec ls {} \;

The xargs command will pretty much do the same thing. Some common wisdom (which doesn't work) is to do this:

host # echo /that/directory/*|xargs ls

however this will still give you the error, unless your version of echo can subvert the OS globbing rules and bypass the ARG_MAX without error.

The only real reason to use xargs to get around this issue is if you run into a situation more complicated than find's -exec flag can deal with. This situation doesn't apply, in that respect, so the following solution is, admittedly redundant and overcomplicated:

find /that/directory|xargs ls

Thirdly, you can use shell while looping to get around the error, again using find to make sure you don't get dinged by the maximum argument length error:

find /that/directory|while read x
do
ls $x
done


Yee-hah :)

Of course, this discourse has been limited to the basics of the shell and one particular situation. If you use Perl, tcl or any other language (under any number of situations) your options will multiply. As with anything else in Linux or Unix, the possible solutions are, to a large degree, limited only to your imagination.

With these little fires lit, go on out there and (to use a dangerous colloquialism) "burn that mother down" ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, September 17, 2008

Revamped Perl Script To More Evenly Distribute Number Pool Match Odds

Hey There,

It's been noted (and I know that it's true) that the spread-system used in the last portion of our Perl script (posted yesterday in our entry regarding maximizing guaranteed matches) was somewhat uneven. The end result, of course, being that your given set-numbers from pool-numbers (3 from 5, 4 from 6, etc) guaranteed that the sets would be included in the generated pools, but (as was noticed by a few people, including myself) the downside (?) ends up being that the front-numbers are more heavily weighted. That is to say that, given a situation where you've got 6 balls drawn, you want to guarantee matches of 3 and you're using a number pool of 8 different numbers (1, 2, 3, 4, 5, 6, 7 and 8 - for example), the first 3 return a higher percentage of the time than the numbers at the other end of the spectrum.

I actually chose to go with this sort of distribution for a particular reason. Well, reasoning, anyway. My reasoning was this: If I rewrite the distribution so that it ends up being more "fair" (The best I could get was a somewhat even distribution that would guarantee any given match set would come up only once or twice), this would probably seem like a better deal, since the odds are "spread out." This is where I, possibly, view things a little bit differently. In our original setup, even though the front numbers are more heavily weighted, the end numbers are guaranteed to contain match sets that all come up at least once or twice. Really, you've got the same thing as the more "fair" method, except for two strong distinctions (aside from the fact that the distributions are unequal in comparative outcomes):

1. In the "fair" distribution, your end number matched-sets have approximately the same odds of returning as they do in the "unfair" distribution. In the "fair" distribution, your end numbers tend to go back and forth between 1 and 2 match-sets guaranteed. In the "unfair" distribution, your end numbers are almost always going to be only 1 match set guaranteed. In neither case should you ever be getting back 0 match sets.

2. In the "fair" distribution, your front number matched-sets have the same odds of returning as your end number matched sets (1, and no more than 2 times guaranteed). In the "unfair" distribution, you'll find several match sets that will return matched sets over 10 times, and then a few more at 9 and some more at 8, a good amount of 4's and 3's and then down to 1's. Basically, your front numbers will be weighted to match not "more often," but "more heavily" if they do hit.

The heavy distribution differential can be easily drawn out, like this (using currency as the currency ;):

a. Front numbers.

1. Fair distribution: Matched set 123 is drawn. We match it twice. Each payout on a matched set it 5 dollars. We've made 10 dollars.
2. Unfair distribution: Matched set 123 is drawn. We match it 11 times. Each payout on a matched set is 5 dollars. We've made 55 dollars.

b. End numbers

1. Fair distribution: Matched set 789 is drawn. We may match it twice (rather than just once). Each payout on a matched set it 5 dollars. We've made 10 dollars.
2. Unfair distribution: Matched set 789 is drawn. We match it once. Each payout on a matched set it 5 dollars. We've made 5 dollars.

So, yes, I have to agree that a difference does exist (and would actually love to find the most economic way to make both ends of the distribution weigh in at 8 to 11 returns without having to run up too many combinations (At a certain point your expenses outweigh your gains... not to mention that those gains are only "possible" and not real until you, maybe, get lucky ;)

Although we went over this previously, I'll repost some data, with slight variations, so that the full code for both the "fair" and "unfair" distributions are covered.

Enjoy :)



FAIR:


@ball_draw_pool = qw(12345 12346 12347 12348 12356 12357 12358 12367 12368 12378 12456 12457 12458 12467 12468 12478 12567 12568 12578 12678 13456 13457 13458 13467 13468 13478 13567 13568 13578 13678 14567 14568 14578 14678 15678 23456 23457 23458 23467 23468 23478 23567 23568 23578 23678 24567 24568 24578 24678 25678 34567 34568 34578 34678 35678 45678);
@rev_ball_draw_pool = qw(45678 35678 34678 34578 34568 34567 25678 24678 24578 24568 24567 23678 23578 23568 23567 23478 23468 23467 23458 23457 23456 15678 14678 14578 14568 14567 13678 13578 13568 13567 13478 13468 13467 13458 13457 13456 12678 12578 12568 12567 12478 12468 12467 12458 12457 12456 12378 12368 12367 12358 12357 12356 12348 12347 12346 12345);

@ball_trap_pool = qw(123 124 125 126 127 128 134 135 136 137 138 145 146 147 148 156 157 158 167 168 178 234 235 236 237 238 245 246 247 248 256 257 258 267 268 278 345 346 347 348 356 357 358 367 368 378 456 457 458 467 468 478 567 568 578
678);

foreach $smaller (@ball_trap_pool) {
@smaller = split("",$smaller);
foreach $larger (@ball_draw_pool) {
print "$larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2]\n";
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}
foreach $smaller (@ball_trap_pool) {
@smaller = split("",$smaller);
foreach $larger (@rev_ball_draw_pool) {
print "$larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2]\n";
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}
$counter = 1;
foreach $key (sort keys %total_pool ) {
$total_poolkey = length $total_pool{$key};
if ( $total_poolkey <= 6 ) {
next;
}
print "Game $counter: $key -- $total_pool{$key}\n";
$counter++;
}



UNFAIR


@ball_draw_pool = qw(12345 12346 12347 12348 12356 12357 12358 12367 12368 12378 12456 12457 12458 12467 12468 12478 12567 12568 12578 12678 13456 13457 13458 13467 13468 13478 13567 13568 13578 13678 14567 14568 14578 14678 15678 23456 23457 23458 23467 23468 23478 23567 23568 23578 23678 24567 24568 24578 24678 25678 34567 34568 34578 34678 35678 45678);

@ball_trap_pool = qw(123 124 125 126 127 128 134 135 136 137 138 145 146 147 148 156 157 158 167 168 178 234 235 236 237 238 245 246 247 248 256 257 258 267 268 278 345 346 347 348 356 357 358 367 368 378 456 457 458 467 468 478 567 568 578 678);

foreach $smaller (@ball_trap_pool) {
@smaller = split("",$smaller);
foreach $larger (@ball_draw_pool) {
print "$larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2]\n";
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}
$counter = 1;
foreach $key (sort keys %total_pool ) {
$total_poolkey = length $total_pool{$key};
if ( $total_poolkey <= 6 ) {
next;
}
print "Game $counter: $key -- $total_pool{$key}\n";
$counter++;
}


, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, September 16, 2008

Perl Script To Maximize Guaranteed Combinations Within Fixed Lists

Hey there,

Breaking tradition (or continuing it, depending on how often you read this blog ;) we're going to have part 2 of yesterday's two-parter tomorrow and put up our final Perl script to find the maximum guaranteed number sets, or lists, within larger number pools. There's not too much else to explain about it, but we will lay out this road map, so that you can see (or possibly revisit or avoid ;) all of the different topics we covered that are included in this script and/or are directly relevant (kind of a list of directions to this post and its attached script).

In order to get to this script, we've tackled:

1. Number Pools And Guaranteed Matches
2. Permuting Lists and Strings With Perl
3. Sorting Lists And Removing Duplicates With Perl
4. Unique Sorting Of Lists Within Lists Within Lists
5. Determining The Maximum Amount Of Pool Sets In Any Number Pool
6. Finding Overlapping Matches Using Lookahead Assertions
7. Evaluating Number Grids
8. Maximizing Number Set Probability Within Number Pools


And, so, without further ado, the culmination of all that effort (okay, that's a bit of a stretch... how about, the amalgamation of all those different concepts ;) - A simple Perl script that gets all its input interactively, so it can be run very simply, like so (sample run):

host # ./wheel.pl
Highest Number: 39
Number Of Balls Drawn: 5
How Many Numbers To Trap: 3
Enter your numbers
separated by space character : 1 2 3 4 5 6 7 19


Highest Number 39
Balls Drawn 5
How Many Numbers To Trap: 3
Actual Numbers To Seed: 1 2 3 4 5 6 7 19
Running 4 phase permute...


Game 1: 1 2 3 4 19
Game 2: 1 2 3 4 5
Game 3: 1 2 3 4 6
Game 4: 1 2 3 4 7
Game 5: 1 2 3 5 19
Game 6: 1 2 3 5 6
Game 7: 1 2 3 5 7
Game 8: 1 2 3 6 19
Game 9: 1 2 3 6 7
Game 10: 1 2 3 7 19
Game 11: 1 2 4 5 19
Game 12: 1 2 4 5 6
Game 13: 1 2 4 5 7
Game 14: 1 2 4 6 19
Game 15: 1 2 4 6 7
Game 16: 1 2 4 7 19
Game 17: 1 2 5 6 19
Game 18: 1 2 5 6 7
Game 19: 1 2 5 7 19
Game 20: 1 2 6 7 19

Output saved in file: output.1_2_3_4_5_6_7_19.091508.6504


Again, this script isn't meant to used for gambling purposes, although it could be. We only chose this scenario as so many facets of our state's lottery relate directly to the concepts we've been going over for the past 2 weeks and it made it fun for the author :)

In all seriousness, if you have a gambling problem (cards, roulette, lottery, whatever) call 1-800-GAM-BLER or visit 800gambler.org and get some help. Like pretty much everything, the lottery is only fun if it's not hurting you! And, oh yes, if it helps, this number picker does not increase the likelihood that any of the numbers it picks will match any random drawing. Luck, and however many other digits are involved in the number pool, make this a losing proposition, at best. To prove this, I ran a test against the Illinois Lottery's past-drawing numbers for 2008 and found that, for my modest investment of $5,040, I would have made $764 in return. In other words, unless you're lucky, this number selection system will only guarantee that you'll lose more than you gain. Like all the disclaimers all say; it's for entertainment purposes only!

Okay, we've done our part. The PSA is over. Enjoy the script (it, and its parts, can be useful for a variety of other purposes) :)

NOTE: The improved permutation subroutine was found online in an excerpt from the Perl Cookbook, by Tom Christiansen and Nathan Torkington - an excellent read :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# wheel.pl
# TODO: out of order numseeds do not make correct output
#
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

print "Highest Number: ";
chomp($highest_number=<STDIN>);

print "Number Of Balls Drawn: ";
chomp($num_balls=<STDIN>);
$array_num_balls=$num_balls - 1;

print "How Many Numbers To Trap: ";
chomp($num_trap=<STDIN>);
$array_num_trap=$num_trap - 1;

print "Enter your numbers\n";
print "separated by space character : ";
chomp($num_seeds=<STDIN>);
$num_seeds =~ s/ /,/g;
@number_seeds = split(/,/, $num_seeds);
$number_seeds = @number_seeds;

if ( $number_balls > $num_seeds ) {
print "--------------------------\n";
print "Your picks $num_seeds\n";
print "is larger than $num_balls nums picked\n";
print "Try again!\n";
print "--------------------------\n";
exit(1);
}
foreach $unique_num (@number_seeds) {
if ($seen{$unique_num}++) {
print "--------------------------\n";
print "Your Number set $num_seeds\n";
print "contains duplicate numbers! Try again!\n";
print "--------------------------\n";
exit(2);
} elsif ( $unique_num > $highest_number ) {
print "--------------------------\n";
print "Your Number set $num_seeds contains\n";
print "a number $unique_num greater than\n";
print "your highest number value: ${highest_number}. Try again!\n";
print "--------------------------\n";
exit(3);
}
}

print "\n\n";
print "Highest Number $highest_number\n";
print "Balls Drawn $num_balls\n";
print "How Many Numbers To Trap: $num_trap\n";
print "Actual Numbers To Seed: @number_seeds\n";

$|=1;

@sperms = permoot(@number_seeds);
print "Running 4 phase permute...\n";

$useless_counter=0;
foreach $unordered (@sperms) {
$unordered =~ s/\s/,/g;
@unsorted = split(/,/, $unordered);
@crazy = @unsorted[0 .. $array_num_balls];
$unsorted = join(" ", @crazy);
@temparray = split(" ", $unsorted);
@temparray = sort { $a <=> $b } (@temparray);
unshift(@sorted_perms, "@temparray");
}

$unik="0";
$last_unik="0";
$useless_counter=0;
foreach $s_p (@sorted_perms) {
@unik = split(" ", $s_p);
@unik = sort(@unik);
$seen2{$s_p}++;
if ( $seen2{$s_p} >= 2 ) {
next;
}
if ( $unik == $last_unik ) {
unshift(@ball_draw_pool,"$s_p");
@last_unik = @unik;
$last_unik++;
} elsif ( @unik == @last_unik ) {
$total = @unik;
$zero = $nope = 0;
while ( $zero < $total ) {
if ( "$unik[$zero]" ne "$last_unik[$zero]" ) {
$nope = 1;
last;
} else {
$zero++;
}
}
if ( $nope ) {
unshift(@ball_draw_pool,"$s_p");
@last_unik = @unik;
}
}
}


$useless_counter=0;
foreach $unordered (@sperms) {
$unordered =~ s/\s/,/g;
@unsorted = split(/,/, $unordered);
@crazy = @unsorted[0 .. $array_num_trap];
$unsorted = join(" ", @crazy);
@temparray = split(" ", $unsorted);
@temparray = sort { $a <=> $b } (@temparray);
unshift(@sorted_perms, "@temparray");
}

$useless_counter=0;
$unik="0";
$last_unik="0";
foreach $s_p (@sorted_perms) {
@unik = split(" ", $s_p);
@unik = sort(@unik);
$seen2{$s_p}++;
if ( $seen2{$s_p} >= 2 ) {
next;
}
if ( $unik == $last_unik ) {
unshift(@ball_trap_pool,"$s_p");
@last_unik = @unik;
$last_unik++;
} elsif ( @unik == @last_unik ) {
$total = @unik;
$zero = $nope = 0;
while ( $zero < $total ) {
if ( "$unik[$zero]" ne "$last_unik[$zero]" ) {
$nope = 1;
last;
} else {
$zero++;
}
}
if ( $nope ) {
unshift(@ball_trap_pool,"$s_p");
@last_unik = @unik;
}
}
}
print "\n";

foreach $smaller (@ball_trap_pool) {
@smaller = split(" ",$smaller);
foreach $larger (@ball_draw_pool) {
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}

chomp($date=`date +%m%d%y`);
$var = $$;
$con_num_seeds = $num_seeds;
$con_num_seeds =~ s/,/_/g;
$lfile_name = "output.${con_num_seeds}.${date}.${var}";
print "\n";
open(LFILE, ">$lfile_name") or die "Cannot open FILE";
print LFILE "Output File output.${con_num_seeds}.${var}\n";
print LFILE "--------------------------------\n";
print LFILE "$highest_number Ball Selection - Pick $num_balls - Trap $num_trap\n";
print LFILE "Seed Numbers: $number_seeds\n";
print LFILE "--------------------------------\n";

$counter = 1;
foreach $key (sort keys %total_pool ) {
print "Game $counter: $key\n";
$|=1;
print LFILE "Game $counter: $key\n";
$counter++;
}
close(LFILE);
print "\nOutput saved in file: $lfile_name\n";

sub permoot {
#
# The improved permutation subroutine was found online in an excerpt from the Perl Cookbook, by Tom Christiansen and Nathan Torkington
@DATA = @_;
foreach ("@DATA") {
my @data = split;
my $num_permutations = factorial(scalar @data);
for (my $i=0; $i < $num_permutations; $i++) {
@permutation = @data[n2perm($i, $#data)];
@sortperms = join(" ", @permutation);
push(@sperms, "@sortperms" );
}
}
return @sperms;

BEGIN {
my @fact = (1);
sub factorial($) {
my $n = shift;
return $fact[$n] if defined $fact[$n];
$fact[$n] = $n * factorial($n - 1);
}
}

sub n2pat {
my $i = 1;
my $N = shift;
my $len = shift;
my @pat;
while ($i <= $len + 1) {
push @pat, $N % $i;
$N = int($N/$i);
$i++;
}
return @pat;
}

sub pat2perm {
my @pat = @_;
my @source = (0 .. $#pat);
my @perm;
push @perm, splice(@source, (pop @pat), 1) while @pat;
return @perm;
}

sub n2perm {
pat2perm(n2pat(@_));
}
}


, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Friday, September 12, 2008

Maximizing Set Match Probability Using Perl On Linux Or Unix

Hey There,

As promised (I think ;), we're back today with some code (not the entire script that encompasses the last 2 weeks worth of posts, of course) to grind out the final concept in this string of surprisingly wide-ranging topics all centered around the concepts of number pools and guaranteed matches. We've covered a lot of different aspects of mathematics, regular expression matching, etc just moving toward our Objective. So, aside from the link to our initial introductory number pools post, we'll just suffice it so say that every post since then (excluding the weekend humour) has been directly related to this mini-series' stated Objective. I'd love to label this paragraph with a whole slew of hyperlinks, but I'm going to pretend you're like me and don't want to get zapped to some other page every 5 seconds just because your finger twitches while you're reading this column ;) You should be able to access any of the older posts via the side menu or by just clicking on the "older posts" link at the bottom of the post itself.

BTW, thanks to an anonymous reader who pointed out that I accidentally goofed when I was manually typing out the distribution of number sets in yesterday's post. The line, in the first grid, that read:

12478 124 127 128 147 148 178 247 248 258 358
should have read:

12478 124 127 128 147 148 178 247 248 278 478

I got sloppy while I was doing the manual typing of the 3-digit strings and accidentally re-typed the last 2 3-digit sets from the previous line. Hopefully, I've fixed it by the time you read this ;)

As I worked out this last part (the brain teaser being directly related here), I found that, although I could squeeze all 3-digit combinations of our 8 numbers into 8 5-digit lists of numbers, the ratio of match to payoff was fairly low (depends on what you're looking for, I suppose) as laid out in the statistics below:

FORMAT: List of 8 5-Digit Sets

12346 12358 12478 13678 14567 23457 25678 34568

FORMAT: Approx % of set pool == # of times matched == # of sets == list of 3-digit matches
41% == 2 == 23 == 123 124 128 136 138 146 147 167 178 234 235 247 257 258 278 345 346 358 368 456 457 567 568
59% == 1 == 33 == 125 126 127 134 135 137 145 148 156 157 158 168 236 237 238 245 246 248 256 267 268 347 348 356 357 367 378 458 467 468 478 578 678


Of course, the idea here is to get the maximum amount of unique matches in a 5-digit set, but it would be nice to have more than a single or double return on each hit (and a greater weighted percentage on the 3-digit sets that match more than once in different lines on the grid), so that the statistical difference is more in your favour (Note: This post is not about the Lottery. We neither recommend nor discourage you from gambling. It's not our place. If you must gamble, only bet what you can afford to lose. That's just good advice all around ;) This is pretty bad, with a 41%/59% ratio of above-single-match-hits vs. single-match-hits

If we took the following Perl code (runnable on any Linux or Unix distro that supports Perl 5.6 and up -- the behaviour of hashes changed slightly around the 5.6 release), which iterates through the 56 5-digit lists we started getting into on our posts on sorting Perl lists and finding the maximum number of pool sets using binomial coefficient theory. The 5-digit list while-loop is wrapped in another while-loop that iterates through all the possible 3-digit sets (since we want to match 3 digits minimum) and populates a hash with keys and values to determine what lists (in our 56 member 5-digit set list) are viable for matching all possible 3-digit matches and returning the highest probable yield. You'll notice that the output is a little skewed toward the lower numbers due to the matching algorithm:

foreach $smaller (@tri_set_pool) {
@smaller = split("",$smaller);
foreach $larger (@five_digit_pool) {
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger
=~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}
$counter = 1;
foreach $key (sort keys %total_pool ) {
print "Game $counter: $key\n";
$counter++;
}


Note that this code would give us "20" 5-digit match strings (up from our original 8), but a disproportionately better chance of a larger return (closer to the beginning, as noted above, which could be counted as a flaw ;)

FORMAT: List of 20 5-Digit Sets
12345 12346 12347 12348 12356 12357 12358 12367 12368 12378 12456 12457 12458 12467 12468 12478 12567 12568 12578 12678

FORMAT: Approx % of set pool == # of times matched == # of sets == list of 3-digit matches
1% == 11 == 1 == 125
6% == 10 == 3 == 123 124 128
1% == 8 == 1 == 127
1 % == 5 == 1 == 126
50% == 4 == 28 == 134 135 136 137 138 145 146 147 148 156 157 158 178 234 235 236 237 238 245 246 247 248 256 257 258 267 268 278
4% == 3 == 2 == 167 168
37% == 1 == 20 == 345 346 347 348 356 357 358 367 368 378 456 457 458 467 468 478 567 568 578 678


So, that's obviously a much better distribution of multiple 3-digit match occurrences (i.e., if you matched 123, you'd match it 10 times!) This tips thing back to good with a 63%/37% ratio of above-single-match-hits vs. single-match-hits.

Finally, one simple addition of a reversed 5-digit list array in the code, attacking the 3-digit matches against both and stripping off all 5-digit numbers that only contain a single match (note that this does not mean that no single match occurrences were found for any given 3-digit list!), gives us the best (as in most even) odds so far, although possibly not the best return on a win (statistics below the additional code following - pardon the cheap editor tricks ;) - This is another 20 list return, but with favorable-match odds that make it worth going over the modest 8-list list we started out with. Note, also, that this revision takes out the humungous skew between beginning and end (from 11 matches to 1 match) that our last revision created:

@five_digit_pool = qw(12345 12346 12347 12348 12356 12357 12358 12367 12368 12378 12456 12457 12458 12467 12468 12478 12567 12568 12578 12678 13456 13457 13458 13467 13468 13478 13567 13568 13578 13678 14567 14568 14578 14678 15678 23456 23457 23458 23467 23468 23478 23567 23568 23578 23678 24567 24568 24578 24678 25678 34567 34568 34578 34678 35678 45678);
@rev_five_digit_pool = qw(45678 35678 34678 34578 34568 34567 25678 24678 24578 24568 24567 23678 23578 23568 23567 23478 23468 23467 23458 23457 23456 15678 14678 14578 14568 14567 13678 13578 13568 13567 13478 13468 13467 13458 13457 13456 12678 12578 12568 12567 12478 12468 12467 12458 12457 12456 12378 12368 12367 12358 12357 12356 12348 12347 12346 12345);
@tri_set_pool = qw(123 124 125 126 127 128 134 135 136 137 138 145 146 147 148 156 157 158 167 168 178 234 235 236 237 238 245 246 247 248 256 257 258 267 268 278 345 346 347 348 356 357 358 367 368 378 456 457 458 467 468 478 567 568 578 678);

foreach $smaller (@tri_set_pool) {
@smaller = split("",$smaller);
foreach $larger (@five_digit_pool) {
print "$larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2]\n";
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}
foreach $smaller (@tri_set_pool) {
@smaller = split("",$smaller);
foreach $larger (@rev_five_digit_pool) {
print "$larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2]\n";
if ( $larger =~ $smaller[0] && $larger =~ $smaller[1] && $larger =~ $smaller[2] ) {
$total_pool{$larger} .= $smaller;
last;
$|=1;
}
}
}
$counter = 1;
foreach $key (sort keys %total_pool ) {
$total_poolkey = length $total_pool{$key};
if ( $total_poolkey <= 6 ) {
next;
}
print "$counter: $key -- $total_pool{$key}\n";
$counter++;
}


FORMAT: List of 20 5-Digit Sets
12345 12346 12347 12348 12356 12357 12358 12367 12368 12378 12678 13678 14678 15678 23678 24678 25678 34678 35678 45678

FORMAT: Approx % of set pool == # of times matched == # of sets == list of 3-digit matches
64% == 2 == 36 == 123 126 127 137 138 146 147 148 156 157 158 167 168 178 236 237 238 246 247 248 256 257 258 267 268 278 346 347 348 356 357 358 367 368 378 678
36% == 1 == 20 == 124 125 128 134 135 136 145 234 235 245 345 456 457 458 467 468 478 567 568 578


So, with this 64%/36% ratio of above-single-match-hits vs. single-match-hits, we've got about the same statistical odds as our last rendition. This version should get you above a single-match more often (since the other leaves you in single-match territory on all sets starting with 3 and up), but it does dampen your possible return (you'll never hit a 3-digit match that comes up more than twice).

Depending upon how you're using this sort of probabilistic determination, one version may appeal more to you than the other (And, again, if you use this to spread lottery picks, you still stand a really good chance of not having any of the numbers in your set match what they pick out of the air. I look at the lottery as straight 50% odds. They'll either pick my numbers or they won't, no matter how "overdue" any combinations may be (Believe me, if you live in Chicago and follow the Cubs, you can witness the fallacy of the "overdue win" in real-life every year ;) It's all random and the future can't be inferred from past events ...unless your local lottery is crooked ;)

Anyway, I hope you all have a great weekend, and I'll be sure to pop the cleaned up (and all put together) version of the script, that encompasses the last 2 weeks worth of post topics, as soon as I can next week. Here's hoping I can find you some more funny stuff for the weekend. I promise: No number jokes ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, September 11, 2008

Evaluating Number Grids Using Perl On Linux Or Unix

Hey There,

And, we're back from an evening of teasing our brains. I was actually quite cruel to mine. Hopefully, it will forgive me ;)

Here's hoping everyone's having an enjoyable day at work (or, even better, an enjoyable drink on the beach :). I'm currently wading through a sea of bureaucracy the complexity of which demands to be taken in with nothing less than total awe. The term Byzantine been taken to another level of meaning for me. It's always an interesting thing in life when you realize that, just the other day, you thought you had it all figured out ;) But, on the flipside, managers and directors need to manage and direct, so I don't begrudge them their duties, even if they seem to be manufactured to a certain degree. I'll gladly fill out a few forms if it'll keep somebody's family in food and clothing with a roof over their heads. My nagging inner-voices are fickle, selfish, somewhat pedestrian and completely unrealistic. It's a good thing I realized this about myself so many years ago. Bless my mother and father for not giving up on my sorry tween-age behind. Having a few kids of my own, I realize ( a little more with each passing day ) why my parents kept me around and why, every once and a while, they wanted to kill me ;)

Anyway, this nightmare of form stamping, filing and dull aching headaches (Think Terry Gilliam's Brazil except not in the future and with nice bright halogen lighting to offset the bizarre floral-patterned non-threatening beige cubicle farms ;) hasn't given me any time to script out my answer to yesterday's brain teaser. Believe it or not, I actually did the original half on paper and then half in my head. Actually, you'll believe it. When you see it in print, it becomes pretty simple to see the pattern.

Hopefully, you didn't give the brain-teaser too much effort if the answer didn't appear to you quickly. Like I said, I wasted a lot of time looking for suitable number sequences ( golden strings, etc ), but, in the end, found that I could reasonably deduce the most economical 8 out of 56 lists by just looking at them. Admittedly, it's a lot easier to read now that I've grouped them together (looking at all 56 was alternately confusing and just bad for my eyesight in general ;) Actually, a lot of you can probably knock out a quick Perl or shell script for Linux or Unix to deal with the pattern matching and list collecting just from seeing the grid of lists in one place.

The simple answer to the question (without the equation part, which I promise I'll put out as an aside to a post on something else original so you won't have to hear about numbered lists any more after we post the script that takes the last 2 weeks of posts on number pools, probability, binomial theory and , of course, lists and automates them ...at least, until I get sick of stuff other than lists ;) is that these 8 lists combined the most dense and absolutely complete set of all 3 digit lists within my 56 5 digit lists. The list of all 3 digit lists is simple to chart out (even if our list wasn't just "1, 2, 3, 4, 5, 6, 7 ,8)" and is shown below:

123 124 125 126 127 128 134 135 136 137 138 145 146 147 148 156 157 158 167 168 178 234 235 236 237 238 245 246 247 248 256 257 258 267 268 278 345 346 347 348 356 357 358 367 368 378 456 457 458 467 468 478 567 568 578 678


We'll leave the group of 20 lists that make for the most economical group of lists for a 4 digit match alone (same principle), and take a look, again, at the 8 lists which most economically covered every single list within the 3 digit match list above (can I type list again? I think I can... ;) These 8 lists are listed in the format: five-digit-list (space) space-delimited listing of all 3 digit matches covered.

12346 123 124 126 134 136 146 234 236 246 346
12358 123 125 128 135 138 158 235 238 258 358
12478 124 127 128 147 148 178 247 248 278 478
13678 136 137 138 167 168 178 367 368 378 678
14567 145 146 147 156 157 167 456 457 467 567
23457 234 235 237 245 247 257 345 347 357 457
25678 256 257 258 267 268 278 567 568 578 678
34568 345 346 348 356 358 368 456 458 468 568


Now, compare that with the list of 8 random lists, taken from the same group of 56, below, in the same format.

12458 124 125 128 145 148 158 245 248 258 358
12457 124 125 127 145 147 157 245 247 257 457
12456 124 125 126 145 146 156 245 246 256 456
12378 123 127 128 137 138 178 237 238 278 378
45678 456 457 458 467 468 478 567 568 578 678
35678 356 357 358 367 368 378 567 568 578 678
34678 346 347 348 367 368 378 467 468 478 678
34578 345 347 348 357 358 378 457 458 478 578


One thing you'll notice, just by looking, is that every single 3 digit match can be found in the first 8 list set, but not all can be found in the second. As for the reason that my answers always come up identical, this may be a trick of circumstance caused by the numbers themselves. I started my parsing from the 1's up (for all 56 lists in numeric order) and found the 8 identified as being a nice tidy all-encompassing grid "first." And I quote first because I didn't bother to check and see if I could find another one afterward. It (and several others) may exist in the list of 56 lists, even after my conditions for completion are satisfied. In fact, by default, if you use all 56 lists, you're guaranteed the "absolute" best coverage of all 3 digit matches, because you'll be hitting every single one of them (all 56 unique variations of 3 digit lists using the numbers 1 through 8, with no repetition or duplication).

To see what I mean, just check for random 3 digit strings in both matrices (or lists of lists). For instance, see if you can find 134, 135 or 136 in both sets or if they only appear in the top one (the one that's supposed to cover all 56 variations).

Enjoy, and I'll crank out a little script to replicate what I have written on paper and stuck in my head for you in the next post or so. As long as you understand the purpose of the grids (covering all variations of the 56 3 digit lists) it becomes trivial for you to create your own complete lists of lists (from the 56 lists you can make of 5 digit lists spreading over 8 digits) and experience for yourself what it is to understand something and feel somewhat at a loss to adequately explain it ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, September 10, 2008

Brain Teaser: Seemingly Random Number List Selection

Hey there,

We're just about done with this series of somewhat disjointed posts on number pools and guaranteed matches. Hopefully, each post in the series has been somewhat entertaining and far enough removed from the starting post that we kept up some sense of originality. It wasn't too hard (unless we screwed up ;) since there were so many unique concepts to cover within the realm of reaching the Objective of the original post. Please refer back to our post on number pools for definitions of all the major terms and a listing of the Objective (although that definition is repeated in a few other posts along the way).

We're just about at the end of the road, so I thought I'd make today's post a bit of a Brain Teaser. The answer to this is actually pretty interesting and (from my struggling with it) you'll either get it right away or it'll take you a good amount of time (kind of like the M I U Puzzle). I, for one, spent way too much time reading up on number sequences and probability. I'm not an engineering major, so I actually had to reference other materials to decipher the Greek alphabet notation. It was interesting for me (especially the insomniac in me), but not something I'd recommend doing unless you're really into it. One thing I noticed, although this is slightly off topic; when people see you sitting in your easy chair chugging diet Pepsi, popping Diphenhydramine and typing in your terminal window with your lap covered with shreds of paper with interpretive numeric scrawl written all over them, they tend to not ask too many questions. It's a great way to guarantee you'll have the evening to yourself ;)

Anyway; for this post's meat: The brain teaser we have today is pretty straightforward, by way of explanation. Here's the setup:

1. Like we did in our posts on deriving list permutations, sorting lists and sorting lists within lists (not necessarily in that order), we've generated a list of 56 5 digit lists using an 8 digit pool of numbers (1, 2, 3, 4, 5, 6, 7, 8). This list represents all possible permutations of the 8 digit list within 5 digit lists while "absolutely removing duplicates" (i.e. "1, 2, 3, 4, 5" and " 5, 3, 2, 4, 1" would be considered equal and would both be removed). That list of numbers follows here (Note that each line is numbered):

1 1 2 3 4 5
2 1 2 3 4 6
3 1 2 3 4 7
4 1 2 3 4 8
5 1 2 3 5 6
6 1 2 3 5 7
7 1 2 3 5 8
8 1 2 3 6 7
9 1 2 3 6 8
10 1 2 3 7 8
11 1 2 4 5 6
12 1 2 4 5 7
13 1 2 4 5 8
14 1 2 4 6 7
15 1 2 4 6 8
16 1 2 4 7 8
17 1 2 5 6 7
18 1 2 5 6 8
19 1 2 5 7 8
20 1 2 6 7 8
21 1 3 4 5 6
22 1 3 4 5 7
23 1 3 4 5 8
24 1 3 4 6 7
25 1 3 4 6 8
26 1 3 4 7 8
27 1 3 5 6 7
28 1 3 5 6 8
29 1 3 5 7 8
30 1 3 6 7 8
31 1 4 5 6 7
32 1 4 5 6 8
33 1 4 5 7 8
34 1 4 6 7 8
35 1 5 6 7 8
36 2 3 4 5 6
37 2 3 4 5 7
38 2 3 4 5 8
39 2 3 4 6 7
40 2 3 4 6 8
41 2 3 4 7 8
42 2 3 5 6 7
43 2 3 5 6 8
44 2 3 5 7 8
45 2 3 6 7 8
46 2 4 5 6 7
47 2 4 5 6 8
48 2 4 5 7 8
49 2 4 6 7 8
50 2 5 6 7 8
51 3 4 5 6 7
52 3 4 5 6 8
53 3 4 5 7 8
54 3 4 6 7 8
55 3 5 6 7 8
56 4 5 6 7 8


2. Using the technique we looked at in our post on determining maximum sets of lists within pools using binomial coefficients, we've deduced that, since we want to guarantee (within the lists in this list of lists) unique 3 digit combinations, we can do so most economically by selecting 8 of the 5 digit lists from the 56. This is not the exact formula we followed in the noted post (as it showed that the binomial coefficient of 8 over 3 is 56). In fairly loose terms, if we want to maximize the odds that we'll get any given 3 digit list (and not use all 56 lists, which works, but is expensive), we can do so with a minimum of 8 5 digit lists. Those 8 lists follow here:

1 2 3 4 6
1 2 3 5 8
1 2 4 7 8
1 3 6 7 8
1 4 5 6 7
2 3 4 5 7
2 5 6 7 8
3 4 5 6 8


3. Using the numbers from point 1 and 2, above, the following chart shows you at what line (in the list of 5 digit lists) each of the 8 lists we determined would give us the best odds of getting a maximum return on a 3 digit list match up.

2 1 2 3 4 6 1 2 3 4 6
7 1 2 3 5 8 1 2 3 5 8
16 1 2 4 7 8 1 2 4 7 8
30 1 3 6 7 8 1 3 6 7 8
31 1 4 5 6 7 1 4 5 6 7
37 2 3 4 5 7 2 3 4 5 7
50 2 5 6 7 8 2 5 6 7 8
52 3 4 5 6 8 3 4 5 6 8


4. Using the numbers from point 1 and 2, above, the following chart shows you at what line (in the list of 5 digit lists) each of the 20 lists we can also determine would give us the best odds of getting a maximum return on a 4 digit list match (We never covered this, but I just added it to give you some frame of reference if the above 3 points aren't enough - BTW, I generated this list because they weren't enough for me, so no offense intended :)

1 1 2 3 4 5 1 2 3 4 5
8 1 2 3 6 7 1 2 3 6 7
9 1 2 3 6 8 1 2 3 6 8
14 1 2 4 6 7 1 2 4 6 7
15 1 2 4 6 8 1 2 4 6 8
18 1 2 5 6 8 1 2 5 6 8
19 1 2 5 7 8 1 2 5 7 8
21 1 3 4 5 6 1 3 4 5 6
22 1 3 4 5 7 1 3 4 5 7
23 1 3 4 5 8 1 3 4 5 8
26 1 3 4 7 8 1 3 4 7 8
35 1 5 6 7 8 1 5 6 7 8
38 2 3 4 5 8 2 3 4 5 8
39 2 3 4 6 7 2 3 4 6 7
42 2 3 5 6 7 2 3 5 6 7
45 2 3 6 7 8 2 3 6 7 8
46 2 4 5 6 7 2 4 5 6 7
49 2 4 6 7 8 2 4 6 7 8
52 3 4 5 6 8 3 4 5 6 8
53 3 4 5 7 8 3 4 5 7 8


Now, here's the fun part. Considering that:

a) no matter how many times we do this using the exact parameters, the results (the lists and the placement of the 8 most economical choices) are totally consistent.
b) If we change anything (like make our list of "1, 2, 3, 4, 5, 6, 7, 8" into "1, 4, 3, 2, 5, 6, 7, 8") about our 8 digit list (assuming that we don't resort everything to numeric order before generating our 8 best 5 digit lists), the outcome will be affected in that the 8 lists will not only contain different numerals, but also end up matching at different numbered locations on master list of 56 lists.

Considering that, how am I determining where to place my 8 5 digit lists in relation to my 56 list list. Or, in other terms, how am I picking the 8 5 digit lists I feel will give me the best odds of matching a 3 digit combination of any 3 unique digits from the 8 digit list used to seed these 5 digit selections?

Think about it, but not too hard. This is only fun if you're having fun with it. If it starts to upset you, watch something violent, yet satisfying (like a good revenge flick), on television and get some sleep ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Friday, September 5, 2008

Unique Sorting Of Lists And Lists Of Lists With Perl For Linux Or Unix

Hey There,

Yesterdays post on sorting Perl lists and removing duplicates did end up being a bit heavy at the end, as I feared. I received my fair share of "here's how you can do it better" emails, which (although I'm not trying to do my most succinct and efficient work here) I always appreciate. In all seriousness, I really do enjoy getting different perspectives on methods and practices put up on this blog. I'm always looking to better my own skill-set, so keep the free advice coming. I'll probably devote an entire future post to the suggestions I've gotten regarding this (with attribution to the contributor's, of course) as the myriad means to an end are quite diverse, clever and interesting. And, yes, we do print contrary opinions as well, but they have to be logical arguments or, at the very least, scathing put-downs that make sense within the given context. If you just write us to tell us to go #### ourselves, we may take you up on that (it can get lonely out here in cyberspace ;) but it won't ever end up as a comment attached to a post.

For today, we're going to break down two areas which generated the most response (mostly because, although I tried, the code just wasn't self-explanatory enough). Sometimes it's actually harder to try and explain something you already do by rote than to explain something you're in the process of picking up on yourself. The two examples for today fall into the former category. My blinders made me think that the code I put out would be easily digested, but (after reading a few comments) I agree that perhaps I was a bit presumptuous. But, life goes on and we learn from our mistakes (even if we just keep making them over and over again ;)

The basic questions, and a bit more detailed of a breakdown:

Q. Why the klunky foreach block at the top of the attached code? Shouldn't sorting be simpler?

A. Actually, sorting data is simpler, but, in this case we were dealing with sorting on two levels, which may not have been readily apparent. The @s_perms array that gets returned from the public domain "permute" subroutine actually contains multiple scalar pseudo-lists. That is to say that $s_perms[0] could be equal to "1 3 2 4 5." While this resembles our lists that we want to sort, it is actually just one variable made up of numbers and spaces. So, for each member of the @s_perms array, we did the following:

1. First we split the scalar variable into an actual array, so that "1 3 2 4 5" became @temparray, with values of 0 through 4 ($temparray[0] = 1, $temparray[1] = 3, etc), like so:

@temparray = split(" ", $unsorted);

2. Then, we sorted that newly created array. The reason we sorted each value returned by the "permute" subroutine was so that each value would be in order. When we do it this way (below), every @temparray list ends up with the members, in order, of "1 2 3 4 5." If we had just called a numeric sort ( $a <=> $b ) on @s_perms, it would have sorted all of the individual lists using their initial numeric value as the sort index. To put it more simply, assuming @s_perms contained only 3 scalar values of:

"1 2 3 5 4"
"4 5 3 2 1"
"1 5 4 2 3"


a straight-up sort on @s_perms would generate a sorted list like this (in order, top to bottom):

"1 2 3 5 4" <-- All 3 scalar values ("1 2 3 5 4," "1 5 4 2 3," etc, being considered single entities) are being sorted as individual elements within an array.
"1 5 4 2 3"
"4 5 3 2 1"


Since our Objective states that all permutations of the same lists of values should be considered equal, the straight-up sort wouldn't make it easier (later) to determine if any, or all, of the 3 scalars were representative of unique or duplicate lists. When we break down each scalar value within the @s_perms array and split that scalar into a temporary array (@temparray) and then do the sort on that, only the values in @temparray get sorted. That is to say that "1 2 3 5 4" gets sorted, and then "1 5 4 2 3," etc. This results in our generating a sorted list like this:

"1 2 3 4 5" <-- Each scalar is split into an array with the "@temparray = split(" ", $unsorted);" statement from above and that array is sorted independently of each succeeding or preceding one!
"1 2 3 4 5"
"1 2 3 4 5"


3. Then we get to the step that caused some folks to wonder why it wasn't the first action taken:

@temparray = sort { $a <=> $b } (@temparray);

Now, we're sorting just like we would have in step 2 (if we did it this way), except we're sorting array variables that have already had their "insides" sorted. Having a list of array elements like:

"1 2 3 4 5"
"1 2 3 4 5"
"1 2 3 4 5"


makes it a lot easier to weed out the duplicates later.

4. Then, we add that array (of individually, and universally, sorted arrays) to the right hand side of the @sorted_perms array, which we use further on in the script.

unshift(@sorted_perms, "@temparray");

Simple enough ;) Hopefully, I'm not making this any worse for the folks out there who wrote in ;) Seriously, though, I do hope this explanation helps out at least a little.

The second question was just as valid:

Q. What's with the @unik and @last_unik variables. I understand that you're comparing arrays, but what are you doing in your "elsif" equality test?

A. This is a great question, because, on its face it seems that all we would have to do is check if the two arrays are equal and that would be that. Unfortunately, this practice has one fatal flaw (and, curiously enough, the behaviour is the same if you use the numeric or alpha comparison operators!) The basic test of the "entire array" actually only considers quantity of indices as indicators of uniqueness. For instance, this small script:

#!/usr/bin/perl

@bob = qw (1 2 3 4 5);
@joe = qw (1 3 2 5 4);

if ( @bob == @joe ) {
print "BOB and JOE are == Equal\n";
}

if ( @bob eq @joe ) {
print "BOB and JOE are EQ Equal\n";
}


produces this output:

host #./test
BOB and JOE are == Equal
BOB and JOE are EQ Equal


Since the basic equality operators only count indices to compare, I used that as the "outside loop" test. I figured, if the two arrays didn't have the same number of members, they couldn't possibly be equal, and we'd move on to the next loop without doing all the extra work. However, if the index counts match, then we need to check and see if the "content" of the arrays are exactly equal. So, if:

} elsif ( @unik == @last_unik ) {

returns true (both @unik and @last_unik have the same number of members), we'll go check them out index by index. I started out by setting three variables, just for ease of reading and to establish controls.

1. $total = @unik; <-- This populates the $total scalar variable with the length of the @unik array

2. $zero = $nope = 0 < -- This is just simple shorthand for assigning the variables $zero and $nope the value of "0."

3. Then, I iterated through both arrays at the same time (At this point in the program, every array has been sorted, so they should all be "1 2 3 4 5"). This was accomplished by a simple while loop that incremented the $zero variable (which represented the index of the @unik and @last_unik arrays) and compared those index values with each other. If, at any point, an index in @unik didn't match the corresponding index in @last_unik, the variable $nope was set to 1 and the while loop was broken (no sense calculating the rest of the index values, since we just hit a difference and the two arrays can't be identical anymore). Every time the corresponding values matched, the value of $zero was incremented by 1, and the process repeated, until the value of $zero reached the value of $total (the length of the @unik array:

while ( $zero < $total ) {
if ( "$unik[$zero]" ne "$last_unik[$zero]" ) {
$nope = 1;
last;
} else {
$zero++;
}
}


4. The block of code following that would only execute if we had found a difference between the two arrays, and the value of $nope was set to 1. This would be an indicator that @unik was a different (unique) array than the previous one and should be printed out. Then (and this shows up more than once), after the value is printed, I set @last_unik to be equal to @unik (Note that the = "assignment" operator is used here, rather than the == "comparative" operator). This sets us up to test the next @unik against @last_unik (which was @unik in the previous iteration) and easily be able to tell if that next array is just more of the same. This is set elsewhere within the larger construct, as well (on a different condition).

if ( $nope ) {
print "$s_p";
@last_unik = @unik;
}


5. As a side note for this piece of code, again, it was written to be simple to follow and works on the assumption that we've sorted the individual arrays numerically (see the first question at the beginning of this book ...I mean, post ;) and they are all the same. For instance, if the array @sorted_perms contained @array1, @array2 and @array3, and they were populated like this:

@array1 = "1 2 3"
@array2 = "3 2 1"
@array3 = "1 2 3"


You would not get a return of 2 values ("123" and "321") since we're not maintaining state in any other way. Since array's 1, 2 and 3 are processed in order and different from each other (in order, one after the other), they would all show up as unique (and be printed) in our example. If we wanted to make sure that we only got "123" and "321" back, we'd have to implement another method to double check that we weren't repeating ourselves. Of course, that would add another level of complexity, and I'm trying to keep this as simple as possible, but, since you asked, you can easily avoid duplicate unique values (??? Can those really exist in a sane universe? ;), you can do this most simply (I think), using grep, and Perl hashes, in the right place, like in the pseudo-code below:

foreach $bogus_value (@bogus_array) {
unless ($seen{$bogus_value}) {
$seen{$item} = 1;
unshift(@bogus_array, $bogus_value);
}
}


and, that would guarantee you that no "duplicate unique" values would appear in your output :)

That's about all I can sneak in at lunch here today ;) Until next time.
Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, September 4, 2008

Sorting Perl Lists And Removing Duplicates On Linux Or Unix

Hey there,

This may be the first time I've run a series of posts where the topic was different every step of the way. That's a good thing, because I get just as bored as anyone else reading about the same thing over and over ;) So, following in the footsteps of our posts on Number Pools And Guaranteed Combinations Within Fixed Lists and Perl List Permutations, we'll move straight ahead to the next logical step, which is almost an entirely different subject altogether. I will however, reiterate (repeat again... sorry, one of my idiosyncrasies ;) our Objective in this whole exercise (Skip to the next paragraph if you feel I've done this sentence to death ;) : Given a Number Pool of "x through y," create the maximum possible Fixed List Length variations of our Fixed List that contain some variation of our Guaranteed Combination, without any duplication (i.e. 1, 2, 3 is equal to 2, 3, 1 and would only count as one match), and return the results.

Of course, to revisit the definitions of our key components , please refer back to our previous post on Number Pools

Today, we're going to look a Perl list sorting. In this context, you can actually consider our lists as arrays if you prefer. I'm going to keep calling them lists because, in the end, it will most closely approximate what we will want to manipulate; a fixed list of numbers.

From yesterday's posts on list permutations you can basically understand, even if you didn't run the code, how very many different combinations of 6 numbers there can be, when duplication is not a factor (i.e. 1, 2, 3 is different than 3, 2, 1). In our case, given our Objective, we would want those number lists, in parentheses above, to be considered equal. So how do we go about that?

There are actually quite a number of ways you can go about doing this. They run the gamut from human-readable and computer-intensive to nearly-hieroglyphic and incredibly efficient. Some folks like to dump all their values into hashes and sort it out that way, since the Perl hash function is built to sort keys and values. I'm not against that at all, but feel like it might stray us farther off the path and I want to keep this series of posts somewhat accessible.

My answer is actually a fairly commonly used one, as well. I don't consider myself a Perl expert (or really even a Unix or Linux expert. Like in Eastern philosophy: Even the teacher is ever the student). If I ever do convince myself that I know it all, I'll probably have a fatal seizure from lack-of-interest within moments of my revelation ;)

I like to sort all of my permutations (in this case numerically) first, and then check for duplicates. This makes sense to me, for some reason, and (especially in this case) it can greatly reduce the pressure you feel when dealing with large numbers of numbers. For instance, our 720 permutations are all of the same 6 numbers, so, once they've all been sorted numerically, we're going to have 720 identical lists. We don't even need a computer to tell us what our Objective obliquely defines as a "unique list" in this situation. It's "1, 2, 3, 4, 5."

All of our actions are predicated on the output of the "public domain" code we put out yesterday, which has been revised slightly to suit our purposes (the original just printed out the answers and didn't do any variable assignation or a return) and, yes, I do use my lists as arrays from time to time (we all need time to relax and unshift ;) The "permute" subroutine is called with an array, or list, (@number_seeds) as its only argument (which contains "1, 2, 3, 4, 5"), like:

@s_perms = permute([@number_seeds], []);

Modified code below:

sub permute {
my @items = @{ $_[0] };
my @perms = @{ $_[1] };
unless (@items) {
# LIMITED TO ONE CONTIGUOUS PERMUTATION CHAIN
@sortperms = join(" ", @perms);
unshift(@s_perms, "@sortperms" );
} else {
my(@newitems,@newperms,$i);
foreach $i (0 .. $#items) {
@newitems = @items;
@newperms = @perms;
unshift(@newperms, splice(@newitems, $i, 1));
permute([@newitems], [@newperms]);
}
}
return @s_perms;
}


And that's the lesson for today. I've attached code to the end of the post to illustrate the steps of sorting each list in our list of lists and checking for (and removing) duplicate lists from the pool. Note that we don't take into account multiple variable lists, as this won't be germane later (and adds some heft to the scriplet :) I tried to make this as easy to read as possible, so various steps, which could be combined, have been spelled out. If it has the opposite effect and makes things more confusing, I apologize profusely. And let me know! If there's interest, I'd be happy to write about this stuff at a much more granular level :)

Here's the mock output, to save you a screenshot:

host # ./program
1 2 3 4 5


Enjoy!


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# program - an unoriginal name for an unoriginal concept ;)
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

foreach $unsorted (@s_perms) {
@temparray = split(" ", $unsorted);
@temparray = sort { $a <=> $b } (@temparray);
unshift(@sorted_perms, "@temparray");
}
#@sorted_perms = sort { $a <=> $b } (@s_perms);

$unik="0";
$last_unik="0";
foreach $s_p (@sorted_perms) {
@unik = split(" ", $s_p);
@unik = sort(@unik);
if ( $unik == $last_unik ) {
print "$s_p";
@last_unik = @unik;
$last_unik++;
} elsif ( @unik == @last_unik ) {
$total = @unik;
$zero = $nope = 0;
while ( $zero < $total ) {
if ( "$unik[$zero]" ne "$last_unik[$zero]" ) {
$nope = 1;
last;
} else {
$zero++;
}
}
if ( $nope ) {
print "$s_p";
@last_unik = @unik;
}
} else {
print "$s_p";
@last_unik = @unik;
}
}


, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, September 3, 2008

Lists vs. Strings: Perl List Permutations For Linux Or Unix

Hey there,

I think I promised yesterday that all posts having to deal with Number Pools And Guaranteed Combinations Within Fixed Lists would have that string in their title, but, upon further reflection, it seems like it would make every title waaaay too long, and none of the parts would get indexed correctly, since Google might discard them as duplicate content based on the title tag.

In any event, this post is another small step toward yesterday's objective, along with (hopefully) an understanding of the various processes and steps involved in getting there. These are, indeed, small chunks of information when taken separately, but that is by intent. I'm not trying to insult anyone's intelligence; just keep the playing field even for all concerned ;) If you need to review the definitions of our system, please refer back to yesterday's post on Number Pools and we'll iterate (not reiterate of course, because that would be repeating it again. I'm only repeating it this time... OK, enough with the wordy nit-picking ;)

Today, we're going to look at one of the basics of building a system which can produce our desired end result. That basic building block is known as the permutation of a list, as opposed to an array (or string). Given Perl's definitions, at their basic, a list is static and cannot be modified, while the opposite is true of an array. They look deceptively the same. Most people don't know the difference. I still may not have a fingernail grip on the exact definition and details of the difference, but it hasn't caused me too much heartache ;) And, of course, strings are generally considered scalar variables (single value).

Our objective has been modified (in form, not in nature) to accommodate this change (and I've updated the original post's definitions as well): Given a Number Pool of "x through y," create the maximum possible Fixed List Length variations of our Fixed List that contain some variation of our Guaranteed Combination, without any duplication (i.e. 1, 2, 3 is equal to 2, 3, 1 and would only count as one match), and return the results.

In any event, my sincerest apologies for using string when I meant list. I didn't get a whole lot of complaints about this, which means either most everyone got what I meant or a vast majority of readers believe that Internet democracy will sort me out one way or another (which it has). This is what happens when you write at family gatherings ;)

So, given our Fixed List from yesterday (the numbers that, together, add up to a total of "Fixed List Length" members), we would first be looking for all permutations of that List. The list being composed of "1, 2, 3, 4, 5"

Using the following "public domain" code (meaning I didn't write it, don't accept credit for it, love it, but don't know who to credit it to ;) we can generate all permutations of our Fixed List. This will be the first thing we want to do, because this step needs to be completed before we check for Guaranteed Combinations within those permutations!

#!/usr/bin/perl

permute([1,2,3,4,5], []);

sub permute {
my @items = @{ $_[0] };
my @perms = @{ $_[1] };
unless (@items) {
print "@perms\n";
} else {
my(@newitems,@newperms,$i);
foreach $i (0 .. $#items) {
@newitems = @items;
@newperms = @perms;
unshift(@newperms, splice(@newitems, $i, 1));
permute([@newitems], [@newperms]);
}
}
}


This will produce all permutations of the List "1, 2, 3, 4, 5," as such (cropped for space savings):

5 4 3 2 1
4 5 3 2 1
5 3 4 2 1
3 5 4 2 1
4 3 5 2 1
3 4 5 2 1
...


As you can see, given our very simple example (where everything is equal to 5 and all lists and combinations are 5 (or 1, 2, 3, 4, 5), we have a lot of repetition in our output, and part of our stated objective is to create this list "without any duplication (i.e. 1, 2, 3 is equal to 2, 3, 1...)..."

Obviously, although this piece of Perl code will provide us with every possible permutation of the list "1, 2, 3, 4, 5," according to our Objective's definition, they're all equal. As we noted yesterday, the result can only be one list of five numbers, given our standards.

Tomorrow, we'll look at a way to resolve this issue, using a minimal amount of code (and, of course, a lot more of my concentric-circular explanation ;) so that the permutations get whittled down to the one unique list (containing all 5 numbers in our list) and removing all the "technically" different ones, which are essentially all the same list printed out in different order.

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, June 12, 2008

Using chkconfig To Manage Linux Service Run Levels

Hey there,

If you're like me, you've probably gotten used to creating init scripts and all the various linking to run level directories that needs to be done so that certain services will start and stop at the run levels you decide you want them to.

Even so, I'm always impressed with ways to make this sort of setup easier. Especially when it comes to manipulation of start and stop (init) scripts that come with system software. Solaris' mish-mosh of hard and soft linked run level scripts can be a headache, for sure, but Redhat, Fedora and other Linux flavours can be a bit of a pain, as well. The main problem I run into is making a customized change that ends up getting overwritten by an RPM upgrade or things of that nature.

Thankfully, that issue has been addressed, more than adequately, in a few ways. One of my favorites is the chkconfig command (usually located in the /sbin directory). This tool makes it very easy for an administrator to control at what run levels virtually every system-controlled service starts and stops.

Today, we're going to look at a few common ways to use chkconfig to make administration of run levels more convenient.

The first way is the most obvious. If you want to know everything that's going on with every service that's being controlled, simply type:

host # /sbin/chkconfig --list

and you'll get output similar to this:

acpid 0:off 1:off 2:off 3:off 4:on 5:on 6:off
anacron 0:off 1:off 2:on 3:on 4:on 5:on 6:off
...


An easy way to find out what services are "on" is to just pipe the above command to grep. If you want to know what's running "now" (or, at least, what should be ;), you can find your run level with the who command and then use chkconfig to find all the active services:

host # who -r
run-level 3...
host # chkconfig --list|grep "3:on"


or, if you're only interested in one service, you can specify it and chkconfig will query its state at your current run level, like so:

host # chkconfig anacron

More specifically (since that would only show you services that get started at run level 3, you could do this:

host # chkconfig --list|egrep '[123]:on'

and you should see all the services that are running currently (assuming your machine boots normally, through run levels 1 and 2, before getting to 3).

You can also use chkconfig to configure any listed service to start and/or stop at any run level you choose. You can even do multiple run levels at once. So, all of the following commands would be valid (assuming you have the service "anacron" on your machine):

host # chkconfig anacron on
host # chkconfig anacron off
host # chkconfig --level 3 anacron on
host # chkconfig --level 3 anacron off
host # chkconfig --level 235 anacron on
host # chkconfig --level 046 anacron off


Also note that on some systems, on and off only apply to run levels 2, 3, 4 and 5. Setting other levels may not work, but should not cause failure.

An alternative to on or off, is to use reset. This keyword will reset the service to start and stop at the run levels it defaults to (look near the bottom of this post to see from where chkconfig gets that information).

host # chkconfig anacron reset

Some simple scripting can make it so that you can replicate this behaviour for multiple services. At this point, to my knowledge, you can only either make changes globally or per-service. In any event, something like this is simple enough to work out at the command line (after checking out all of the services with --list, put the ones you want to start at runlevels 3 and 5 , and be turned off at all other levels, into a text file, one service per line). Note, that this is just my little command line script, and can be done a lot of different ways, so you should do this however makes the most sense for you:

host # for x in `cat MYSERVICES`;do /sbin/chkconfig --level 35 $x on;/sbin/chkconfig --level 01246 off;done

And the final (and most helpful, since it keeps you from having to remember how to format an init script to work with chkconfig) thing chkconfig does, is allow you to add and delete services. If your service isn't standard, you may still have to write your own init script, but for all packaged (and handled) services, this is a snap.

To remove a service that's currently active, just type:

host # chkconfig --del anacron

And to reinstate it, just type

host # chkconfig --add anacron

And, bingo, you're all set :) Note that the above add/del function really only creates and destroys symlinks from the init directory to the run level directories, so if you've deleted the actual init script, using chkconfig to re-add the service probably won't work. If you still have access to the RPM for that package, you can fix it to replace any missing files that way first.

If you do decide to create your own init script, and want it to be controlled by chkconfig, just make sure that you have these lines near the top of the script, in the comment section, below the shebang line and above any other comments in the script, like this:

#!/bin/sh

#
# chkconfig: 235 10 60


This part of the init script is what chkconfig looks for, and, in this instance, it tells chkconfig that the service should start at run levels 2, 3 and 5, it should be turned off for all other run levels (chkconfig's default assumption) and that it should have a start priority of 10 and a stop priority of 60. The priority numbers that you include in your script are relative and shouldn't generally be an issue. The defaults are usually 20 and 80. You can also add a "#description:" line (directly after the required chkconfig line) to your script if you want to be able to see that in chkconfig output, but it's not necessary.

Here's hoping this helps your run level management step up and get easier, all at the same time! :)

Cheers,

, Mike

Saturday, June 7, 2008

Using Perl To Handle Mass Mailing In Linux Or Unix

Hey there,

Today, we're going to take a look at a quick Saturday script to handle mass mailing with Perl. This is not to be confused with SPAM, although you could use it for that purpose if you're looking to trim down your social circle ;)

Actually, an older post we did on collecting mails using a CGI autoresponder is probably more suited to "Bulk Email Marketing." Although I simply delete any SPAM I get, I don't question anyone's right to fill my mailbox with junk if I sign up online to download some goofy report. I take no side in the "good vs. evil" debate, insofar as SPAM is concerned, and consider myself more of an on-looker. If it is, indeed, wrong, there is almost certainly something unpleasant waiting in the wings for the purveyors, and opting to sit on the fence can become very painful after a while ;)

In any event, I hope you enjoy (or can find some good use for) today's script. It's very simple to run, and should allow you to mass email to groups of people (who belong to your mailing list because they work at your company or requested inclusion) on any Linux or Unix variant that supports sendmail. Minor modifications should be easy enough to make if you use another mail agent.

You can execute the script with the following arguments:

host # ./listmail.pl listname messagename

with the listname being a text file consisting of one address per line, with a more descriptive name followed by the email address and separated by double-colon notation (::), like this:

Mr. Miller::abc@def.com

You can modify the split() function in the script if you prefer to delimit multiple items on single lines using another typographical character (you can also opt to change the script so it only takes an email address per line and doesn't do the split).

The messagename should be a text file which includes the body of your email message. Also, your sendmail may be in /usr/lib, rather than /usr/sbin.

Note for those who wish to do some mangling and make this script more flexible: An easy improvement to this script would be to include the From:, To:, etc lines in your message file and then pipe your print statements to "sendmail -t", rather than hardcoding it using sendmail flags, as we've done below.

Anyhow, hope you enjoy it and have a great weekend :)


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl
#
# listmail.pl - send email to folks, who want to receive email from you, more efficiently
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

if ($#ARGV != 1) {
print "Usage: listmail listname messagename\n";
exit;
}

$maillist=$ARGV[0];
$message=$ARGV[1];
$count = 0;

open(MAILING, "<$maillist");
@mailing = <MAILING>;
close(MAILING);

foreach $mailee (@mailing) {
if ($count < 60) {
@addies = split(/::/, $mailee);
open(HEADER, ">/tmp/header.lst");
print HEADER "From: uvw\@xyz.com\n";
print HEADER "Subject: xyz.com Updates!\n";
print HEADER "Reply-To: uvw\@xyz.com\n";
print HEADER "X-cid: $addies[0]\n";
close(HEADER);
open(HEADER, "</tmp/header.lst");
@HEADER = <HEADER>;
close(HEADER);
open(SENDMAIL, "|/usr/sbin/sendmail -f uvw\@xyz.com -F \"uvw\@xyz.com\" -oi $addies[1]");
foreach $head (@HEADER) {
print SENDMAIL $head;
}
open(MESSAGE, "<$message");
@message = <MESSAGE>;
close(MESSAGE);
foreach $line (@message) {
print SENDMAIL $line;
}
close(SENDMAIL);
$count++;
} elsif ($count == 60) {
@addies = split(/::/, $mailee);
open(HEADER, ">/tmp/header.lst");
print HEADER "From: uvw\@xyz.com\n";
print HEADER "Subject: xyz.com Updates!\n";
print HEADER "Reply-To: uvw\@xyz.com\n";
print HEADER "X-cid: $addies[0]\n";
close(HEADER);
open(HEADER, "</tmp/header.lst");
@HEADER = <HEADER>;
close(HEADER);
open(SENDMAIL, "|/usr/sbin/sendmail -f uvw\@xyz.com -F \"uvw\@xyz.com\" -oi $addies[1]");
foreach $head (@HEADER) {
print SENDMAIL $head;
}
open(MESSAGE, "<$message");
@message = <MESSAGE>;
close(MESSAGE);
foreach $line (@message) {
print SENDMAIL $line;
}
close(SENDMAIL);
$count = 0;
sleep 60;
}
}


, Mike