#!/usr/bin/perl # Michael Tartaglia # restaurant.cgi # This program helps a user decide upon a resaurant to dine in. The user # enters some options, and the computer "flips coins" and tells the user which # restaurant to go to use strict; use CGI qw( :standard ); require template; template::startHTML("Freelance Program","Restaurant Chooser"); my $QUERY = $ENV{'QUERY_STRING'}; # QUERY STRING OF USER # IF THERE WAS NO QUERY STRING (NO INITIAL SUBMISSION), THEN DISPLAY INTRO print "

If you have ever been unable to decide which restaurant in which ", "you want to have dinner, this is the program for you! Enter ", "the number of restaurants you are having trouble trying to ", "choose between.


", "
" if ($QUERY eq ""); # IF THERE WAS AN ENTRY MADE, AND IT WAS OF A NUMBER 'N', # DISPLAY A FORM THAT CONTAINS N ROWS OF BOXES IN WHICH # TO TYPE IN RESTAURANT NAMES if ($QUERY ne "" && param("num") ne "") { my $n = param("num"); $n =~ s/\D//g; # ENSURE ONLY A NUMBER WAS ENTERED if ($n ne "") { print "STEP 2: Now, enter the names of each restaurant.
", "
"; print "Restaurant #$_:
" foreach (1 .. $n); print "
"; } elsif ($n < 2) { # AT LEAST 2 RESTAURANTS NEED BE ENTERED print "You need at least two restaurants!
", "Go back and fix your number." and goto END; } else { # IF NO VALID NUMBER WAS ENTERED print "Umm...
You gotta enter a number of restaurants.
", "Go back and fix your number." and goto END; } # ELSE, IF THERE WAS AN ENTRY, AND IT DID NOT CONTAIN A NUMBER # GATHER THE RESTAURANT NAMES, "FLIP A COIN," AND DISPLAY # RESULTS TO USER } elsif ($QUERY ne "" && param("num") eq "") { my $r = 1; # INDEX my @foodStoreNames = (""); # NAMES ENTERED IN FORM while (param("r$r") ne "") { # READ IN RESTAURANT NAMES $foodStoreNames[$r-1] = param("r$r"); $r++; } # IF LESS THAN TWO RESTAURANT NAMES ARE ENTERED print "You gotta enter at least two restaurant names!
", "Go back and fix what you entered." and goto END if ($foodStoreNames[0] eq "" || $foodStoreNames[1] eq ""); my $stores = @foodStoreNames - 1; my @foodStoreChoices; # FOOD STORE CHOICES $foodStoreChoices[$_] = 0 foreach (0 .. $stores); my $MAX = $stores*100; # MAXIMUM NUMBER OF COIN FLIPS # FLIP COINS $foodStoreChoices[rand($stores+1)]++ foreach(1 .. $MAX); # AFTER COIN FLIPS, SORT THE FOOD STORES (USING BUBBLE SORTING) INTO # DESCENDING ORDER my $swap; foreach my $i (0 .. $stores) { foreach my $j ($i .. $stores) { if ($foodStoreChoices[$j] > $foodStoreChoices[$i]) { my $swap = $foodStoreChoices[$i]; $foodStoreChoices[$i] = $foodStoreChoices[$j]; $foodStoreChoices[$j] = $swap; $swap = $foodStoreNames[$i]; $foodStoreNames[$i] = $foodStoreNames[$j]; $foodStoreNames[$j] = $swap; }}} # DISPLAY RESULTS TO USER print "According to what you entered,
the program found these ", "restaurants most appealing:

"; print "" foreach (0 .. $stores); print "
", 1+$_ , ".$foodStoreNames[$_](", (int(10000*$foodStoreChoices[$_]/$MAX)/100), "\%)
"; } END: # END BLOCK template::endHTML();