├── 2005 ├── soap.pl ├── test2.pl ├── add.pl ├── test3.pl ├── reverse.pl ├── grepstuff.pl ├── edit.pl ├── test.pl ├── entries.pl ├── sig.pl └── chain.pl ├── 2006 ├── crap.java ├── stacktest.java ├── q3.pl ├── testcodeshit.java ├── old.java ├── expressionEvaluator.java ├── old2.java └── expressionTreeNode.java ├── 2007 ├── find.pl ├── users.pl ├── smbhash.pl └── gen.pl ├── 2008 ├── iii.py ├── count.pl ├── costs.pl ├── transform.pl ├── generate_expectations.pl ├── draw_graph_gener.py ├── generate_expectations2.pl ├── c.py ├── d.py ├── hw2-clean.py ├── b.py ├── 1.py ├── hw1.py ├── a.py ├── look.py ├── test.py └── draw_graph.py ├── 2009 ├── parse.py ├── check.py ├── working-traffic.py ├── clean.py └── traffic.py └── README.md /2008/iii.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Some of the first programs I wrote. 2 | -------------------------------------------------------------------------------- /2007/find.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | print `grep $ARGV[0] sums-stuff/users2`; 4 | -------------------------------------------------------------------------------- /2008/count.pl: -------------------------------------------------------------------------------- 1 | my $i = 0; 2 | while(<>) { 3 | $i += $_; 4 | } 5 | print "$i\n" 6 | 7 | -------------------------------------------------------------------------------- /2007/users.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl\ 2 | 3 | while(<>) { 4 | my ($name, @rest) = split(/:/); 5 | print "$name\n"; 6 | } 7 | -------------------------------------------------------------------------------- /2006/crap.java: -------------------------------------------------------------------------------- 1 | public class crap { 2 | 3 | public static void main() { 4 | byte blah = 3; 5 | byte blah2 = 4; 6 | blah = blah * blah2; 7 | } 8 | } -------------------------------------------------------------------------------- /2005/soap.pl: -------------------------------------------------------------------------------- 1 | use SOAP::Lite; 2 | print SOAP::Lite 3 | -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl') 4 | -> getQuote('MSFT'), "\n"; -------------------------------------------------------------------------------- /2005/test2.pl: -------------------------------------------------------------------------------- 1 | use SOAP::Lite; 2 | print SOAP::Lite 3 | -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl') 4 | -> getQuote('MSFT'), "\n"; -------------------------------------------------------------------------------- /2006/stacktest.java: -------------------------------------------------------------------------------- 1 | public stacktest { 2 | public static void main() { 3 | Stack blah = new Stack(); 4 | blah.push("something"); 5 | String s = blah.pop(); 6 | } 7 | } -------------------------------------------------------------------------------- /2005/add.pl: -------------------------------------------------------------------------------- 1 | use Chaos; 2 | 3 | my $blog = new Chaos(username=>"someone", password=>"foobar"); 4 | 5 | $blog->add( text=>"Test Post", 6 | title=>"This Is A Test", 7 | tags=>["test", "test2"] 8 | ) -------------------------------------------------------------------------------- /2005/test3.pl: -------------------------------------------------------------------------------- 1 | use Interblog; 2 | 3 | my $blog = new Interblog(username=>"someone", password=>"foobar"); 4 | 5 | $blog->add( text=>"entry", 6 | title=>" sucks", 7 | tags=>["mytags", "blah"] 8 | ) 9 | -------------------------------------------------------------------------------- /2005/reverse.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | print "Content-type: text/html\n\n"; 3 | my $string = $ENV{'QUERY_STRING'}; 4 | $string =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("c", hex($1))/ge; 5 | my $reverse = reverse $string; 6 | print $reverse; -------------------------------------------------------------------------------- /2005/grepstuff.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use warnings; 3 | my @imgs; 4 | while(<>) 5 | { 6 | /src="(.+?)"/; 7 | s:/pictures::g; 8 | if ($1) 9 | { 10 | push(@imgs,$1) unless -e $1 ; 11 | } 12 | } 13 | print join("\n",@imgs); 14 | -------------------------------------------------------------------------------- /2006/q3.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use warnings; 4 | use strict; 5 | my @peaks, @tf; 6 | 7 | for (0..199) { 8 | my $num = int(rand() * 400); 9 | print "$num\n"; 10 | } 11 | my $cur = $peaks[0]; 12 | my $curind = 0; 13 | for(0..199) { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /2005/edit.pl: -------------------------------------------------------------------------------- 1 | use Chaos; 2 | 3 | my $blog = new Chaos(username=>"someone", password=>"foobar"); 4 | 5 | my $entry = $blog->edit(text=>"Blah", 6 | title=>"You Suck", 7 | tags=>["test", "test2"], 8 | id=>3, 9 | ); 10 | 11 | print $entry->title, "\n"; 12 | -------------------------------------------------------------------------------- /2007/smbhash.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | my $pass = $ARGV[0]; 3 | use Crypt::SmbHash qw(ntlmgen lmhash nthash); 4 | use Encode; 5 | ( $lm, $nt ) = ntlmgen decode('iso-8859-1', $pass); 6 | $lm = lmhash(decode_utf8($pass), $pwenc); 7 | $nt = nthash(decode_utf8($pass)); 8 | print "sambaLMPassword: $lm\nsambaNTPassword: $nt\n"; 9 | -------------------------------------------------------------------------------- /2005/test.pl: -------------------------------------------------------------------------------- 1 | use Entry; 2 | use warnings; 3 | my $entry = new Entry; 4 | 5 | $entry->title("Hello"); 6 | $entry->id("339293"); 7 | $entry->tags(1,2,3,4); 8 | print $entry->title; 9 | print $entry->id; 10 | print join("\n", $entry->tags); 11 | 12 | my %other = ( 13 | song => "greenday", 14 | mood => "insane", 15 | ); 16 | 17 | $entry->other(\%other); 18 | 19 | my %hash = ($entry->other); 20 | print keys %hash, "\n"; -------------------------------------------------------------------------------- /2005/entries.pl: -------------------------------------------------------------------------------- 1 | use Chaos; 2 | 3 | my $blog = Chaos->new(username=>"someone", password=>"foobar"); 4 | for (19..25) { 5 | if (my $entry = $blog->entry($_)) { 6 | print "Title: ", $entry->title, "\n"; 7 | print "Tags: ", join(", ", $entry->tags), "\n"; 8 | print "HTML: \n", $entry->html, "\n\n"; 9 | } else { 10 | print "none\n"; } 11 | #~ print join("\n", $entry->tags), "\n"; 12 | #~ print ($entry->html || "no", "\n"); 13 | } -------------------------------------------------------------------------------- /2008/costs.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use warnings; 3 | use strict; 4 | 5 | unless(open DISTANCES, $ARGV[0]) { 6 | print "\n\nUsage: ./generatedistances [filename of matrix of expectations]\n"; 7 | exit; 8 | } 9 | my $i = 0; 10 | my $str; 11 | while() { 12 | # Each row i is the expectations of # of people coming to site i from zone j 13 | $i++; 14 | my $j = 0; 15 | chomp; 16 | my @distances = split/, /; 17 | for (@distances) { 18 | $j++; 19 | print "$i $j $_\n"; 20 | } 21 | } 22 | 23 | sub f { 24 | exp(-1*shift); 25 | } 26 | -------------------------------------------------------------------------------- /2008/transform.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use warnings; 3 | use strict; 4 | 5 | unless(open DISTANCES, $ARGV[0]) { 6 | print "\n\nUsage: ./generatedistances [filename of matrix of expectations]\n"; 7 | exit; 8 | } 9 | my $i = 0; 10 | my $str; 11 | while() { 12 | next if /^$/; 13 | # Each row i is the expectations of # of people coming to site i from zone j 14 | $i++; 15 | my $j = 0; 16 | chomp; 17 | my @distances = split/ /; 18 | for (@distances) { 19 | $j++; 20 | print "$i $j $_\n"; 21 | } 22 | } 23 | 24 | sub f { 25 | exp(-1*shift); 26 | } 27 | -------------------------------------------------------------------------------- /2007/gen.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use Crypt::SmbHash qw(ntlmgen lmhash nthash); 3 | use Encode; 4 | 5 | while(<>) { 6 | my ($username, $nothing, $uid, $gid, $gecos, $homedir, $shell) = split(/:/); 7 | $gecos=~/(.+?) \) { 18 | chomp; 19 | push @densities, $_; 20 | } 21 | my $i = 0; 22 | while() { 23 | next if /^$/; 24 | chomp; 25 | my @distances = split /\s+/; 26 | for (@distances) { 27 | my $expectation = f($_) * $densities[$i] *10000; 28 | print "$expectation "; 29 | } 30 | print "\n"; 31 | $i++; 32 | } 33 | 34 | sub f { 35 | return exp(-1*shift); # f(x) is probability that someone at distance x will come to the clinic 36 | # this function should actually be provided by the management team 37 | # (mostly so that we can blame them for it). I asked Yang for something yesterday. 38 | } 39 | -------------------------------------------------------------------------------- /2008/draw_graph_gener.py: -------------------------------------------------------------------------------- 1 | import os,sys 2 | 3 | f = os.popen("gnuplot", "w") 4 | 5 | f.write(""" 6 | #!/usr/bin/gnuplot -persist 7 | # 8 | # 9 | # G N U P L O T 10 | # Version 4.2 patchlevel 2 11 | # last modified 31 Aug 2007 12 | # System: Linux 2.6.24-19-generic 13 | # 14 | # Copyright (C) 1986 - 1993, 1998, 2004, 2007 15 | # Thomas Williams, Colin Kelley and many others 16 | # 17 | # Type `help` to access the on-line reference manual. 18 | # The gnuplot FAQ is available from http://www.gnuplot.info/faq/ 19 | # 20 | # Send bug reports and suggestions to 21 | # 22 | # set terminal wxt 0 23 | set out \"""" + sys.argv[1] + ".ps\"" 24 | """ 25 | set terminal postscript portrait enhanced "Helvetica" 14 26 | set style arrow 27 | set grid 28 | set autoscale 29 | set title "2. c) dataset 2" 30 | set xlabel "Sensitivity" 31 | set ylabel "Specificity" 32 | plot \"""" + sys.argv[1] + ".txt\" with linespoints 1 7 " 33 | ) 34 | -------------------------------------------------------------------------------- /2009/parse.py: -------------------------------------------------------------------------------- 1 | import sys 2 | inStr = file(sys.argv[-1]).read() 3 | lines = [x for x in inStr.split('\n') if len(x)>0] 4 | #print lines 5 | names = [line.split()[0] for line in lines] 6 | nameToNum = dict(zip(names, range(len(names)))) 7 | 8 | fields = ["name", "ServingSize", "Calories", "CaloriesFromFat", "TotalFat", "TotalFatPercent", "SaturatedFat", "SaturatedFatPercent", "TransFat", "TransFatPercent", "Cholesterol", "CholesterolPercent", "Sodium", "SodiumPercent", "TotalCarbs", "TotalCarbsPercent", "DietaryFiber", "DietaryFiberPercent", "Sugars", "SugarsPercent", "Protein", "VitaminA", "VitaminC", "Calcium", "Iron", "isFruitVeg", "isDairy", "isCereal", "isMeat", "Price"] 9 | 10 | 11 | output = "" 12 | 13 | def f(x): 14 | if x.startswith("-"): 15 | return "0" 16 | else: 17 | return x 18 | 19 | for line in lines: 20 | values = dict(zip(fields, line.split())) 21 | name = values["name"] 22 | id = nameToNum[name] 23 | del values["name"] 24 | for i in values.keys(): 25 | output += "%s %s %s\n" % (id, i, f(values[i])) 26 | print output 27 | -------------------------------------------------------------------------------- /2008/generate_expectations2.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use warnings; 3 | use strict; 4 | 5 | my $file1 = $ARGV[0]; 6 | my $file2 = $ARGV[1]; 7 | 8 | unless ((-e $file1) and (-e $file2)) { 9 | print "Usage: generate_expectations.pl distance_matrix_file.txt density_file.txt\n"; 10 | exit; 11 | } 12 | 13 | open DISTANCES, $file1; 14 | open DENSITIES, $file2; 15 | 16 | my @densities; 17 | while() { 18 | chomp; 19 | push @densities, $_; 20 | } 21 | my $i = 0; 22 | while() { 23 | next if /^$/; 24 | chomp; 25 | my @distances = split /\s+/; 26 | my $j = 0; 27 | for (@distances) { 28 | my $expectation = f($_) * $densities[$j] * 8 * 220; 29 | $j++; 30 | print "$expectation "; 31 | } 32 | print "\n"; 33 | $i++; 34 | } 35 | 36 | sub f { 37 | my $dist = shift; 38 | if ($dist < 1.1) { 39 | return 1; 40 | } 41 | return exp(-1/10*($dist - 1.1) ); # f(x) is probability that someone at distance x will come to the clinic 42 | # this function should actually be provided by the management team 43 | # (mostly so that we can blame them for it). I asked Yang for something yesterday. 44 | } 45 | -------------------------------------------------------------------------------- /2008/c.py: -------------------------------------------------------------------------------- 1 | import operator 2 | # Change dataset1 to dataset2 to get the results for dataset2 3 | pos = open("dataset2/positive.txt", "r") 4 | neg = open("dataset2/negative.txt", "r") 5 | 6 | pos_sites = pos.readlines() 7 | num_sites = len(pos_sites) 8 | neg_sites = neg.readlines() 9 | seq_length = len(pos_sites[0]) -1 10 | nucleotides = ['A', 'C', 'G','T'] 11 | M = dict() 12 | for x in nucleotides: 13 | for i in range(seq_length): 14 | M[(i,x)] = 0 15 | for site in pos_sites: 16 | for i in range(seq_length): 17 | M[(i,site[i])] += float(1) / num_sites 18 | 19 | def predict(matrix, site, threshold): 20 | score =reduce (operator.mul, [matrix[(i,site[i])] for i in range(seq_length)]) 21 | # print score , threshold 22 | if score < threshold: 23 | return 0 24 | else: 25 | return 1 26 | 27 | class_errors = [] 28 | def threshold(index): 29 | return float(index) / 1000000 30 | 31 | for i in range(200000): 32 | curr_threshold = threshold(i) 33 | true_pos = 0 34 | false_neg = 0 35 | true_neg = 0 36 | false_pos = 0 37 | for site in pos_sites: 38 | if predict(M, site, curr_threshold): 39 | true_pos +=1 40 | else: 41 | false_neg +=1 42 | for site in neg_sites: 43 | if predict(M, site, curr_threshold): 44 | false_pos +=1 45 | else: 46 | true_neg +=1 47 | print float(true_pos) / float(false_neg + true_pos) ,float(true_neg) / float(false_pos + true_neg) 48 | -------------------------------------------------------------------------------- /2008/d.py: -------------------------------------------------------------------------------- 1 | import operator 2 | # change x and the dataset to obtain different results 3 | x = 100 4 | pos = open("dataset2/positive.txt", "r") 5 | neg = open("dataset2/negative.txt", "r") 6 | 7 | pos_sites = pos.readlines() 8 | num_sites = len(pos_sites) 9 | neg_sites = neg.readlines() 10 | seq_length = len(pos_sites[0]) -1 11 | nucleotides = ['A', 'C', 'G','T'] 12 | M = dict() 13 | for n in nucleotides: 14 | for i in range(seq_length): 15 | M[(i,n)] = float(x) / (num_sites + 4*x) 16 | for site in pos_sites: 17 | for i in range(seq_length): 18 | M[(i,site[i])] += 1.0 / (num_sites + 4*x) 19 | 20 | def predict(matrix, site, threshold): 21 | score =reduce (operator.mul, [(matrix[(i,site[i])]) for i in range(seq_length)]) 22 | # print score , threshold 23 | if score < threshold: 24 | return 0 25 | else: 26 | return 1 27 | 28 | class_errors = [] 29 | def threshold(index): 30 | return float(index) / 10000000 31 | 32 | for i in range(20000): 33 | curr_threshold = threshold(i) 34 | true_pos = 0 35 | false_neg = 0 36 | true_neg = 0 37 | false_pos = 0 38 | for site in pos_sites: 39 | if predict(M, site, curr_threshold): 40 | true_pos +=1 41 | else: 42 | false_neg +=1 43 | for site in neg_sites: 44 | if predict(M, site, curr_threshold): 45 | false_pos +=1 46 | else: 47 | true_neg +=1 48 | print float(true_pos) / float(false_neg + true_pos) ,float(true_neg) / float(false_pos + true_neg) 49 | -------------------------------------------------------------------------------- /2005/sig.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use GD; 3 | use strict; 4 | use warnings; 5 | use CGI qw/:standard/; 6 | my %songdat; 7 | song(); 8 | my $string = &randstring; 9 | 10 | my $browser = $ENV{'HTTP_USER_AGENT'}; 11 | if ($songdat{'is_playing'} eq "true") { 12 | my $song = $songdat{'playlist_title'}; 13 | my $length = length (length($string) > length("music: $song") ? $string: "music: $song") * 6; 14 | my $im = new GD::Image($length + 2, 40); 15 | my $white = $im->colorAllocate(255,255,255); 16 | my $black = $im->colorAllocate(0,0,0); 17 | # make the background transparent and interlaced 18 | $im->transparent($white); 19 | $im->interlaced('true'); 20 | $im->string(gdSmallFont, 2, 2, $string, $black); 21 | $im->string(gdSmallFont, 2, 22, "music: $song" , $black); 22 | print "Content-type: image/png\n\n"; 23 | binmode STDOUT; 24 | print $im->png; 25 | } else { 26 | my $length = length($string) * 6; 27 | my $im = new GD::Image($length + 2, 20); 28 | my $white = $im->colorAllocate(255,255,255); 29 | my $black = $im->colorAllocate(0,0,0); 30 | # make the background transparent and interlaced 31 | $im->transparent($white); 32 | $im->interlaced('true');$im->string(gdSmallFont, 2, 2, $string, $black); 33 | print "Content-type: image/png\n\n"; 34 | binmode STDOUT; 35 | print $im->png; 36 | } 37 | 38 | 39 | sub randstring { 40 | my $file = "sigs"; 41 | open(DAT, "< $file"); 42 | chomp(my @array = ); 43 | my $rand = rand(@array); 44 | $array[$rand]; 45 | } 46 | 47 | sub song { 48 | my $file = "nowplaying"; 49 | open (DAT, "< $file"); 50 | while() { 51 | chomp; 52 | next unless /=/; 53 | my ($key, $val) = split/=/; 54 | $songdat{$key} = $val; 55 | } 56 | } -------------------------------------------------------------------------------- /2008/hw2-clean.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | import operator 3 | def rosenbrock(x,y): 4 | return 100*(y - x*x)**2 + (1-x)**2 5 | def gradient(x, y): 6 | return [400*x * (x*x - y) + 2*(x-1) , 200 * (y-x*x)] 7 | def hessian(x,y): 8 | return [[1200*x*x - 400*y, -400*x], [-400*x, 200]] 9 | def dot(l1, l2): 10 | return reduce( operator.add, map( operator.mul, l1, l2)) 11 | def mul(a, list): 12 | return map(lambda x: x*a, list) 13 | def add(l1, l2): 14 | return map(operator.add, l1, l2) 15 | def Mmulv(M, v): 16 | return map(lambda x: dot(v,x), M) 17 | 18 | def inverse(l): 19 | [[a,b], [c,d]] = l 20 | det = a*d-b*c 21 | return [[d/(det), -b/(det)], [-c/(det), a/(det)]] 22 | 23 | def backtrack(f, fk, pk, xk, grad, p, c, alpha): 24 | [a,b] = add(xk, mul(alpha, pk)) 25 | if (fk + c*alpha * dot(grad, pk) < f(a,b)): 26 | return backtrack(f, fk, pk, xk, grad, p, c, alpha*p) 27 | else: 28 | print alpha 29 | return alpha 30 | 31 | def descent(f,x,y): 32 | grad = gradient(x,y) 33 | if dot(grad, grad) < 0.01: 34 | return [x,y] 35 | else: 36 | pk = mul(-1/sqrt(dot(grad, grad)), grad) 37 | alpha = backtrack(f, f(x,y), pk, [x,y], grad, 0.8, 0.9,1) 38 | [a,b]=add( [x,y], mul(alpha, pk)) 39 | return descent(f,a,b) 40 | 41 | def newton(f,x,y): 42 | grad = gradient(x,y); 43 | hess = hessian(x,y); 44 | if dot(grad, grad) < 0.01: 45 | return [x,y] 46 | else: 47 | pk = mul( -1, Mmulv(inverse(hessian(x,y)), grad)) 48 | alpha = backtrack(f, f(x,y), pk, [x,y], grad, 0.8, 0.9,1) 49 | [a,b]=add( [x,y], mul(alpha, pk)) 50 | return newton(f, a, b) 51 | 52 | print "Steepest descent starting from point (1.2, 1.2): " 53 | descent(rosenbrock, 1.2, 1.2); 54 | print "Steepest descent starting from point (-1.2, 1): " 55 | descent(rosenbrock, -1.2, 1); 56 | print "Newton's method starting from point (1.2, 1.2): " 57 | newton(rosenbrock, 1.2, 1.2); 58 | print "Newton's method starting from point (-1.2, 1): " 59 | newton(rosenbrock, -1.2, 1); 60 | -------------------------------------------------------------------------------- /2008/b.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | # Change dataset1 to dataset2 to get the results for dataset2 4 | pos = open("dataset1/positive.txt", "r") 5 | neg = open("dataset1/negative.txt", "r") 6 | 7 | pos_sites = pos.readlines() 8 | num_sites = len(pos_sites) 9 | neg_sites = neg.readlines() 10 | seq_length = len(pos_sites[0]) -1 11 | nucleotides = ['A', 'C', 'G','T'] 12 | M = dict() 13 | for x in nucleotides: 14 | for i in range(seq_length): 15 | M[(i,x)] = 0 16 | for site in pos_sites: 17 | for i in range(seq_length): 18 | M[(i,site[i])] += float(1) / num_sites 19 | 20 | # predict whether or not a site will be predicted from the PWM 'matrix' given the threshold 'threshold' 21 | def predict(matrix, site, threshold): 22 | score =reduce (operator.mul, [matrix[(i,site[i])] for i in range(seq_length)]) 23 | if score <= threshold: 24 | return 0 25 | else: 26 | return 1 27 | 28 | class_errors = [] 29 | 30 | def threshold(index): 31 | return float(index) / 1000 32 | 33 | for i in range(1000): 34 | curr_threshold = threshold(i) 35 | true_pos = 0 36 | false_neg = 0 37 | true_neg = 0 38 | false_pos = 0 39 | for site in pos_sites: 40 | if predict(M, site, curr_threshold): 41 | true_pos +=1 42 | else: 43 | false_neg +=1 44 | for site in neg_sites: 45 | if predict(M, site, curr_threshold): 46 | false_pos +=1 47 | else: 48 | true_neg +=1 49 | class_errors.append(false_neg + false_pos) 50 | 51 | #print class_errors 52 | 53 | # choose the threshold to minimize classification errors 54 | opt_threshold = threshold(class_errors.index(min(class_errors))) 55 | print "Optimal threshold: ", opt_threshold 56 | 57 | true_pos = 0 58 | false_neg = 0 59 | true_neg = 0 60 | false_pos = 0 61 | for site in pos_sites: 62 | if predict(M, site, opt_threshold): 63 | print site 64 | true_pos +=1 65 | else: 66 | false_neg +=1 67 | for site in neg_sites: 68 | if predict(M, site, opt_threshold): 69 | false_pos +=1 70 | else: 71 | true_neg +=1 72 | print "True positives: ", true_pos 73 | print "False negatives: ", false_neg 74 | print "False positives: ", false_pos 75 | print "True negatives: ", true_neg 76 | 77 | print "Sensitivity: ", float(true_pos) / float(true_pos + false_neg) 78 | print "Specificity: ", float(true_neg) / float(true_neg + false_pos) 79 | -------------------------------------------------------------------------------- /2008/1.py: -------------------------------------------------------------------------------- 1 | import re 2 | import operator 3 | 4 | pos = open("promoterPositive.fa", "r") 5 | neg = open("promoterNegative.fa", "r") 6 | 7 | nucleotides = ['A', 'C', 'G','T'] 8 | def choose2(list): 9 | combinations = [] 10 | for x in list: 11 | for y in list: 12 | if x < y : 13 | combinations.append((x,y)) 14 | return combinations 15 | 16 | 17 | alphabet = nucleotides + choose2(nucleotides) + [tuple(nucleotides)] 18 | 19 | # generate all possible sequences 20 | sigmastar = [ [a,b,c,d,e,f] for a in alphabet for b in alphabet for c in alphabet for d in alphabet for e in alphabet for f in alphabet] 21 | 22 | d = dict() 23 | 24 | pos_lines = pos.readlines() 25 | neg_lines = neg.readlines() 26 | 27 | # calculate probabilities of A,C,G,T occurring 28 | 29 | promoter_length = len(pos_lines[0]) - 1 30 | 31 | num_A = sum([s.count('A') for s in pos_lines]) 32 | num_C = sum([s.count('C') for s in pos_lines]) 33 | num_G = sum([s.count('G') for s in pos_lines]) 34 | num_T = sum([s.count('T') for s in pos_lines]) 35 | total = num_A + num_C + num_G + num_T 36 | pos_probs = {'A' : float(num_A) / total, 37 | 'C' : float(num_C) / total, 38 | 'G' : float(num_G) / total, 39 | 'T' : float(num_T) / total} 40 | 41 | num_A = sum([s.count('A') for s in neg_lines]) 42 | num_C = sum([s.count('C') for s in neg_lines]) 43 | num_G = sum([s.count('G') for s in neg_lines]) 44 | num_T = sum([s.count('T') for s in neg_lines]) 45 | total = num_A + num_C + num_G + num_T 46 | neg_probs = {'A' : float(num_A) / total, 47 | 'C' : float(num_C) / total, 48 | 'G' : float(num_G) / total, 49 | 'T' : float(num_T) / total} 50 | 51 | print pos_probs 52 | print neg_probs 53 | 54 | for word in sigmastar: 55 | pos_matches = 0 56 | neg_matches = 0 57 | re_string = "".join(map(lambda x: "[" + "".join(x) + "]", word)) 58 | my_re = re.compile(re_string) 59 | expected_num_pos = reduce(operator.mul, [sum([pos_probs[x] for x in w]) for w in word]) * promoter_length * len(pos_lines) 60 | expected_num_neg = reduce(operator.mul, [sum([neg_probs[x] for x in w]) for w in word]) * promoter_length * len(neg_lines) 61 | for str in pos_lines: 62 | if my_re.search(str): pos_matches += 1 63 | for str in neg_lines: 64 | if my_re.search(str): neg_matches += 1 65 | if (pos_matches > expected_num_pos and neg_matches < expected_num_neg): 66 | print pos_matches, neg_matches, expected_num_pos, expected_num_neg, re_string 67 | -------------------------------------------------------------------------------- /2008/hw1.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | import operator 3 | def rosenbrock(x,y): 4 | return 100*(y - x*x)**2 + (1-x)**2 5 | def gradient(x, y): 6 | return [400*x * (x*x - y) + 2*(x-1) , 200 * (y-x*x)] 7 | def hessian(x,y): 8 | return [[1200*x*x - 400*y, -400*x], [-400*x, 200]] 9 | def dot(l1, l2): 10 | return reduce( operator.add, map( operator.mul, l1, l2)) 11 | def mul(a, list): 12 | return map(lambda x: x*a, list) 13 | def add(l1, l2): 14 | return map(operator.add, l1, l2) 15 | def Mmulv(M, v): 16 | return map(lambda x: dot(v,x), M) 17 | 18 | def inverse(l): 19 | [[a,b], [c,d]] = l 20 | det = a*d-b*c 21 | return [[d/(det), -b/(det)], [-c/(det), a/(det)]] 22 | 23 | def backtrack(f, fk, pk, xk, grad, p, c, alpha): 24 | # dir = c*alpha * dot(grad, pk) 25 | [a,b] = add(xk, mul(alpha, pk)) 26 | if (fk + c*alpha * dot(grad, pk) < f(a,b)): 27 | # print "f(", xk, " + ", alpha, "*", pk, ")", "<", "f", (a,b), "returning", p, "times alpha" 28 | # print fk + c*alpha * dot(grad, pk), " < " ,f(a,b) 29 | return backtrack(f, fk, pk, xk, grad, p, c, alpha*p) 30 | else: 31 | # print "f(", xk, " + ", alpha, "*", pk, ")", ">", "f", (a,b), "ok step size" 32 | # print fk + c*alpha * dot(grad, pk), " > " ,f(a,b) 33 | print "direction is ", pk 34 | print "Step length: ", alpha 35 | return alpha 36 | 37 | def descent(f,x,y): 38 | grad = gradient(x,y) 39 | print "I am at: ", [x,y] 40 | print "Gradient is: ", grad 41 | print "Gradient has size: ", dot(grad, grad) 42 | if dot(grad, grad) < 0.00001: 43 | return [x,y] 44 | else: 45 | pk = mul(-1/sqrt(dot(grad, grad)), grad) 46 | alpha = backtrack(f, f(x,y), pk, [x,y], grad, 0.8, 0.9,1) 47 | [a,b]=add( [x,y], mul(alpha, pk)) 48 | # print "Moving by: ", alpha, " * ", pk, " = ", mul(alpha, pk), "from: ", [x,y], [a,b], add([x,y], mul(alpha, pk)) 49 | return descent(f,a,b) 50 | 51 | def newton(f,x,y): 52 | grad = gradient(x,y); 53 | hess = hessian(x,y); 54 | print "I am at: ", [x,y] 55 | print "Gradient is: ", grad 56 | print "Gradient has size: ", dot(grad, grad) 57 | if dot(grad, grad) < 0.00001: 58 | return [x,y] 59 | else: 60 | pk = mul( -1, Mmulv(inverse(hessian(x,y)), grad)) 61 | alpha = backtrack(f, f(x,y), pk, [x,y], grad, 0.8, 0.9,1) 62 | [a,b]=add( [x,y], mul(alpha, pk)) 63 | return newton(f, a, b) 64 | 65 | print "Steepest descent starting from point (1.2, 1.2): " 66 | descent(rosenbrock, 1.2, 1.2); 67 | print "Steepest descent starting from point (-1.2, 1): " 68 | descent(rosenbrock, -1.2, 1); 69 | print "Newton's method starting from point (1.2, 1.2): " 70 | newton(rosenbrock, 1.2, 1.2); 71 | print "Newton's method starting from point (-1.2, 1): " 72 | newton(rosenbrock, -1.2, 1); 73 | -------------------------------------------------------------------------------- /2008/a.py: -------------------------------------------------------------------------------- 1 | # Change dataset1 to dataset2 to get the results for dataset2 2 | pos = open("dataset1/positive.txt", "r") 3 | neg = open("dataset1/negative.txt", "r") 4 | 5 | nucleotides = ['A', 'C', 'G','T'] 6 | 7 | # consensus sequences are represented as lists of lists of nucleotides. 8 | 9 | def choose2(list): 10 | combinations = [] 11 | for x in list: 12 | for y in list: 13 | if x < y : 14 | combinations.append((x,y)) 15 | return combinations 16 | 17 | def train(pos_list): 18 | num_pos_sites = len(pos_list) 19 | cons_sequence = [] 20 | seq_length = len(pos_list[0]) - 1 21 | for i in range(seq_length): 22 | current_position = [] 23 | for x in nucleotides: 24 | pos_count = 0 25 | for site in pos_list: 26 | if site[i] == x: 27 | pos_count += 1 28 | if pos_count >= num_pos_sites * 0.9: 29 | # then we have a nucleotide that is there 90% of the time 30 | current_position = [x] 31 | if (not current_position): 32 | for (x,y) in choose2(nucleotides): 33 | pos_count = 0 34 | for site in pos_list: 35 | if site[i] == x or site[i] == y: 36 | pos_count += 1 37 | if pos_count >= num_pos_sites * 0.9: 38 | # then we have two nucleotides that are there 90% of the time 39 | current_position = [x,y] 40 | if (not current_position): 41 | # use [ACGT] 42 | current_position = nucleotides 43 | cons_sequence.append(current_position) 44 | return cons_sequence 45 | 46 | def predict(consensus_sequence, site): 47 | for i in range(len(consensus_sequence)): 48 | if not (site[i] in consensus_sequence[i]): 49 | return 0 50 | else: 51 | return 1 52 | 53 | pos_sites = pos.readlines() 54 | true_pos = 0 55 | false_neg = 0 56 | for i in range(len(pos_sites)): 57 | consensus_sequence = train(pos_sites[:i] + pos_sites[i+1:]) 58 | if predict(consensus_sequence, pos_sites[i]): 59 | true_pos +=1 60 | else: 61 | false_neg +=1 62 | print "True positives: ", true_pos 63 | print "False negatives: ", false_neg 64 | 65 | neg_sites = neg.readlines() 66 | true_neg = 0 67 | false_pos = 0 68 | consensus_sequence = train(pos_sites) 69 | for i in range(len(neg_sites)): 70 | if predict(consensus_sequence, neg_sites[i]): 71 | false_pos +=1 72 | else: 73 | true_neg +=1 74 | print "False positives: ", false_pos 75 | print "True negatives: ", true_neg 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /2006/testcodeshit.java: -------------------------------------------------------------------------------- 1 | 2 | for(int i = 1; i< 30; i++) { 3 | int k = (int)java.lang.Math.pow(2,i); 4 | String l = "" + k; 5 | bigInteger a = new bigInteger(l); 6 | bigInteger b = new bigInteger(l); 7 | long t1 = System.currentTimeMillis(); 8 | bigInteger product=b.iterativeMultiplication( a ); 9 | long t2 = System.currentTimeMillis(); 10 | System.out.println(l + " : " + (t2 - t1)); 11 | } 12 | 13 | 14 | 15 | long t1 = System.currentTimeMillis(); 16 | int tries = 1; 17 | for(int i = 1; i<= tries; i++) { 18 | a = bigInteger.getRandom( 8 ); 19 | b = bigInteger.getRandom( 8 ); 20 | a.iterativeMultiplication(b); 21 | 22 | } 23 | long t2 = System.currentTimeMillis(); 24 | System.out.println(((float)(t2 - t1))/tries); 25 | 26 | 27 | /* This is just an example of how to use various things you'll need 28 | for question 4. You don't need to keep any of the code below if 29 | you don't feel it's necessary. */ 30 | 31 | /* since getRandom is a static member of bigInteger, 32 | it can be called using only the name of the class 33 | ( i.e. without an actual object ) */ 34 | public class testBigInteger { 35 | public static void main( String args[] ) { 36 | bigInteger a = bigInteger.getRandom( 1000 ); 37 | bigInteger b = bigInteger.getRandom( 1000 ); 38 | 39 | long t1 = System.currentTimeMillis(); 40 | bigInteger product=b.recursiveMultiplication( a ); 41 | long t2 = System.currentTimeMillis(); 42 | // System.out.println( a + " * " + b + " = " + product ); 43 | System.out.println( "Recursive: Total time: " + ( t2-t1 ) ); 44 | 45 | t1 = System.currentTimeMillis(); 46 | product=b.standardMultiplication( a ); 47 | t2 = System.currentTimeMillis(); 48 | // System.out.println("Standard: \n" + a + " * " + b + " = " + product ); 49 | System.out.println( "Standard: Total time: " + ( t2-t1 ) ); 50 | 51 | t1 = System.currentTimeMillis(); 52 | product=b.recursiveFastMultiplication( a ); 53 | t2 = System.currentTimeMillis(); 54 | // System.out.println("Recursive Fast: \n" + a + " * " + b + " = " + product ); 55 | System.out.println( "Fast: Total time: " + ( t2-t1 ) ); 56 | 57 | a = new bigInteger(args[0]); 58 | b = new bigInteger(args[1]); 59 | t1 = System.currentTimeMillis(); 60 | product=b.iterativeMultiplication( a ); 61 | t2 = System.currentTimeMillis(); 62 | System.out.println( a + " * " + b + " = " + product ); 63 | System.out.println( "Total time: " + ( t2-t1 ) ); 64 | 65 | 66 | 67 | } 68 | } -------------------------------------------------------------------------------- /2008/look.py: -------------------------------------------------------------------------------- 1 | # This file was *autogenerated* from the file /home/bork/work/sage/look.sage. 2 | from sage.all_cmdline import * # import sage library 3 | def valid_params(n): 4 | list = [] 5 | conferences = [] 6 | for n in range(Integer(1),n): 7 | print n 8 | for k in range(Integer(1),(n+Integer(1))/Integer(2)): 9 | if (k * (k-Integer(1)) < (n-k-Integer(1))): 10 | continue 11 | if is_odd(k*n): # then the graph isn't even regular 12 | continue 13 | for a in range(k-Integer(1)): 14 | if is_odd(k*a): 15 | continue 16 | if (k * (k - a - Integer(1)) % (n-k-Integer(1)) != Integer(0)): # c isn't an integer 17 | continue 18 | c = (k * (k-a-Integer(1)) / (n-k-Integer(1))) 19 | disc = Integer((a-c)**Integer(2) + Integer(4) * (k-c)) 20 | o = (a-c) + sqrt(disc) 21 | t = (a-c) - sqrt(disc) 22 | if (Integer(2)*k + (n-Integer(1)) * (a-c) != Integer(0)) and not (disc.is_square()): 23 | continue 24 | m_theta = Integer(1)/Integer(2) * ((n-Integer(1)) - (Integer(2)*k + (n-Integer(1))*(a-c)) / disc.sqrt()) 25 | m_tau = Integer(1)/Integer(2) * ((n-Integer(1)) + (Integer(2)*k + (n-Integer(1))*(a-c)) / disc.sqrt()) 26 | if (Integer(2)*k + (n-Integer(1)) * (a-c) == Integer(0)): 27 | m_theta = (n-Integer(1))/Integer(2) 28 | m_tau = (n-Integer(1))/Integer(2) 29 | if (m_theta.is_integral()): 30 | conferences.append((n,k,a,c,o, t)) 31 | continue 32 | if not ( m_theta.is_integral()): 33 | continue 34 | list.append((n,k,a,c,o, t)) 35 | return (list, conferences) 36 | 37 | def non_conf(r): 38 | list = [] 39 | for n in range(Integer(1),r): 40 | for k in range(Integer(1),(n+Integer(1))/Integer(2)): 41 | if (k * (k-Integer(1)) < (n-k-Integer(1))): 42 | continue 43 | if is_odd(k*n): 44 | continue 45 | for o in range(Integer(1),k): 46 | if ( ((-k*o - k*n + k**Integer(2)) % ((n-Integer(1)) * o + k) ) != Integer(0)): 47 | continue # tau isn't integral 48 | t = ((-k*o - k*n + k**Integer(2)) / ((n-Integer(1)) * o + k)) 49 | if (k*(k-t) * (t+Integer(1)) %( (k+o*t) * (t-o)) != Integer(0)): 50 | continue # m_theta isn't integral 51 | m_theta = k*(k-t) * (t+Integer(1)) / (k+o*t) / (t-o) 52 | c = k+o*t 53 | a = o + t + c 54 | if (k == (n-Integer(1))/Integer(2) and c == k/Integer(2) and a == c-Integer(1)): 55 | continue 56 | if (a < Integer(0)): 57 | continue 58 | list.append(dict(a=a, k=k, n=n, c=c, theta = o, tau = t)) 59 | return list 60 | 61 | def is_odd(c): 62 | return (c % Integer(2) == Integer(1)) 63 | 64 | def is_krein((n,k,a,c)): 65 | disc = Integer((a-c)**Integer(2) + Integer(4) * (k-c)) 66 | o = ((a-c) + disc.sqrt()) / Integer(2) 67 | t = ((a-c) - disc.sqrt()) / Integer(2) 68 | if (o*t**Integer(2) - Integer(2)*o**Integer(2)*t - o**Integer(2) - k*o + k*t**Integer(2) + Integer(2)*k*t < Integer(0)): 69 | return Integer(0) 70 | if (t*o**Integer(2) - Integer(2)*t**Integer(2)*o - t**Integer(2) - k*t + k*o**Integer(2) + Integer(2)*k*o < Integer(0)): 71 | return Integer(0) 72 | return Integer(1) 73 | 74 | 75 | -------------------------------------------------------------------------------- /2009/check.py: -------------------------------------------------------------------------------- 1 | import math 2 | import sys 3 | inStr = open(sys.argv[-2]).read() 4 | solutionFile = open(sys.argv[-1]) 5 | lines = inStr.split('\n') 6 | del lines[-1] 7 | print lines 8 | names = [line.split()[0] for line in lines] 9 | nameToNum = dict(zip(names, range(len(names)))) 10 | 11 | fields = ["name", "ServingSize", "Calories", "CaloriesFromFat", "TotalFat", "TotalFatPercent", "SaturatedFat", "SaturatedFatPercent", "TransFat", "TransFatPercent", "Cholesterol", "CholesterolPercent", "Sodium", "SodiumPercent", "TotalCarbs", "TotalCarbsPercent", "DietaryFiber", "DietaryFiberPercent", "Sugars", "SugarsPercent", "Protein", "VitaminA", "VitaminC", "Calcium", "Iron", "isFruitVeg", "isDairy", "isCereal", "isMeat", "Price"] 12 | 13 | foodValues = {} 14 | 15 | def f(x): 16 | if x.startswith("-"): 17 | return "0" 18 | else: 19 | return x 20 | for line in lines: 21 | values = dict(zip(fields, line.split())) 22 | name = values["name"] 23 | id = nameToNum[name] 24 | foodValues[id] = {} 25 | foodValues[id]["name"] = name 26 | del values["name"] 27 | for i in values.keys(): 28 | foodValues[id][i] = float(f(values[i])) 29 | 30 | solutionPairs = [] 31 | for line in solutionFile.read().split('\n'): 32 | sLine = line.split() 33 | solutionPairs.append((int(sLine[0]), float(sLine[1]))) 34 | 35 | score = 1000 36 | calories = 0 37 | caloriesFromFat = 0 38 | proteins = 0 39 | dietaryFiber = 0 40 | fruitPortions = 0 41 | dairyPortions = 0 42 | cerealPortions = 0 43 | meatPortions = 0 44 | transFat = 0 45 | saturatedFat = 0 46 | 47 | fields2 = [x for x in fields if x != "name"] 48 | 49 | totals = dict(zip(fields2, [0 for i in range(len(fields2))])) 50 | 51 | for p in solutionPairs: 52 | for f in fields2: 53 | totals[f] += p[1] * foodValues[p[0]][f] 54 | 55 | print totals 56 | score -= abs(totals["Calories"] - 2000) 57 | if totals["CaloriesFromFat"]/totals["Calories"]*100 > 25: 58 | score -= 5 *float(totals["CaloriesFromFat"])/totals["Calories"] - 25 59 | score -= 2 * abs(totals["Protein"] - 100) 60 | score -= 3 * abs(totals["DietaryFiber"] - 20) 61 | "isFruitVeg", "isDairy", "isCereal", "isMeat" 62 | if totals["isFruitVeg"] < 6: 63 | score -= 50*abs(6-totals["isFruitVeg"]) 64 | elif totals["isFruitVeg"] > 6: 65 | score -= 20*abs(6-totals["isFruitVeg"]) 66 | if totals["isCereal"] < 6: 67 | score -= 50*abs(6-totals["isCereal"]) 68 | elif totals["isCereal"] > 6: 69 | score -= 20*abs(6-totals["isCereal"]) 70 | if totals["isMeat"] < 2: 71 | score -= 50*abs(2-totals["isMeat"]) 72 | elif totals["isMeat"] > 2: 73 | score -= 20*abs(2-totals["isMeat"]) 74 | if totals["isDairy"] < 2: 75 | score -= 50*abs(2-totals["isDairy"]) 76 | elif totals["isDairy"] > 2: 77 | score -= 20*abs(2-totals["isDairy"]) 78 | score -= 2* (totals["TransFat"]+totals["SaturatedFat"]) 79 | print "SOLUTION: %s" % map(lambda x: (foodValues[x[0]]["name"],x[1]), solutionPairs) 80 | print "SCORE: %s" % score 81 | 82 | "VitaminA", "VitaminC", "Calcium", "Iron" 83 | if not totals["VitaminA"] >= 100: 84 | print totals["VitaminA"] 85 | print "BAD: does not satisfy vitamin A" 86 | if not totals["VitaminC"] >= 100: 87 | print "BAD: does not satisfy vitamin C" 88 | if not totals["Calcium"] >= 100: 89 | print "BAD: does not satisfy calcium" 90 | if not totals["Iron"] >= 100: 91 | print "BAD: does not satisfy iron" 92 | if not len(solutionPairs) <= 10: 93 | print "BAD: too many ingredients!" 94 | if not totals["Price"] <= 1500: 95 | print "BAD: too expensive!" 96 | print totals["Price"] 97 | -------------------------------------------------------------------------------- /2006/old.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.lang.Exception; 4 | 5 | public class expressionEvaluator { 6 | /* This method evaluates the given arithmetic expression and returns 7 | * its Integer value. The method throws an Exception if the expression 8 | * is malformed.*/ 9 | 10 | static String evaluate( String expr ) throws Exception { 11 | expr.replaceAll(" ", ""); 12 | int open, close; 13 | open = close = 1; 14 | while(close != 0) { 15 | open = close = 0; 16 | for (int i = 0; i <=expr.length()-1; i++) { 17 | if (String.valueOf(expr.charAt(i)).equals("(")) 18 | open = i; 19 | if (String.valueOf(expr.charAt(i)).equals(")")) { 20 | close = i; 21 | if (open + 1 >= close) 22 | throw new Exception("Empty brackets"); 23 | expr = expr.substring(0, open) + evalSimple(expr.substring(open+1, close ))+ expr.substring(close + 1, expr.length()); 24 | break; 25 | } 26 | } 27 | 28 | } 29 | if (open != 0) 30 | throw new Exception("Unmatched bracket"); 31 | String val = evalSimple(expr); 32 | if (val.substring(1,2).equals("-")) 33 | return val.substring(1,val.length()); 34 | else 35 | return val; 36 | } // end of evaluate 37 | private static String evalSimple( String expr ) throws Exception { 38 | try { 39 | new Integer(expr); // if expr is just an integer, return it, otherwise continue 40 | return expr; 41 | } 42 | catch(NumberFormatException e) {} 43 | System.out.println("Evaluating expression: " + expr); 44 | String delimiters="+-*%()"; 45 | StringTokenizer nums = new StringTokenizer( expr , delimiters , false ); 46 | StringTokenizer ops = new StringTokenizer ( expr, "0123456789", false ); 47 | if (nums.hasMoreElements() == false || ops.hasMoreElements() == false) 48 | throw new Exception("Not enough operators or numbers"); 49 | int value = Integer.parseInt(nums.nextToken()); // holds the value so far 50 | if (nums.countTokens() != ops.countTokens()) 51 | throw new Exception("Wrong amount of operators and/or numbers: "+ nums.countTokens() + " vs " + ops.countTokens()); 52 | while(nums.hasMoreElements() && ops.hasMoreElements()) { 53 | String op = ops.nextToken(); 54 | if (op.equals("*")) 55 | value *= Integer.parseInt(nums.nextToken()); 56 | else if (op.equals("+")) 57 | value += Integer.parseInt(nums.nextToken()); 58 | else if (op.equals("%")) 59 | value = value / Integer.parseInt(nums.nextToken()); 60 | else if (op.equals("-")) 61 | value -= Integer.parseInt(nums.nextToken()); 62 | else 63 | throw new Exception(op + ": Not a valid operator"); 64 | } 65 | if (value >= 0) 66 | return String.valueOf(value); 67 | else 68 | return "0-" + String.valueOf(-value); 69 | } 70 | 71 | 72 | 73 | /* This method repeatedly asks the user for an expression and evaluates it. 74 | The loop stops when the user enters an empty expression */ 75 | public void queryAndEvaluate() throws Exception { 76 | String line; 77 | BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) ); 78 | System.out.println("Enter an expression"); 79 | line = stdin.readLine(); 80 | 81 | while ( line.length() > 0 ) { 82 | try { 83 | String value = evaluate( line ); 84 | System.out.println("value = " + value ); 85 | } 86 | catch (Exception e) 87 | { 88 | System.out.println(e.toString()); 89 | } 90 | System.out.println( "Enter an expression" ); 91 | line = stdin.readLine(); 92 | } // end of while loop 93 | } // end of query and evaluate 94 | 95 | public static void main(String args[]) throws Exception { 96 | expressionEvaluator e=new expressionEvaluator(); 97 | e.queryAndEvaluate(); 98 | } // end of main 99 | } 100 | -------------------------------------------------------------------------------- /2005/chain.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use Chaos; 3 | chdir "blog"; 4 | use strict; 5 | #use warnings; 6 | use CGI qw/:standard/; 7 | open CONF, "conf"; 8 | chomp(my ($glob_pass, $database_name, $username, $password) = ); 9 | close CONF; 10 | my $loc = "http://".$ENV{'HTTP_HOST'}.$ENV{'SCRIPT_NAME'}; 11 | my $blog = new Chaos(username=>$username, password=>$password, scriptloc=>$loc, database => $database_name); 12 | 13 | print header; 14 | my @path = split(m:/:,path_info); 15 | shift(@path); 16 | 17 | my $first = shift(@path); 18 | 19 | if ($first eq "tags") { 20 | my $tag = shift(@path); 21 | if($tag ne "") { 22 | my @entries = $blog->entries($tag); 23 | put ("", "", "None tagged with $tag") unless @entries; 24 | my $titles; 25 | foreach my $entry (@entries) { 26 | my $title = $entry->title; 27 | my $id = $entry->id; 28 | $titles.= "$title
\n"; 29 | } 30 | put ($tag, [], $titles); 31 | } else { 32 | my $tags; 33 | foreach ($blog->tags) { 34 | my $tag = $_; 35 | $tags.="$tag
\n"; 36 | } 37 | put( "tags", [], $tags); 38 | } 39 | } 40 | 41 | elsif ($first eq "id") { 42 | my $id = shift(@path); 43 | if ($id =~/^\d+$/) { 44 | my $entry = $blog->entry($id); 45 | if($entry->title) { 46 | my @tags = $entry->tags; 47 | put($entry->title, \@tags, $entry->html); 48 | } else { 49 | put("Invalid ID", [], "No entry exists with id $id. Try again?"); 50 | } 51 | } else { 52 | my @entries = $blog->entries; 53 | my $html; 54 | foreach (@entries) { 55 | my $id = $_->id; 56 | my $title = $_->title; 57 | $html.=qq^$id: $title
^ 58 | } 59 | put ("All entries", [], $html); 60 | 61 | } 62 | } 63 | 64 | elsif ($first eq "add") { 65 | if(param('text')) { 66 | my $password = param('password'); 67 | my $title = param('title'); 68 | my $text = param('text') ; 69 | my @tags = split(/\s*,\s*/, param('tags')); 70 | if ($password eq $glob_pass) { 71 | my $entry = $blog->add( text=> $text, 72 | title=> $title, 73 | tags=> \@tags, 74 | ); 75 | } else { 76 | put ("Incorrect password", [], "Password \"$password\" incorrect."); 77 | } 78 | # put($title, \@tags, $entry->html); 79 | } else { 80 | my $html = file("add.html"); 81 | put("add entry", [], $html); 82 | } 83 | } 84 | 85 | elsif ($first eq "edit") { 86 | my $id = (shift(@path) || param('id')); 87 | if($id=~/^\d+$/) { 88 | unless (param('text')) { 89 | my $entry = $blog->entry($id); 90 | my $title = $entry->title; 91 | my $text = $entry->text; 92 | my @tags = $entry->tags; 93 | my $tags = join(", ", @tags); 94 | my $html = file("edit.html", $title, $tags, $text, $id); 95 | put("editing $title", \@tags, $html); 96 | } else { 97 | my $text = param('text'); 98 | my $password = param('password'); 99 | my $title = param('title'); 100 | my @tags = split(/\s*,\s*/, param('tags')); 101 | if ($password eq $glob_pass) { 102 | my $entry = $blog->edit(text=>$text, 103 | title=>$title, 104 | tags=> \@tags, 105 | id=>$id 106 | ); 107 | put("entry edited: ". $entry->title, \@tags, $entry->html); 108 | } else { 109 | put ("Incorrect password", [], "Password $password incorrect."); 110 | } 111 | } 112 | } else { 113 | put("edit entry?", [], file("add.html")); 114 | } 115 | } 116 | else { 117 | my @tags = $blog->tags; 118 | put("Hello!", \@tags, "Here's a chain of random thought. Welcome."); 119 | } 120 | 121 | sub put { 122 | my ($title, $tag, $content) = @_; 123 | my $tags; 124 | foreach(@{$tag}) { 125 | my $url = "$loc/tags/$_"; 126 | # $tags.="$_"; 127 | # $tags.="
  • $_
  • " 128 | # $tags.=qq^:: $_
    ^ 129 | $tags.=""; 130 | } 131 | 132 | my $file = "look.html"; 133 | open(FIL, "< $file"); 134 | my $temp = join("\n", ); 135 | close FIL; 136 | $temp =~s/(\$\w+(?:::)?\w*)/"defined $1 ? $1 : ''"/gee; 137 | print $temp; 138 | } 139 | 140 | sub file { 141 | my $file = shift; 142 | my ($title, $tags, $text, $id) = @_; 143 | open (DAT, "< $file") || print "failed"; 144 | my @blah = ; 145 | close DAT; 146 | my $temp = join("\n", @blah); 147 | $temp =~s/(\$\w+(?:::)?\w*)/"defined $1 ? $1 : ''"/gee; 148 | return $temp; 149 | } 150 | 151 | -------------------------------------------------------------------------------- /2008/test.py: -------------------------------------------------------------------------------- 1 | import sgmllib 2 | from datetime import date 3 | 4 | def sum_values(trnlist): 5 | return sum([trn.amount for trn in trnlist]) 6 | 7 | def strip_transfers(trnlist): 8 | return filter(lambda x: not(x.sibling), trnlist) 9 | 10 | def amalgamate(account_list): 11 | a = Account() 12 | for j in account_list: 13 | a.combine(j) 14 | return a 15 | 16 | def sep_month(trnlist): 17 | h = {} 18 | for trn in trnlist: 19 | month = trn.date.month 20 | if not h.has_key(month): 21 | h[month] = [] 22 | h[month].append(trn) 23 | return h 24 | 25 | def label_transfers(accountlist): 26 | for account in accountlist[0:-1]: 27 | for otheracct in accountlist[accountlist.index(account)+1:]: 28 | for trn1 in account.trns: 29 | for trn2 in otheracct.trns: 30 | if (abs((trn1.date - trn2.date).days) < 2 and trn1.amount == -trn2.amount): 31 | # these probably go together. 32 | trn1.sibling = trn2 33 | trn2.sibling = trn1 34 | 35 | def overall_by_month(account): 36 | by_month(account, lambda x: True) 37 | 38 | def spending_by_month(account): 39 | by_month(account, lambda x: x.amount < 0) 40 | 41 | def earnings_by_month(account): 42 | by_month(account, lambda x: x.amount > 0) 43 | 44 | def by_month(account, f): 45 | t = strip_transfers(account.trns) 46 | h = sep_month(t) 47 | print h 48 | for month in h: 49 | print month, sum_values([ x for x in h[month] if f(x)]) 50 | 51 | 52 | def print_trns(trns): 53 | for i in range(len(trns)): 54 | print "%3d: %s" % (i, trns[i].to_string()) 55 | 56 | class Transaction: 57 | def __init__(self): 58 | self.type = "POS" 59 | self.amount = 0 60 | self.name = "Transaction" 61 | self.memo = "" 62 | self.id = 0 63 | self.date = '20000000' 64 | self.sibling = None 65 | self.account = None 66 | self.tags = [] 67 | def to_string(self): 68 | if (self.amount > 0): 69 | amt = "+$%s" % self.amount 70 | else: 71 | amt = "-$%s" % abs(self.amount) 72 | return "%8s, %-10s, %-25s, %s" % (self.date, amt, self.name, self.memo) 73 | 74 | class Account: 75 | def __init__(self): 76 | self.trns = [] 77 | self.bankid = 0 78 | self.id = 0 79 | self.start_date = 0 80 | self.end_date = 0 81 | self.balance = 0 82 | self.type = 0 83 | def combine(self, acct): 84 | self.balance += acct.balance 85 | self.trns.extend(acct.trns) 86 | self.trns.sort(key = lambda x: x.date) 87 | def list(self): 88 | for i in range(len(self.trns)): 89 | print "%3d: %s" % (i, self.trns[i].to_string()) 90 | def description(self): 91 | return "%s account, id %s, with balance %s" % (self.type, self.id, self.balance) 92 | 93 | class ofxparser(sgmllib.SGMLParser): 94 | def start_ofx(self, data): 95 | self.accounts = [] 96 | 97 | def start_stmttrn(self, data): 98 | self.curtrn = Transaction() 99 | self.curtrn.account = self.curacct 100 | 101 | def end_stmttrn(self): 102 | self.curacct.trns.append(self.curtrn) 103 | 104 | def start_bankacctfrom(self, data): 105 | self.curacct = Account() 106 | 107 | def start_ledgerbal(self, data): 108 | pass 109 | def start_ccacctfrom(self, data): 110 | self.curract = Account() 111 | self.curacct.type = "Credit Card" 112 | def end_ledgerbal(self): 113 | self.accounts.append(self.curacct) 114 | self.curacct = Account() 115 | def parse(self, filename): 116 | self.feed(open(filename).read()) 117 | self.close() 118 | return self.accounts 119 | 120 | def handle_data(self, data): 121 | data = data.strip() 122 | if not (data and self.get_starttag_text()): 123 | return 124 | tag = self.get_starttag_text()[1:-1].lower() 125 | if (tag == "trntype"): 126 | self.curtrn.type = data 127 | elif (tag == "trnamt"): 128 | self.curtrn.amount = float(data) 129 | elif (tag == "name"): 130 | self.curtrn.name = data 131 | elif (tag == "memo"): 132 | self.curtrn.memo = data 133 | elif (tag == "fitid"): 134 | self.curtrn.id = data 135 | elif (tag == "dtposted"): 136 | self.curtrn.date = date(int(data[0:4]), int(data[4:6]), int(data[6:8])) 137 | elif (tag == "bankid"): 138 | self.curacct.bankid = data 139 | elif (tag == "acctid"): 140 | self.curacct.id = data 141 | elif (tag == "dtstart"): 142 | self.curacct.start_date = data 143 | elif (tag == "dtend"): 144 | self.curacct.end_date = data 145 | elif (tag == "balamt"): 146 | self.curacct.balance = float(data) 147 | elif (tag == 'accttype'): 148 | self.curacct.type = data.capitalize() 149 | else: 150 | pass 151 | parser = ofxparser() 152 | acctlist = parser.parse('ofx50081.qfx') 153 | label_transfers(acctlist) 154 | #acctlist = parser.parse('ofx24986.ofx') 155 | -------------------------------------------------------------------------------- /2008/draw_graph.py: -------------------------------------------------------------------------------- 1 | import os,sys 2 | 3 | f = os.popen("gnuplot", "w") 4 | 5 | dataset = sys.argv[1] 6 | x_num = sys.argv[2] 7 | 8 | f.write(""" 9 | #!/usr/bin/gnuplot -persist 10 | # 11 | # 12 | # G N U P L O T 13 | # Version 4.2 patchlevel 2 14 | # last modified 31 Aug 2007 15 | # System: Linux 2.6.24-19-generic 16 | # 17 | # Copyright (C) 1986 - 1993, 1998, 2004, 2007 18 | # Thomas Williams, Colin Kelley and many others 19 | # 20 | # Type `help` to access the on-line reference manual. 21 | # The gnuplot FAQ is available from http://www.gnuplot.info/faq/ 22 | # 23 | # Send bug reports and suggestions to 24 | # 25 | # set terminal wxt 0 26 | set out "dx%i_%i.ps" """ % (x_num, dataset) 27 | """ 28 | set terminal postscript portrait enhanced "Helvetica" 14 29 | unset clip points 30 | set clip one 31 | unset clip two 32 | set bar 1.000000 33 | set border 31 front linetype -1 linewidth 1.000 34 | set xdata 35 | set ydata 36 | set zdata 37 | set x2data 38 | set y2data 39 | set timefmt x "%d/%m/%y,%H:%M" 40 | set timefmt y "%d/%m/%y,%H:%M" 41 | set timefmt z "%d/%m/%y,%H:%M" 42 | set timefmt x2 "%d/%m/%y,%H:%M" 43 | set timefmt y2 "%d/%m/%y,%H:%M" 44 | set timefmt cb "%d/%m/%y,%H:%M" 45 | set boxwidth 46 | set style fill empty border 47 | set style rectangle back fc lt -3 fillstyle solid 1.00 border -1 48 | set dummy x,y 49 | set format x "% g" 50 | set format y "% g" 51 | set format x2 "% g" 52 | set format y2 "% g" 53 | set format z "% g" 54 | set format cb "% g" 55 | set angles radians 56 | unset grid 57 | set key title "" 58 | set key inside right top vertical Right noreverse enhanced autotitles nobox 59 | set key noinvert samplen 4 spacing 1 width 0 height 0 60 | unset label 61 | unset arrow 62 | set style increment default 63 | unset style line 64 | unset style arrow 65 | set style histogram clustered gap 2 title offset character 0, 0, 0 66 | unset logscale 67 | set offsets 0, 0, 0, 0 68 | set pointsize 1 69 | set encoding default 70 | unset polar 71 | unset parametric 72 | unset decimalsign 73 | set view 60, 30, 1, 1 74 | set samples 100, 100 75 | set isosamples 10, 10 76 | set surface 77 | unset contour 78 | set clabel '%8.3g' 79 | set mapping cartesian 80 | set datafile separator whitespace 81 | unset hidden3d 82 | set cntrparam order 4 83 | set cntrparam linear 84 | set cntrparam levels auto 5 85 | set cntrparam points 5 86 | set size ratio 0 1,1 87 | set origin 0,0 88 | set style data points 89 | set style function lines 90 | set xzeroaxis linetype -2 linewidth 1.000 91 | set yzeroaxis linetype -2 linewidth 1.000 92 | set zzeroaxis linetype -2 linewidth 1.000 93 | set x2zeroaxis linetype -2 linewidth 1.000 94 | set y2zeroaxis linetype -2 linewidth 1.000 95 | set ticslevel 0.5 96 | set mxtics default 97 | set mytics default 98 | set mztics default 99 | set mx2tics default 100 | set my2tics default 101 | set mcbtics default 102 | set xtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 103 | set xtics autofreq 104 | set ytics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 105 | set ytics autofreq 106 | set ztics border in scale 1,0.5 nomirror norotate offset character 0, 0, 0 107 | set ztics autofreq 108 | set nox2tics 109 | set noy2tics 110 | set cbtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 111 | set cbtics autofreq 112 | set title \" """ + "Dataset %i, x = %i" % (dataset, x_num) + """ \" 113 | set title offset character 0, 0, 0 font "" norotate 114 | set timestamp bottom 115 | set timestamp "" 116 | set timestamp offset character 0, 0, 0 font "" norotate 117 | set rrange [ * : * ] noreverse nowriteback # (currently [0.00000:10.0000] ) 118 | set trange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] ) 119 | set urange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] ) 120 | set vrange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] ) 121 | set xlabel "Sensitivity" 122 | set xlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate 123 | set x2label "" 124 | set x2label offset character 0, 0, 0 font "" textcolor lt -1 norotate 125 | set xrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) 126 | set x2range [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) 127 | set ylabel "Specificity" 128 | set ylabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by 90 129 | set y2label "" 130 | set y2label offset character 0, 0, 0 font "" textcolor lt -1 rotate by 90 131 | set yrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) 132 | set y2range [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) 133 | set zlabel "" 134 | set zlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate 135 | set zrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) 136 | set cblabel "" 137 | set cblabel offset character 0, 0, 0 font "" textcolor lt -1 norotate 138 | set cbrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) 139 | set zero 1e-08 140 | set lmargin -1 141 | set bmargin -1 142 | set rmargin -1 143 | set tmargin -1 144 | set locale "C" 145 | set pm3d explicit at s 146 | set pm3d scansautomatic 147 | set pm3d interpolate 1,1 flush begin noftriangles nohidden3d corners2color mean 148 | set palette positive nops_allcF maxcolors 0 gamma 1.5 color model RGB 149 | set palette rgbformulae 7, 5, 15 150 | set colorbox default 151 | set colorbox vertical origin screen 0.9, 0.2, 0 size screen 0.05, 0.6, 0 bdefault 152 | set loadpath 153 | set fontpath 154 | set fit noerrorvariables 155 | GNUTERM = "wxt" 156 | """ + "plot \"dx%i_%i.txt\" % (x_num, dataset) 157 | ) 158 | -------------------------------------------------------------------------------- /2006/expressionEvaluator.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class expressionEvaluator { 5 | 6 | static String evaluate( String expr ) throws Exception { return eval(expr,false); } 7 | static String evaluatePriority( String expr ) throws Exception { return eval(expr,true); } 8 | 9 | /* This method evaluates the given arithmetic expression and returns 10 | * its Integer value. The method throws an exception if the expression 11 | * is malformed. 12 | * if smart == true, evaluates with normal priority 13 | * if smart == false, evaluates with left-to-right priority*/ 14 | static String eval( String expr , boolean smart) throws Exception { 15 | Stack tokens = new Stack(); 16 | StringTokenizer tok = new StringTokenizer( expr , "+-*%()", true ); // get the entire expression 17 | while (tok.hasMoreTokens()) { 18 | String cur = tok.nextToken(); 19 | if (cur.equals(")")) { /* if we find the end of a parenthesis group, replace the group 20 | with the value of the expression it contains */ 21 | Stack nums = new Stack(); 22 | Stack ops = new Stack(); 23 | while (tokens.peek().equals("(") == false) { 24 | String str = tokens.pop().toString(); 25 | // sort the tokens into two stacks 26 | if (str.equals("*") || str.equals("-") || str.equals("+") || str.equals("%")) 27 | ops.push(str); 28 | else 29 | nums.push(str); 30 | } 31 | tokens.pop(); // take off the "(" too 32 | tokens.push(evalSimple(nums,ops,smart)); // push the value of the expression onto the stack 33 | } 34 | else 35 | tokens.push(cur); 36 | 37 | } 38 | Stack nums = new Stack(); 39 | Stack ops = new Stack(); 40 | while (tokens.empty() == false) { 41 | String str = tokens.pop().toString(); 42 | if (str.equals("*") || str.equals("-") || str.equals("+") || str.equals("%") || str.equals("/")) 43 | ops.push(str); 44 | else 45 | nums.push(str); 46 | } 47 | return evalSimple(nums,ops,smart); 48 | } // end of eval 49 | 50 | /* This method takes two stacks of numbers and operators, and returns a String containing the result, 51 | * throwing an exception if the expression is malformed 52 | * if smart == true, evaluates with normal priority 53 | * if smart == false, evaluates with left-to-right priority*/ 54 | private static String evalSimple (Stack nums, Stack ops, boolean smart) throws Exception { 55 | int value = Integer.parseInt(nums.pop().toString()); 56 | if (nums.size() != ops.size()) 57 | throw new Exception("Too many or too few operators"); 58 | if (nums.empty()) // if the expression is just a number, return it 59 | return String.valueOf(value); 60 | while(nums.empty() == false && ops.empty() == false) { 61 | String op = ops.pop().toString(); 62 | int num = Integer.parseInt(nums.pop().toString()); 63 | if (smart == true) { // only do this is we're evaluating with normal priority 64 | /* If the next n operations exist and are multiplication or a division, do them first */ 65 | if (op.equals("%") == false) { // but integer division doesn't commute, so always do that first 66 | while((ops.empty() == false) && (ops.peek().toString().equals("*") || ops.peek().toString().equals("%"))) { 67 | int nextnum = Integer.parseInt(nums.pop().toString()); 68 | String nextop = ops.pop().toString(); 69 | num = evalBinary(num, nextop, nextnum); 70 | } 71 | } 72 | } 73 | value = evalBinary(value, op, num); 74 | } 75 | return String.valueOf(value); 76 | } // end of evalSimple 77 | 78 | /* returns the result of a simple binary operation, given num1 op num2*/ 79 | private static int evalBinary(int num1, String op, int num2) throws Exception { 80 | if (op.equals("*")) 81 | return num1 * num2; 82 | else if (op.equals("+")) 83 | return num1 + num2; 84 | else if (op.equals("%")) 85 | return num1 / num2; 86 | else if (op.equals("-")) 87 | return num1 - num2; 88 | else 89 | throw new Exception(op + ": Not a valid operator"); 90 | } // end of evalBinary 91 | 92 | /* This method repeatedly asks the user for an expression and evaluates it. 93 | The loop stops when the user enters an empty expression */ 94 | public void queryAndEvaluate() throws Exception { 95 | String line; 96 | BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) ); 97 | System.out.println("Enter an expression"); 98 | line = stdin.readLine(); 99 | while ( line.length() > 0 ) { 100 | try { 101 | String value = evaluate( line ); 102 | System.out.println("Fake value = " + value ); 103 | System.out.println("Actual value = " + evaluatePriority( line )); 104 | } 105 | catch (Exception e) 106 | { 107 | System.out.println("Malformed Expression"); 108 | } 109 | System.out.println( "Enter an expression" ); 110 | line = stdin.readLine(); 111 | } // end of while loop 112 | } // end of query and evaluate 113 | 114 | public static void main(String args[]) throws Exception { 115 | expressionEvaluator e=new expressionEvaluator(); 116 | e.queryAndEvaluate(); 117 | } // end of main 118 | 119 | } 120 | -------------------------------------------------------------------------------- /2009/working-traffic.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | import pygame 3 | import random 4 | from copy import deepcopy 5 | from pygame.locals import * 6 | 7 | YIELD = 1 8 | LIGHT = 2 9 | OUT = 3 10 | IN = 4 11 | maxSpeed = 7 12 | numInBranches = 10 13 | numOutBranches = 3 14 | 15 | branchLength = 100 16 | trackLength = 100 17 | 18 | inBranchLocations = random.sample(range(trackLength), numInBranches) 19 | outBranchLocations = random.sample(range(trackLength), numOutBranches) 20 | 21 | inBranches = [] 22 | outBranches = [] 23 | 24 | cars = [] 25 | factories = [] 26 | 27 | 28 | class Tile: 29 | def __init__(self, track, index): 30 | self.tags = [] # (YIELD, inside/outside), LIGHT, OUT, IN 31 | self.car = None 32 | self.inBranches = [] 33 | self.outBranches = [] 34 | self.next = None 35 | self.prev = None 36 | self.track = track 37 | self.index = index 38 | 39 | class Track(object): 40 | def __init__(self, length): 41 | self.tiles = [Tile(self, i) for i in range(trackLength)] 42 | self.length = length 43 | self.start = self.tiles[0] 44 | self.end = self.tiles[-1] 45 | for t in range(len(self.tiles)): 46 | if t < len(self.tiles)-1: 47 | self.tiles[t].next = self.tiles[t+1] 48 | if t > 0: 49 | self.tiles[t].prev = self.tiles[t-1] 50 | 51 | class Circle(Track): 52 | def __getitem__(self,n): 53 | return self.tiles[n % self.length] 54 | 55 | class InBranch(Track): 56 | def __getitem__(self,n): 57 | if n >= self.length: 58 | return self.branchPt 59 | else: 60 | return self.tiles[n] 61 | def __init__(self, length, branchPt): 62 | self.branchPt = branchPt 63 | super(InBranch, self).__init__(length) 64 | 65 | class Car: 66 | def __init__(self, tile, dest): 67 | self.speed = 0 68 | self.tile = tile 69 | self.destination = dest 70 | self.nextLocation = None 71 | self.colour = random.choice([(255,0,0), (200,0,0), (150,0,0), (150,0,150)]) 72 | # self.acceleration = 10 73 | def update(self): 74 | # set nextLocation 75 | track = self.tile.track 76 | trackLength = track.length 77 | nextCar = None 78 | for dist in range(1, self.speed * (self.speed + 1) / 2): 79 | j = (dist + self.tile.index) % (trackLength) 80 | if (track[j].car): 81 | print j, trackLength, self.tile.index 82 | nextCar = track[j].car 83 | break 84 | #if (track[j].car.location != (dist + self.location) % trackLength): 85 | #print "car has the wrong location!" 86 | #if (self.speed*(self.speed+1)/2 >= track[j].car.speed * (track[j].car.speed + 1)/2 + dist): 87 | #print "oh no!" 88 | if nextCar == None: 89 | if self.speed < maxSpeed: 90 | self.speed += 1 91 | else: 92 | if (self.speed*(self.speed+1)/2 >= nextCar.speed*(nextCar.speed - 1)/2 + dist+1): 93 | self.speed = self.speed - 1 94 | #print 1,self.speed, dist, track[j].car.speed 95 | elif ((self.speed + 2)*(self.speed+1)/2 < nextCar.speed*(nextCar.speed - 1)/2 + dist+1): 96 | self.speed = self.speed + 1 97 | #print 2,self.speed, dist, nextCar.speed 98 | #else: 99 | #print 3,self.speed, dist, nextCar.speed 100 | 101 | 102 | self.nextLocation = self.tile.track[(self.tile.index + self.speed)] 103 | print self.tile == self.nextLocation 104 | 105 | 106 | 107 | def destFactory(): 108 | while 1: 109 | print "dest" 110 | yield random.choice(inBranches) 111 | 112 | 113 | 114 | def newCar(location, dest): 115 | car = Car(location, dest) 116 | cars.append(car) 117 | location.car = car 118 | 119 | 120 | def carFactory(rate, start, destGen): 121 | while 1: 122 | if random.random() < rate: 123 | newcar = newCar(start, destGen.next()) 124 | yield newcar 125 | else: 126 | yield None 127 | 128 | def createInBranches(inBranchLocations): 129 | for loc in inBranchLocations: 130 | track = InBranch(branchLength, loc) 131 | inBranches.append(track) 132 | factory = carFactory(0.1, track.start, destFactory()) 133 | factories.append(factory) 134 | track.end.next = loc 135 | loc.inBranches.append(track) 136 | 137 | 138 | 139 | circle = Circle(trackLength) 140 | createInBranches(map(lambda x: circle[x], inBranchLocations)) 141 | newCar(circle.start, None) 142 | 143 | 144 | 145 | #for loc in inBranchLocations: 146 | # track = Track(branchLength) 147 | # for i in range(track.length): 148 | # if (random.random() > 0.8): 149 | # track[i].car = Car(track[i]) 150 | # track[i].car.location = i 151 | # circle[loc].inBranches.append(track) 152 | #for loc in outBranchLocations: 153 | # circle[loc].outBranches.append(Track(branchLength)) 154 | 155 | 156 | #for tile in circle: 157 | # if (random.random() > 0.7): 158 | # tile.car = Car(tile) 159 | # tile.car.location = tile.location 160 | 161 | 162 | def update(): 163 | for car in cars: 164 | car.update() 165 | for car in cars: 166 | car.tile.car = None 167 | car.tile = car.nextLocation 168 | car.tile.car = car 169 | for factory in factories: 170 | factory.next() 171 | print "updated!" 172 | 173 | 174 | def drawTrack(track, horiz, startPoint, screen): 175 | (x0,y0) = startPoint 176 | if (track in inBranches): 177 | perm = lambda x, y: (x0 + (5 * track.length - (x - x0)) , y) 178 | elif (horiz): 179 | perm = lambda x, y: (x, y) 180 | else: 181 | perm = lambda x, y: (y, x) 182 | for i in range(track.length): 183 | if (track[i].car): 184 | pygame.draw.line(screen, track[i].car.colour, perm(x0 + 5*i, y0), perm(x0 + 5*i+3, y0)) 185 | # pygame.draw.line(screen, track[i].car.colour, perm(x0 + 5*i, y0+1), perm(x0 + 5*i+3, y0+1)) 186 | 187 | 188 | def draw(screen): 189 | drawTrack(circle, False, (8,9), screen) 190 | for i in range(trackLength): 191 | for branch in circle[i].inBranches: 192 | drawTrack(branch, True, (11, 5*i), screen) 193 | for branch in circle[i].outBranches: 194 | drawTrack(branch, True, (11, 5*i), screen) 195 | pygame.display.flip() 196 | 197 | 198 | def main(): 199 | pygame.init() 200 | screen = pygame.display.set_mode((468, 600)) 201 | pygame.display.set_caption('Traffic Jam') 202 | pygame.mouse.set_visible(1) 203 | background = pygame.Surface(screen.get_size()) 204 | background = background.convert() 205 | background.fill((250, 250, 250)) 206 | 207 | #Display The Background 208 | screen.blit(background, (0, 0)) 209 | pygame.display.flip() 210 | 211 | #Prepare Game Objects 212 | clock = pygame.time.Clock() 213 | while 1: 214 | clock.tick(10) 215 | 216 | #Handle Input Events 217 | for event in pygame.event.get(): 218 | if event.type == QUIT: 219 | return 220 | elif event.type == KEYDOWN and event.key == K_ESCAPE: 221 | return 222 | 223 | #Draw Everything 224 | screen.blit(background, (0, 0)) 225 | d = dict() 226 | update() 227 | draw(screen) 228 | 229 | main() 230 | -------------------------------------------------------------------------------- /2006/old2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class expressionEvaluator { 5 | /* This method evaluates the given arithmetic expression and returns 6 | * its Integer value. The method throws an exception if the expression 7 | * is malformed.*/ 8 | static String evaluate( String expr ) throws Exception { 9 | Stack tokens = new Stack(); 10 | StringTokenizer tok = new StringTokenizer( expr , "+-*%()", true ); // get the entire expression 11 | while (tok.hasMoreTokens()) { 12 | String cur = tok.nextToken(); 13 | if (cur.equals(")")) { /* if we find the end of a parenthesis group, replace the group 14 | with the value of the expression it contains */ 15 | Stack nums = new Stack(); 16 | Stack ops = new Stack(); 17 | while (tokens.peek().equals("(") == false) { 18 | String str = tokens.pop().toString(); 19 | // sort the tokens into two stacks 20 | if (str.equals("*") || str.equals("-") || str.equals("+") || str.equals("%")) 21 | ops.push(str); 22 | else 23 | nums.push(str); 24 | } 25 | tokens.pop(); // take off the "(" too 26 | tokens.push(evalSimple(nums,ops)); 27 | } 28 | else 29 | tokens.push(cur); 30 | 31 | } 32 | Stack nums = new Stack(); 33 | Stack ops = new Stack(); 34 | while (tokens.empty() == false) { 35 | String str = tokens.pop().toString(); 36 | if (str.equals("*") || str.equals("-") || str.equals("+") || str.equals("%") || str.equals("/")) 37 | ops.push(str); 38 | else 39 | nums.push(str); 40 | } 41 | return evalSimple(nums,ops); 42 | } // end of evaluate 43 | 44 | 45 | /* evaluatePriority() is exactly the same as evaluate(), but with evalSimple replaced with evalSmart. 46 | * Sue me. :) */ 47 | static String evaluatePriority( String expr ) throws Exception { 48 | Stack tokens = new Stack(); 49 | StringTokenizer tok = new StringTokenizer( expr , "+-*%()", true ); // get the entire expression 50 | while (tok.hasMoreTokens()) { 51 | String cur = tok.nextToken(); 52 | if (cur.equals(")")) { /* if we find the end of a parenthesis group, replace the group 53 | with the value of the expression it contains */ 54 | Stack nums = new Stack(); 55 | Stack ops = new Stack(); 56 | while (tokens.peek().equals("(") == false) { 57 | String str = tokens.pop().toString(); 58 | // sort the tokens into two stacks 59 | if (str.equals("*") || str.equals("-") || str.equals("+") || str.equals("%")) 60 | ops.push(str); 61 | else 62 | nums.push(str); 63 | } 64 | tokens.pop(); // take off the "(" too 65 | tokens.push(evalSmart(nums,ops)); 66 | } 67 | else 68 | tokens.push(cur); 69 | 70 | } 71 | Stack nums = new Stack(); 72 | Stack ops = new Stack(); 73 | while (tokens.empty() == false) { 74 | String str = tokens.pop().toString(); 75 | if (str.equals("*") || str.equals("-") || str.equals("+") || str.equals("%") || str.equals("/")) 76 | ops.push(str); 77 | else 78 | nums.push(str); 79 | } 80 | return evalSmart(nums,ops) 81 | } // end of evaluatePriority 82 | 83 | 84 | /* This method takes two stacks of numbers and operators, and returns a String containing the result, 85 | * (using left-to-right priority), and throwing an exception if the expression is malformed */ 86 | private static String evalSimple( Stack nums, Stack ops) throws Exception { 87 | int value = Integer.parseInt(nums.pop().toString()); 88 | if (nums.size() != ops.size()) 89 | throw new Exception("Too many or too few operators"); 90 | if (nums.empty()) // if the expression is just a number, return it 91 | return String.valueOf(value); 92 | while(nums.empty() == false && ops.empty() == false) { 93 | String op = ops.pop().toString(); 94 | int num = Integer.parseInt(nums.pop().toString()); 95 | value = evalBinary(value, op, num); 96 | } 97 | return String.valueOf(value); 98 | } // end of evalSimple 99 | 100 | /* This method takes two stacks of numbers and operators, and returns a String containing the result, 101 | * (using normal, "correct" priority), throws an exception if the expression is malformed) */ 102 | private static String evalSmart (Stack nums, Stack ops) throws Exception { 103 | int value = Integer.parseInt(nums.pop().toString()); 104 | if (nums.size() != ops.size()) 105 | throw new Exception("Too many or too few operators"); 106 | if (nums.empty()) // if the expression is just a number, return it 107 | return String.valueOf(value); 108 | while(nums.empty() == false && ops.empty() == false) { 109 | String op = ops.pop().toString(); 110 | int num = Integer.parseInt(nums.pop().toString()); 111 | /* If the next n operations exist and are multiplication or a division, do them first */ 112 | if (op.equals("%") == false) { // but integer division doesn't commute, so always do that first 113 | while((ops.empty() == false) && (ops.peek().toString().equals("*") || ops.peek().toString().equals("%"))) { 114 | int nextnum = Integer.parseInt(nums.pop().toString()); 115 | String nextop = ops.pop().toString(); 116 | num = evalBinary(num, nextop, nextnum); 117 | } 118 | } 119 | value = evalBinary(value, op, num); 120 | } 121 | return String.valueOf(value); 122 | } // end of evalSmart 123 | 124 | /* returns the result of a simple binary operation, given num1 op num2*/ 125 | private static int evalBinary(int num1, String op, int num2) throws Exception { 126 | if (op.equals("*")) 127 | return num1 * num2; 128 | else if (op.equals("+")) 129 | return num1 + num2; 130 | else if (op.equals("%")) 131 | return num1 / num2; 132 | else if (op.equals("-")) 133 | return num1 - num2; 134 | else 135 | throw new Exception(op + ": Not a valid operator"); 136 | 137 | } // end of evalBinary 138 | 139 | 140 | 141 | 142 | /* This method repeatedly asks the user for an expression and evaluates it. 143 | The loop stops when the user enters an empty expression */ 144 | public void queryAndEvaluate() throws Exception { 145 | String line; 146 | BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) ); 147 | System.out.println("Enter an expression"); 148 | line = stdin.readLine(); 149 | 150 | while ( line.length() > 0 ) { 151 | try { 152 | String value = evaluate( line ); 153 | System.out.println("value = " + value ); 154 | } 155 | catch (Exception e) 156 | { 157 | System.out.println("Malformed Expression" + e.toString()); 158 | } 159 | System.out.println( "Enter an expression" ); 160 | line = stdin.readLine(); 161 | } // end of while loop 162 | } // end of query and evaluate 163 | 164 | public static void main(String args[]) throws Exception { 165 | expressionEvaluator e=new expressionEvaluator(); 166 | e.queryAndEvaluate(); 167 | } // end of main 168 | } 169 | -------------------------------------------------------------------------------- /2006/expressionTreeNode.java: -------------------------------------------------------------------------------- 1 | import java.lang.Math.*; 2 | import java.lang.Double; 3 | 4 | class expressionTreeNode { 5 | private Object value; 6 | private expressionTreeNode leftChild, rightChild, parent; 7 | 8 | expressionTreeNode() { 9 | value = null; 10 | leftChild = rightChild = parent = null; 11 | } 12 | 13 | // Constructor 14 | /* Arguments: String s: Value to be stored in the node 15 | expressionTreeNode l, r, p: the left child, right child, and parent of the node to created 16 | Returns: the newly created expressionTreeNode 17 | */ 18 | expressionTreeNode(String s, expressionTreeNode l, expressionTreeNode r, expressionTreeNode p) { 19 | value = s; 20 | leftChild = l; 21 | rightChild = r; 22 | parent = p; 23 | } 24 | 25 | /* Basic access methods */ 26 | Object getValue() { return value; } 27 | 28 | expressionTreeNode getLeftChild() { return leftChild; } 29 | 30 | expressionTreeNode getRightChild() { return rightChild; } 31 | 32 | expressionTreeNode getParent() { return parent; } 33 | 34 | 35 | /* Basic setting methods */ 36 | void setValue(Object o) { value = o; } 37 | 38 | // sets the left child of this node to n 39 | void setLeftChild(expressionTreeNode n) { 40 | leftChild = n; 41 | n.parent = this; 42 | } 43 | 44 | // sets the right child of this node to n 45 | void setRightChild(expressionTreeNode n) { 46 | rightChild = n; 47 | n.parent=this; 48 | } 49 | 50 | 51 | // Returns the root of the tree describing the expression s 52 | // Watch out: it makes no validity checks whatsoever! 53 | expressionTreeNode(String s) { 54 | // check if s contains parentheses. If it doesn't, then it's a leaf 55 | if (s.indexOf("(")==-1) setValue(s); 56 | else { // it's not a leaf 57 | 58 | /* break the string into three parts: the operator, the left operand, 59 | and the right operand. ***/ 60 | setValue( s.substring( 0 , s.indexOf( "(" ) ) ); 61 | // delimit the left operand 62 | int left = s.indexOf("(")+1; 63 | int i = left; 64 | int parCount = 0; 65 | // find the comma separating the two operands 66 | while (parCount>=0 && !(s.charAt(i)==',' && parCount==0)) { 67 | if ( s.charAt(i) == '(' ) parCount++; 68 | if ( s.charAt(i) == ')' ) parCount--; 69 | i++; 70 | } 71 | int mid=i; 72 | if (parCount<0) mid--; 73 | 74 | // recursively build the left subtree 75 | setLeftChild(new expressionTreeNode(s.substring(left,mid))); 76 | 77 | if (parCount==0) { 78 | // it is a binary operator 79 | // find the end of the second operand 80 | while ( ! (s.charAt(i) == ')' && parCount == 0 ) ) { 81 | if ( s.charAt(i) == '(' ) parCount++; 82 | if ( s.charAt(i) == ')' ) parCount--; 83 | i++; 84 | } 85 | int right=i; 86 | setRightChild( new expressionTreeNode( s.substring( mid + 1, right))); 87 | } 88 | } 89 | } 90 | 91 | 92 | // Returns a copy of the subtree rooted at this node. 93 | expressionTreeNode deepCopy() { 94 | expressionTreeNode n = new expressionTreeNode(); 95 | n.setValue( getValue() ); 96 | if ( getLeftChild()!=null ) n.setLeftChild( getLeftChild().deepCopy() ); 97 | if ( getRightChild()!=null ) n.setRightChild( getRightChild().deepCopy() ); 98 | return n; 99 | } 100 | 101 | // Returns a String describing the subtree rooted at a certain node 102 | public String toString() { 103 | String ret = (String) value; 104 | if ( getLeftChild() == null ) return ret; 105 | else ret = ret + "(" + getLeftChild().toString(); 106 | if ( getRightChild() == null ) return ret + ")"; 107 | else ret = ret + "," + getRightChild().toString(); 108 | ret = ret + ")"; 109 | return ret; 110 | } 111 | 112 | 113 | // Returns the value of the the expression rooted at a given node 114 | // when x has a certain value 115 | double evaluate(double x) { 116 | expressionTreeNode left = getLeftChild(); 117 | expressionTreeNode right = getRightChild(); 118 | if (left == null && right == null) { 119 | if (value.toString().equals("x")) 120 | return x; 121 | else 122 | return new Double(value.toString()); 123 | } 124 | String op = value.toString(); 125 | if (op.equals("add")) 126 | return left.evaluate(x) + right.evaluate(x); 127 | else if (op.equals("mult")) 128 | return left.evaluate(x) * right.evaluate(x); 129 | else if (op.equals("minus")) 130 | return left.evaluate(x) - right.evaluate(x); 131 | else if (op.equals("cos")) 132 | return java.lang.Math.cos(left.evaluate(x)); 133 | else if (op.equals("sin")) 134 | return java.lang.Math.sin(left.evaluate(x)); 135 | else if (op.equals("exp")) 136 | return java.lang.Math.exp(left.evaluate(x)); 137 | else 138 | System.out.println("Invalid operator in eval(): " + op); 139 | return 0; 140 | } 141 | 142 | /* returns the root of a new expression tree representing the derivative of the 143 | expression represented by the tree rooted at the node on which it is called ***/ 144 | expressionTreeNode differentiate() { 145 | expressionTreeNode left = getLeftChild(); 146 | expressionTreeNode right = getRightChild(); 147 | if (left == null && right == null) { 148 | if (value.toString().equals("x")) 149 | return new expressionTreeNode("1"); 150 | else 151 | return new expressionTreeNode("0"); 152 | } 153 | String op = value.toString(); 154 | if (op.equals("add")) 155 | return new expressionTreeNode("add", left.differentiate(), right.differentiate(), null); 156 | else if (op.equals("mult")) { 157 | expressionTreeNode prod = new expressionTreeNode("add", null, null, null); 158 | prod.setLeftChild(new expressionTreeNode("mult", right.differentiate(), left, null)); 159 | prod.setRightChild(new expressionTreeNode("mult", left.differentiate(), right, null)); 160 | return prod; 161 | } 162 | else if (op.equals("minus")) 163 | return new expressionTreeNode("minus", left.differentiate(), right.differentiate(), null); 164 | else if (op.equals("cos")) { 165 | expressionTreeNode copy = deepCopy(); 166 | copy.setValue("sin"); 167 | expressionTreeNode prod = new expressionTreeNode("mult", left.differentiate(), null, null); 168 | prod.setRightChild(new expressionTreeNode("minus", new expressionTreeNode("0"), copy,null)); 169 | return prod; 170 | } 171 | else if (op.equals("sin")) { 172 | expressionTreeNode copy = deepCopy(); 173 | copy.setValue("cos"); 174 | expressionTreeNode prod = new expressionTreeNode("mult", left.differentiate(), null, null); 175 | prod.setRightChild(copy); 176 | return prod; 177 | } 178 | else if (op.equals("exp")) { 179 | expressionTreeNode copy = deepCopy(); 180 | expressionTreeNode prod = new expressionTreeNode("mult", left.differentiate(), null, null); 181 | prod.setRightChild(copy); 182 | return prod; 183 | } 184 | else 185 | System.out.println("Invalid operator in diff(): " + op); 186 | return new expressionTreeNode("0"); 187 | } // end of differentiate() 188 | 189 | expressionTreeNode simplify() { 190 | String val = value.toString(); 191 | // base case: 192 | if (getRightChild() == null && getLeftChild() == null) 193 | return this; 194 | if (getRightChild() != null) { 195 | // clears up all the 0*, 1*, and 0+ 196 | expressionTreeNode right = getRightChild().simplify(); 197 | String rval = right.getValue().toString(); 198 | expressionTreeNode left = getLeftChild().simplify(); 199 | String lval = left.getValue().toString(); 200 | // evaluates binary numerical expressions 201 | if (isNum((right.getValue().toString())) && isNum(left.getValue().toString())) { 202 | Double result = evaluate(1); 203 | return new expressionTreeNode(result.toString()); 204 | } 205 | String op = value.toString(); 206 | 207 | 208 | if (op.equals("add")) { 209 | if (rval.equals("0") || rval.equals("0.0")) 210 | return left; 211 | if (lval.equals("0")|| lval.equals("0.0")) 212 | return right; 213 | } 214 | if (op.equals("mult")) { 215 | //System.out.println("hey, i'm mult! for .." + right + " and " + left); 216 | if (rval.equals("0") || rval.equals("0.0")) 217 | return new expressionTreeNode("0"); 218 | if (lval.equals("0")|| lval.equals("0.0")) 219 | return new expressionTreeNode("0"); 220 | if (rval.equals("1") || rval.equals("1.0")) 221 | return left; 222 | if (lval.equals("1")|| lval.equals("1.0")) 223 | return right; 224 | 225 | } 226 | return new expressionTreeNode(getValue().toString(), left, right, null); 227 | } 228 | 229 | else { 230 | // evaluates other expressions 231 | expressionTreeNode left = getLeftChild().simplify(); 232 | if (isNum(left.getValue().toString())) { 233 | Double result = evaluate(1); 234 | return new expressionTreeNode(result.toString()); 235 | } 236 | return new expressionTreeNode(getValue().toString(), left, null, null); 237 | } 238 | } 239 | 240 | 241 | private boolean isNum(String s) { 242 | try { 243 | double k = new Double(s); 244 | return true; 245 | } 246 | catch (NumberFormatException e) { 247 | return false; 248 | } 249 | 250 | } 251 | 252 | public static void main(String args[]) { 253 | expressionTreeNode e = new expressionTreeNode("mult(exp(mult(x,2)),x)"); 254 | System.out.println(e); 255 | System.out.println(e.evaluate(1)); 256 | System.out.println(" Diff: "+ e.differentiate()); 257 | System.out.println("Simplified: " + e.differentiate().simplify()); 258 | } 259 | 260 | } 261 | -------------------------------------------------------------------------------- /2009/clean.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | import pygame 3 | import math 4 | import random 5 | from math import sqrt 6 | from pygame.locals import * 7 | 8 | 9 | DISPLAY = True 10 | 11 | data = [] 12 | YIELD = 1 13 | LIGHT = 2 14 | OUT = 3 15 | IN = 4 16 | maxSpeed = 15 17 | 18 | numLightCycles = 0 19 | 20 | numLeftThisTurn = 0 21 | numLeftRecently = [] 22 | 23 | # amount you can slow down / speed up per half second 24 | decel = 7 25 | accel = 3 26 | 27 | problem = False 28 | carLength = 4 29 | carOffset = carLength - 1 30 | 31 | branchLength = 1000 32 | circleLength = 480 33 | 34 | inBranchLocations = [10, 130, 250, 370] 35 | outBranchLocations = [0, 120, 240, 360] # random.sample(range(circleLength), numOutBranches) 36 | 37 | quiet = 0.2 38 | busy = 0.4 39 | inRates = [quiet, quiet,quiet, quiet] 40 | outWeights = [1,1,1,1] 41 | yields = [0,0,0,0] 42 | inBranches = [] 43 | outBranches = [] 44 | 45 | cars = [] 46 | factories = [] 47 | 48 | def stoppingDistance(speed): 49 | return sum([speed - decel * i for i in range(speed) if (speed - decel * i) > 0]) 50 | return 0 51 | 52 | def findMaxTime(speed, dist): 53 | t = 0 54 | while(dist > 0): 55 | speed = speed - decel 56 | if (speed < 0): 57 | return (False,False) 58 | dist = dist - speed 59 | t = t + 1 60 | return (t, dist) 61 | 62 | def findMaxDist(speed, t): 63 | d = 0 64 | while(t > 0): 65 | d = d + speed 66 | speed = min(speed + accel, maxSpeed) 67 | t = t - 1 68 | return d 69 | 70 | def findMinTime(speed, dist): 71 | t = 0 72 | speed = speed + accel 73 | while(dist > speed): 74 | dist = dist - speed 75 | speed = min(speed + accel, maxSpeed) 76 | t = t + 1 77 | return (t, dist) 78 | 79 | 80 | class Tile: 81 | def __init__(self, track, index): 82 | self.tags = [] # (YIELD, inside/outside), LIGHT, OUT, IN 83 | self.car = None 84 | self.inBranches = [] 85 | self.outBranches = [] 86 | self.next = [] 87 | self.prev = [] 88 | self.track = track 89 | self.index = index 90 | self.yieldFrom = None 91 | self.yieldTo = None 92 | 93 | class Track(object): 94 | def __init__(self, length): 95 | self.tiles = [Tile(self, i) for i in range(length)] 96 | self.length = length 97 | self.start = self.tiles[0] 98 | self.end = self.tiles[-1] 99 | for t in range(len(self.tiles)): 100 | if t < len(self.tiles)-1: 101 | self.tiles[t].next.append(self.tiles[t+1]) 102 | if t > 0: 103 | self.tiles[t].prev.append(self.tiles[t-1]) 104 | 105 | 106 | class Circle(Track): 107 | def __getitem__(self,n): 108 | return self.tiles[n % self.length] 109 | def __init__(self,length): 110 | super(Circle,self).__init__(length) 111 | self.start.prev.append(self.end) 112 | self.end.next.append(self.start) 113 | 114 | class InBranch(Track): 115 | def __getitem__(self,n): 116 | if n >= self.length: 117 | return self.branchPt 118 | else: 119 | return self.tiles[n] 120 | def __init__(self, length, branchPt, yieldDirection): 121 | super(InBranch, self).__init__(length) 122 | self.branchPt = branchPt 123 | other = self.branchPt.prev[0] 124 | self.branchPt.prev.append(self.end) 125 | if yieldDirection == 0: 126 | self.branchPt.yieldFrom = other 127 | other.yieldTo = self.branchPt 128 | else: 129 | self.branchPt.yieldFrom = self.end 130 | self.end.yieldTo = self.branchPt 131 | 132 | class OutBranch(Track): 133 | def __getitem__(self,n): 134 | if (n >= self.length): 135 | return None 136 | else: 137 | return self.tiles[n] 138 | def __init__(self, length, branchPt): 139 | self.branchPt = branchPt 140 | super(OutBranch, self).__init__(length) 141 | 142 | 143 | class Car: 144 | def __init__(self, tile, dest): 145 | self.speed = 0 146 | self.tile = tile 147 | self.problem = False 148 | self.destination = dest 149 | self.nextLocation = None 150 | self.colour = random.choice([(255,0,0), (200,0,0), (150,0,0), (150,0,150)]) 151 | self.tempColour = 0 152 | self.stage = 0 153 | 154 | def solve(self, a,b,c): 155 | try: 156 | return (-b + sqrt(b**2 - 4*a*c))/(2*a) 157 | except: 158 | return False 159 | def checkBackOne(self, dist1, dist2, speed1, speed2): 160 | # returns -1, 0, or 1 161 | # yielding car is dist1 from intersection, moving at speed1 162 | # other car is dist2 from intersection, moving at speed2 163 | ## 164 | if (speed1 == 0): 165 | return -1 # everything is fine. You can think about going faster 166 | 167 | t1 = math.floor(float(dist1) / speed1) # conservative 168 | (t2, overshootDist) = findMaxTime(speed2, dist2 + carLength) 169 | if (t2 == False): 170 | t2 = 100000 171 | assert(t2 > 0) 172 | if t2 <= t1: 173 | # car 2 gets there first for sure 174 | deltaD = dist1 - t2 * speed1 - overshootDist 175 | assert(deltaD >= 0) 176 | if stoppingDistance(speed1) >= stoppingDistance(speed2 - decel * t2) + deltaD: 177 | return 0 178 | else: 179 | return 1 180 | # done with first half 181 | 182 | t1 = math.ceil((dist1 + carLength) / float(speed1)) 183 | (t2, undershootDist) = findMinTime(speed2, dist2) 184 | if (t1 <= t2): 185 | deltaD = dist2 - findMaxDist(speed2, t1) + t1 * speed1 - dist1 - carLength 186 | if stoppingDistance(speed1) + deltaD <= stoppingDistance(min(speed2 + accel * t1, maxSpeed)): 187 | return 0 188 | else: 189 | return -1 190 | return 0 191 | 192 | def checkDanger(self, currTile, yieldTile, dist): 193 | nextTile = yieldTile.next[0] 194 | otherTile = None 195 | for i in nextTile.prev: 196 | if i is not yieldTile: 197 | otherTile = i 198 | dist2 = 1 199 | while True: 200 | if (dist2 >= otherTile.track.length): 201 | return False 202 | if (otherTile.car): 203 | result = self.checkBackOne(dist, dist2, currTile.car.speed, otherTile.car.speed) 204 | if (result == 0): 205 | return True 206 | if (result == -1): 207 | return False 208 | otherTile = otherTile.prev[0] 209 | dist2 += 1 210 | 211 | 212 | def update(self): 213 | global numLeftThisTurn 214 | assert(self.tile.car) 215 | assert(self.destination) 216 | track = self.tile.track 217 | trackLength = track.length 218 | nextCar = None 219 | doDecel = False 220 | doAccel = False 221 | currDist = 0 222 | assert(self.tile) 223 | for dist in range(0, stoppingDistance(min(self.speed + accel, maxSpeed)) + carLength): 224 | j = (dist + self.tile.index) 225 | if (track[j] == None): 226 | if (dist < max(self.speed, 5)): 227 | self.nextLocation = None 228 | return 229 | break 230 | if (track[j].car and (not nextCar) and (track[j].car != self.tile.car)): 231 | nextCar = track[j].car 232 | currDist = dist - carOffset 233 | if (track[j].yieldTo != None): 234 | if self.checkDanger(self.tile, track[j], dist + 1): 235 | doDecel = True 236 | #decelerating because of danger 237 | if track[j] == self.destination.branchPt: 238 | if (dist < self.speed): 239 | self.nextLocation = self.destination[0] 240 | numLeftThisTurn +=1 241 | return 242 | 243 | if nextCar == None: 244 | if self.speed < maxSpeed: 245 | doAccel = True 246 | else: 247 | if (currDist < 1): 248 | self.tile.car.tempColour = (0,255,0) 249 | nextCar.tempColour = (128,128,255) 250 | 251 | if stoppingDistance(self.speed) >= stoppingDistance(nextCar.speed - decel) + currDist: 252 | doDecel = True 253 | elif stoppingDistance(self.speed + accel) < stoppingDistance(nextCar.speed - decel) + currDist: 254 | doAccel = True 255 | # else same speed 256 | if (doDecel): 257 | self.speed = max(self.speed - decel, 0) 258 | elif (random.random() < 0.1): 259 | self.speed = max(self.speed - 1, 0) 260 | elif (doAccel): 261 | oldspeed = self.speed 262 | self.speed = min(self.speed + accel, maxSpeed) 263 | for dist in range(0, stoppingDistance(self.speed)+ carLength): 264 | j = (dist + self.tile.index) 265 | if (track[j] == None): 266 | continue 267 | if (track[j].yieldTo != None): 268 | if self.checkDanger(self.tile, track[j], dist + 1): 269 | self.speed = oldspeed 270 | break 271 | 272 | 273 | 274 | 275 | self.nextLocation = self.tile.track[(self.tile.index + self.speed)] 276 | 277 | 278 | 279 | def destFactory(): 280 | while 1: 281 | choiceLst = [] 282 | for i in range(min(len(outBranches), len(outWeights))): 283 | for j in range(outWeights[i]): 284 | choiceLst.append(outBranches[i]) 285 | yield random.choice(choiceLst) 286 | 287 | 288 | 289 | def newCar(location, dest): 290 | car = Car(location, dest) 291 | cars.append(car) 292 | location.car = car 293 | 294 | 295 | def carFactory(rate, start, destGen): 296 | while 1: 297 | if random.random() < rate and start.car == None: 298 | newcar = newCar(start, destGen.next()) 299 | yield newcar 300 | else: 301 | yield None 302 | 303 | 304 | def carFactory2(rate, start, destGen): 305 | global numLightCycles 306 | global data 307 | counter = 0 308 | go = False 309 | while 1: 310 | counter += 1 311 | if (counter % 60) == 0: 312 | numLightCycles += 1 313 | data.append(sum(numLeftRecently)) 314 | go = not go 315 | if random.random() < rate and start.car == None and go: 316 | newcar = newCar(start, destGen.next()) 317 | yield newcar 318 | else: 319 | yield None 320 | 321 | 322 | def createInBranches(inBranchLocations): 323 | for i in range(len(inBranchLocations)): 324 | loc = inBranchLocations[i] 325 | track = InBranch(branchLength, loc, yields[i]) 326 | inBranches.append(track) 327 | factory = carFactory2(inRates[i], track.start, destFactory()) 328 | factories.append(factory) 329 | track.end.next.append(loc) 330 | loc.inBranches.append(track) 331 | 332 | 333 | def createOutBranches(outBranchLocations): 334 | for loc in outBranchLocations: 335 | track = OutBranch(branchLength, loc) 336 | outBranches.append(track) 337 | loc.outBranches.append(track) 338 | 339 | 340 | circle = Circle(circleLength) 341 | createInBranches(map(lambda x: circle[x], inBranchLocations)) 342 | createOutBranches(map(lambda x: circle[x], outBranchLocations)) 343 | 344 | def update(): 345 | for car in cars: 346 | car.tile.car = car 347 | car.update() 348 | if (not car.nextLocation): 349 | car.tile = None 350 | cars.remove(car) 351 | for car in cars: 352 | assert(car.tile) 353 | car.tile.car = None 354 | for car in cars: 355 | car.tile = car.nextLocation 356 | car.tile.car = car 357 | for factory in factories: 358 | factory.next() 359 | 360 | 361 | def drawTrack(track, horiz, startPoint, screen): 362 | (x0,y0) = startPoint 363 | if (track in inBranches): 364 | perm = lambda x, y: (x0 + (track.length - (x - x0)) , y) 365 | elif (horiz): 366 | perm = lambda x, y: (x, y) 367 | else: 368 | perm = lambda x, y: (y, x) 369 | for i in range(track.length): 370 | if (track[i].car): 371 | if (track[i].car.tempColour): 372 | pygame.draw.line(screen, track[i].car.tempColour, perm(x0 + i, y0), perm(x0 + i+carOffset, y0)) 373 | track[i].car.tempColour = None 374 | else: 375 | pygame.draw.line(screen, track[i].car.colour, perm(x0 + i, y0), perm(x0 + i+carOffset, y0)) 376 | 377 | 378 | 379 | def draw(screen): 380 | global numLeftThisTurn 381 | global numLeftRecently 382 | if not DISPLAY: 383 | return 384 | drawTrack(circle, False, (8,9), screen) 385 | for i in range(circleLength): 386 | for branch in circle[i].inBranches: 387 | drawTrack(branch, True, (11, i+8), screen) 388 | for branch in circle[i].outBranches: 389 | drawTrack(branch, True, (11, i+8), screen) 390 | pygame.display.flip() 391 | 392 | 393 | def main(): 394 | pygame.init() 395 | screen = pygame.display.set_mode((468, 800)) 396 | pygame.display.set_caption('Traffic Jam') 397 | pygame.mouse.set_visible(1) 398 | background = pygame.Surface(screen.get_size()) 399 | background = background.convert() 400 | background.fill((250, 250, 250)) 401 | 402 | #Display The Background 403 | screen.blit(background, (0, 0)) 404 | pygame.display.flip() 405 | 406 | #Prepare Game Objects 407 | clock = pygame.time.Clock() 408 | while 1: 409 | clock.tick(1000) 410 | 411 | #Handle Input Events 412 | for event in pygame.event.get(): 413 | if event.type == QUIT: 414 | return 415 | elif event.type == KEYDOWN and event.key == K_ESCAPE: 416 | return 417 | 418 | global numLeftRecently 419 | global numLeftThisTurn 420 | global numLightCycles 421 | global data 422 | numLeftRecently.append(numLeftThisTurn) 423 | numLeftRecently = numLeftRecently[-60:] 424 | if (numLightCycles == 40): 425 | data = data[12:] 426 | print float(sum(data)) / len(data) 427 | break 428 | numLeftThisTurn = 0 429 | 430 | #Draw Everything 431 | screen.blit(background, (0, 0)) 432 | d = dict() 433 | update() 434 | draw(screen) 435 | 436 | main() 437 | -------------------------------------------------------------------------------- /2009/traffic.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | import pygame 3 | import math 4 | import random 5 | from math import sqrt 6 | from pygame.locals import * 7 | 8 | 9 | DISPLAY = True 10 | 11 | data = [] 12 | YIELD = 1 13 | LIGHT = 2 14 | OUT = 3 15 | IN = 4 16 | maxSpeed = 15 17 | #numInBranches = 4 18 | #numOutBranches = 19 | 20 | numLightCycles = 0 21 | 22 | numLeftThisTurn = 0 23 | numLeftRecently = [] 24 | 25 | # amount you can slow down / speed up per half second 26 | decel = 7 27 | accel = 3 28 | 29 | problem = False 30 | carLength = 4 31 | carOffset = carLength - 1 32 | 33 | branchLength = 1000 34 | circleLength = 480 35 | 36 | inBranchLocations = [10, 130, 250, 370] 37 | outBranchLocations = [0, 120, 240, 360] # random.sample(range(circleLength), numOutBranches) 38 | 39 | quiet = 0.2 40 | busy = 0.4 41 | inRates = [quiet, quiet,quiet, quiet] 42 | outWeights = [1,1,1,1] 43 | yields = [0,0,0,0] 44 | inBranches = [] 45 | outBranches = [] 46 | 47 | cars = [] 48 | factories = [] 49 | 50 | def stoppingDistance(speed): 51 | return sum([speed - decel * i for i in range(speed) if (speed - decel * i) > 0]) 52 | return 0 53 | 54 | def findMaxTime(speed, dist): 55 | t = 0 56 | while(dist > 0): 57 | speed = speed - decel 58 | if (speed < 0): 59 | return (False,False) 60 | dist = dist - speed 61 | t = t + 1 62 | return (t, dist) 63 | 64 | def findMaxDist(speed, t): 65 | d = 0 66 | while(t > 0): 67 | d = d + speed 68 | speed = min(speed + accel, maxSpeed) 69 | t = t - 1 70 | return d 71 | 72 | def findMinTime(speed, dist): 73 | t = 0 74 | speed = speed + accel 75 | while(dist > speed): 76 | dist = dist - speed 77 | speed = min(speed + accel, maxSpeed) 78 | t = t + 1 79 | return (t, dist) 80 | 81 | 82 | class Tile: 83 | def __init__(self, track, index): 84 | self.tags = [] # (YIELD, inside/outside), LIGHT, OUT, IN 85 | self.car = None 86 | self.inBranches = [] 87 | self.outBranches = [] 88 | self.next = [] 89 | self.prev = [] 90 | self.track = track 91 | self.index = index 92 | self.yieldFrom = None 93 | self.yieldTo = None 94 | 95 | class Track(object): 96 | def __init__(self, length): 97 | self.tiles = [Tile(self, i) for i in range(length)] 98 | self.length = length 99 | self.start = self.tiles[0] 100 | self.end = self.tiles[-1] 101 | for t in range(len(self.tiles)): 102 | if t < len(self.tiles)-1: 103 | self.tiles[t].next.append(self.tiles[t+1]) 104 | if t > 0: 105 | self.tiles[t].prev.append(self.tiles[t-1]) 106 | 107 | 108 | class Circle(Track): 109 | def __getitem__(self,n): 110 | return self.tiles[n % self.length] 111 | def __init__(self,length): 112 | super(Circle,self).__init__(length) 113 | self.start.prev.append(self.end) 114 | self.end.next.append(self.start) 115 | 116 | class InBranch(Track): 117 | def __getitem__(self,n): 118 | if n >= self.length: 119 | return self.branchPt 120 | else: 121 | return self.tiles[n] 122 | def __init__(self, length, branchPt, yieldDirection): 123 | super(InBranch, self).__init__(length) 124 | self.branchPt = branchPt 125 | other = self.branchPt.prev[0] 126 | self.branchPt.prev.append(self.end) 127 | if yieldDirection == 0: 128 | self.branchPt.yieldFrom = other 129 | other.yieldTo = self.branchPt 130 | else: 131 | self.branchPt.yieldFrom = self.end 132 | self.end.yieldTo = self.branchPt 133 | 134 | class OutBranch(Track): 135 | def __getitem__(self,n): 136 | if (n >= self.length): 137 | return None 138 | else: 139 | return self.tiles[n] 140 | def __init__(self, length, branchPt): 141 | self.branchPt = branchPt 142 | super(OutBranch, self).__init__(length) 143 | 144 | 145 | class Car: 146 | def __init__(self, tile, dest): 147 | self.speed = 0 148 | self.tile = tile 149 | self.problem = False 150 | self.destination = dest 151 | self.nextLocation = None 152 | self.colour = random.choice([(255,0,0), (200,0,0), (150,0,0), (150,0,150)]) 153 | self.tempColour = 0 154 | self.stage = 0 155 | 156 | # def checkReverseDanger(tile, ): 157 | # if tile.speed: 158 | # pass 159 | # for t in tile.prev: 160 | # pass 161 | # 162 | # 163 | def solve(self, a,b,c): 164 | try: 165 | return (-b + sqrt(b**2 - 4*a*c))/(2*a) 166 | except: 167 | return False 168 | def checkBackOne(self, dist1, dist2, speed1, speed2): 169 | # returns -1, 0, or 1 170 | # yielding car is dist1 from intersection, moving at speed1 171 | # other car is dist2 from intersection, moving at speed2 172 | ## 173 | if (speed1 == 0): 174 | return -1 # everything is fine. You can think about going faster 175 | 176 | t1 = math.floor(float(dist1) / speed1) # conservative 177 | (t2, overshootDist) = findMaxTime(speed2, dist2 + carLength) 178 | if (t2 == False): 179 | t2 = 100000 180 | assert(t2 > 0) 181 | if t2 <= t1: 182 | # car 2 gets there first for sure 183 | deltaD = dist1 - t2 * speed1 - overshootDist 184 | assert(deltaD >= 0) 185 | if stoppingDistance(speed1) >= stoppingDistance(speed2 - decel * t2) + deltaD: 186 | return 0 187 | else: 188 | return 1 189 | # done with first half 190 | 191 | t1 = math.ceil((dist1 + carLength) / float(speed1)) 192 | (t2, undershootDist) = findMinTime(speed2, dist2) 193 | if (t1 <= t2): 194 | deltaD = dist2 - findMaxDist(speed2, t1) + t1 * speed1 - dist1 - carLength 195 | if stoppingDistance(speed1) + deltaD <= stoppingDistance(min(speed2 + accel * t1, maxSpeed)): 196 | return 0 197 | else: 198 | return -1 199 | return 0 200 | 201 | def checkDanger(self, currTile, yieldTile, dist): 202 | nextTile = yieldTile.next[0] 203 | otherTile = None 204 | for i in nextTile.prev: 205 | if i is not yieldTile: 206 | otherTile = i 207 | #otherTile = nextTile.prev[1] 208 | # should be 0 in other case 209 | # for tile in nextTile.prev: 210 | # if (currTile == tile): 211 | # continue 212 | # else: 213 | # otherTile = tile 214 | # break 215 | # else: 216 | # print "oh no! there is no previous tile" 217 | # print "My tile: ", currTile 218 | # print "Other tile: ", otherTile 219 | dist2 = 1 220 | while True: 221 | if (dist2 >= otherTile.track.length): 222 | return False 223 | if (otherTile.car): 224 | # print "My car: ", currTile.car 225 | # print "Other car: ", otherTile.car 226 | result = self.checkBackOne(dist, dist2, currTile.car.speed, otherTile.car.speed) 227 | # print result, dist, dist2, currTile.car.speed, otherTile.car.speed 228 | if (result == 0): 229 | return True 230 | if (result == -1): 231 | return False 232 | # print otherTile.prev 233 | otherTile = otherTile.prev[0] # TODO: wrong 234 | dist2 += 1 235 | 236 | # flags = [False] 237 | # if tile.car: 238 | # if tile.car.speed*(tile.car.speed -1)/2 > dist: 239 | # if dist == 0: 240 | # flags.append(False) 241 | # else: 242 | # flags.append(checkDanger(tile.next, dist-1)) 243 | # else: 244 | # flags.append(True) 245 | # if prevTile in tile.yield_: 246 | # for t in tile.prev: 247 | # if t is not prevTile 248 | # flag.append(checkReverseDanger(t, speed)) 249 | # 250 | 251 | def update(self): 252 | global numLeftThisTurn 253 | # print "Updating car at index %i" % self.tile.index 254 | # set nextLocation 255 | assert(self.tile.car) 256 | assert(self.destination) 257 | track = self.tile.track 258 | trackLength = track.length 259 | nextCar = None 260 | doDecel = False 261 | doAccel = False 262 | currDist = 0 263 | assert(self.tile) 264 | for dist in range(0, stoppingDistance(min(self.speed + accel, maxSpeed)) + carLength): 265 | j = (dist + self.tile.index) 266 | if (track[j] == None): 267 | # wrong 268 | if (dist < max(self.speed, 5)): 269 | # print "reached the end.." 270 | self.nextLocation = None 271 | return 272 | break 273 | if (track[j].car and (not nextCar) and (track[j].car != self.tile.car)): 274 | nextCar = track[j].car 275 | currDist = dist - carOffset 276 | if (track[j].yieldTo != None): 277 | # print "checking for danger..." 278 | if self.checkDanger(self.tile, track[j], dist + 1): 279 | doDecel = True 280 | # print "decelerating because of DANGER" 281 | # wrong: 282 | if track[j] == self.destination.branchPt: 283 | if (dist < self.speed): 284 | self.nextLocation = self.destination[0] 285 | numLeftThisTurn +=1 286 | ## print self.destination 287 | return 288 | 289 | if nextCar == None: 290 | if self.speed < maxSpeed: 291 | doAccel = True 292 | else: 293 | if (currDist < 1): 294 | self.tile.car.tempColour = (0,255,0) 295 | nextCar.tempColour = (128,128,255) 296 | # print "holy crap there should not be a car there" 297 | 298 | if stoppingDistance(self.speed) >= stoppingDistance(nextCar.speed - decel) + currDist: 299 | doDecel = True 300 | # print "decelerating because of car ahead" 301 | elif stoppingDistance(self.speed + accel) < stoppingDistance(nextCar.speed - decel) + currDist: 302 | doAccel = True 303 | # else same speed 304 | if (doDecel): 305 | self.speed = max(self.speed - decel, 0) 306 | elif (random.random() < 0.1): 307 | self.speed = max(self.speed - 1, 0) 308 | elif (doAccel): 309 | oldspeed = self.speed 310 | self.speed = min(self.speed + accel, maxSpeed) 311 | for dist in range(0, stoppingDistance(self.speed)+ carLength): 312 | j = (dist + self.tile.index) 313 | if (track[j] == None): 314 | continue 315 | if (track[j].yieldTo != None): 316 | # print "there is a yield sign!" 317 | if self.checkDanger(self.tile, track[j], dist + 1): 318 | # print "there is danger!" 319 | # print "my speed is %i" % self.speed 320 | self.speed = oldspeed 321 | break 322 | 323 | 324 | 325 | 326 | self.nextLocation = self.tile.track[(self.tile.index + self.speed)] 327 | # print self.tile == self.nextLocation 328 | 329 | 330 | 331 | def destFactory(): 332 | while 1: 333 | # print "dest" 334 | choiceLst = [] 335 | for i in range(min(len(outBranches), len(outWeights))): 336 | for j in range(outWeights[i]): 337 | choiceLst.append(outBranches[i]) 338 | yield random.choice(choiceLst) 339 | 340 | 341 | 342 | def newCar(location, dest): 343 | car = Car(location, dest) 344 | cars.append(car) 345 | location.car = car 346 | 347 | 348 | def carFactory(rate, start, destGen): 349 | while 1: 350 | if random.random() < rate and start.car == None: 351 | newcar = newCar(start, destGen.next()) 352 | yield newcar 353 | else: 354 | yield None 355 | 356 | 357 | def carFactory2(rate, start, destGen): 358 | global numLightCycles 359 | global data 360 | counter = 0 361 | go = False 362 | while 1: 363 | counter += 1 364 | if (counter % 60) == 0: 365 | numLightCycles += 1 366 | data.append(sum(numLeftRecently)) 367 | go = not go 368 | if random.random() < rate and start.car == None and go: 369 | newcar = newCar(start, destGen.next()) 370 | yield newcar 371 | else: 372 | yield None 373 | 374 | 375 | def createInBranches(inBranchLocations): 376 | for i in range(len(inBranchLocations)): 377 | loc = inBranchLocations[i] 378 | track = InBranch(branchLength, loc, yields[i]) 379 | inBranches.append(track) 380 | factory = carFactory2(inRates[i], track.start, destFactory()) 381 | factories.append(factory) 382 | track.end.next.append(loc) 383 | loc.inBranches.append(track) 384 | 385 | 386 | def createOutBranches(outBranchLocations): 387 | for loc in outBranchLocations: 388 | track = OutBranch(branchLength, loc) 389 | outBranches.append(track) 390 | loc.outBranches.append(track) 391 | 392 | 393 | circle = Circle(circleLength) 394 | createInBranches(map(lambda x: circle[x], inBranchLocations)) 395 | createOutBranches(map(lambda x: circle[x], outBranchLocations)) 396 | #newCar(circle.start, None) 397 | 398 | 399 | 400 | #for loc in inBranchLocations: 401 | # track = Track(branchLength) 402 | # for i in range(track.length): 403 | # if (random.random() > 0.8): 404 | # track[i].car = Car(track[i]) 405 | # track[i].car.location = i 406 | # circle[loc].inBranches.append(track) 407 | #for loc in outBranchLocations: 408 | # circle[loc].outBranches.append(Track(branchLength)) 409 | 410 | 411 | #for tile in circle: 412 | # if (random.random() > 0.7): 413 | # tile.car = Car(tile) 414 | # tile.car.location = tile.location 415 | 416 | 417 | def update(): 418 | for car in cars: 419 | car.tile.car = car # should not be here 420 | # print "My speed: ", car.speed 421 | car.update() 422 | if (not car.nextLocation): 423 | car.tile = None 424 | # print "removing car" 425 | cars.remove(car) 426 | for car in cars: 427 | assert(car.tile) 428 | car.tile.car = None 429 | for car in cars: 430 | car.tile = car.nextLocation 431 | car.tile.car = car 432 | for factory in factories: 433 | factory.next() 434 | # print "updated!" 435 | 436 | 437 | def drawTrack(track, horiz, startPoint, screen): 438 | (x0,y0) = startPoint 439 | if (track in inBranches): 440 | perm = lambda x, y: (x0 + (track.length - (x - x0)) , y) 441 | elif (horiz): 442 | perm = lambda x, y: (x, y) 443 | else: 444 | perm = lambda x, y: (y, x) 445 | for i in range(track.length): 446 | if (track[i].car): 447 | if (track[i].car.tempColour): 448 | pygame.draw.line(screen, track[i].car.tempColour, perm(x0 + i, y0), perm(x0 + i+carOffset, y0)) 449 | track[i].car.tempColour = None 450 | else: 451 | pygame.draw.line(screen, track[i].car.colour, perm(x0 + i, y0), perm(x0 + i+carOffset, y0)) 452 | 453 | 454 | 455 | def draw(screen): 456 | global numLeftThisTurn 457 | global numLeftRecently 458 | if not DISPLAY: 459 | return 460 | drawTrack(circle, False, (8,9), screen) 461 | for i in range(circleLength): 462 | for branch in circle[i].inBranches: 463 | drawTrack(branch, True, (11, i+8), screen) 464 | for branch in circle[i].outBranches: 465 | drawTrack(branch, True, (11, i+8), screen) 466 | pygame.display.flip() 467 | # if (problem): 468 | # e = pygame.event.wait() 469 | # problem = False 470 | 471 | 472 | def main(): 473 | pygame.init() 474 | screen = pygame.display.set_mode((468, 800)) 475 | pygame.display.set_caption('Traffic Jam') 476 | pygame.mouse.set_visible(1) 477 | background = pygame.Surface(screen.get_size()) 478 | background = background.convert() 479 | background.fill((250, 250, 250)) 480 | 481 | #Display The Background 482 | screen.blit(background, (0, 0)) 483 | pygame.display.flip() 484 | 485 | #Prepare Game Objects 486 | clock = pygame.time.Clock() 487 | while 1: 488 | clock.tick(20) 489 | 490 | #Handle Input Events 491 | for event in pygame.event.get(): 492 | if event.type == QUIT: 493 | return 494 | elif event.type == KEYDOWN and event.key == K_ESCAPE: 495 | return 496 | 497 | global numLeftRecently 498 | global numLeftThisTurn 499 | global numLightCycles 500 | global data 501 | numLeftRecently.append(numLeftThisTurn) 502 | numLeftRecently = numLeftRecently[-60:] 503 | if (numLightCycles == 40): 504 | data = data[12:] 505 | print float(sum(data)) / len(data) 506 | break 507 | numLeftThisTurn = 0 508 | 509 | #Draw Everything 510 | screen.blit(background, (0, 0)) 511 | d = dict() 512 | update() 513 | draw(screen) 514 | 515 | main() 516 | --------------------------------------------------------------------------------