code » Code for zeroesones.cgi

Last modified

Perl code written to create a list comprising X zeroes and Y ones, randomly placed, relating to this entry. See the program itself.

#!/usr/bin/perl -w
# zeroesones.cgi
# fridgemagnet, 2004/03/09
# Creates a string containing a fixed number of zeroes and 
ones, randomly placed.

use strict;
use CGI qw(:param);

my $MAXIMUM = 100000;

my $zeroes = param("zeroes") || 0;
my $ones = param("ones") || 0;

print "Content-type: text/html\n\n";

print "<html>\n<head>\n<title>Zeroes And Ones String 
Generation</title>\n";<style>\n\@import 
url(\"/lj_styles.css\");\nbody \{ text-align: left; margin: 20px; 
\}\n</style>\n</head>\n<body>\n<h1>Zeroes And Ones 
String Generation</h1>\n";

if ($zeroes && $ones) {
	if (($zeroes + $ones) > $MAXIMUM) {
		print "<p>What are you trying to do
		here? $zeroes zeroes and $ones ones? You're having a laugh mate. 
		You'll tie up my server.</p>\n<p>(Try reducing the total
		length to $MAXIMUM or less.)</p>\n";
	} else {
		my ($a, $b) = ("0", "1");
		if ($ones > $zeroes) {
			($a, $b) = ("1", "0");
		}
		my $list = $a x ($zeroes + $ones);
		my $position;
		for (my $count = 0; $count < $ones; $count++) {
			do {
				$position = sprintf("%d", rand($zeroes + $ones));
			} until (substr($list, $position, 1) ne $b);
			substr($list, $position, 1) = $b;
		}
		print "<p>$zeroes zeroes, $ones ones:</p>\n<textarea
		cols=\"60\" 
		rows=\"6\">$list</textarea>\n<hr>\n";
	}
}

print '<form> <p>Enter number of zeroes:<br /><input 
type="text" name="zeroes"></p> <p>Enter 
number of ones:<br /><input type="text" 
name="ones"></p> <p><input 
type="submit"></p> </form> ';

print "<p><a href=\"/\">fridgemagnet</a>, 
Friday 5 March 2004</p>\n<p>(<a 
href=\"/code/zeroesones.html\">See the 
source</a>)</p>\n";
print "</body>\n</html>\n";

fridgemagnet, Friday 5 March 2004