## Spectacular Seven

### May 4, 2010

There’s nothing hard about this program as long as you keep straight what you are doing at each step:

`(define (seven n)`

(let ((wins (make-vector 8 0))

(scores (make-vector 8 0)))

(let loop ((k n) (p 0) (winner 0) (challenger 1)

(queue '(2 3 4 5 6 7)))

(cond ((zero? k) ; simulation ends

(map (lambda (x) (exact->inexact (/ x n 1/100)))

(vector->list wins)))

((<= 7 (vector-ref scores winner)) ; game ends

(vector-set! wins winner

(+ (vector-ref wins winner) 1))

(set! scores (make-vector 8 0))

(loop (- k 1) 0 0 1 '(2 3 4 5 6 7)))

((< (rand) 1/2) ; current winner wins point

(vector-set! scores winner

(+ (vector-ref scores winner)

(if (<= 7 p) 2 1)))

(loop k (+ p 1) winner (car queue)

(append (cdr queue) (list challenger))))

(else ; current challenger wins point

(vector-set! scores challenger

(+ (vector-ref scores challenger)

(if (<= 7 p) 2 1)))

(loop k (+ p 1) challenger (car queue)

(append (cdr queue) (list winner))))))))

The `wins`

vector tracks which team won; at the end of the simulation, the sum of the wins over all teams should equal `n`

. The `scores`

vector tracks the scores of each team in a single game, and is reset at the beginning of each game; `p`

keeps track of the point count in each game, to determine if a particular point has a value of 1 or 2. Here are the winning percentages we get after a million simulated games:

`> (seven 1000000)`

(16.3057 16.2836 13.8705 12.4255 10.2218 10.2573 8.877 11.7586)

The first two teams have similar winning percentages; since it is fifty/fifty that either wins the first point, that makes sense. Winning percentages decrease for each succeeding team until the last, who can win the game if they win the four points they play, with 1 on the first point and 2 on each of the next three points. In real jai alai games, handicappers put the best teams in the fourth, fifth and sixth post positions to make games more exciting.

We used rand from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/6bcXRB4Z.

[…] Praxis – Spectacular Seven By Remco Niemeijer In today’s Programming Praxis exercise our task is to run a simulation of a ballgame to see if the scoring […]

My Haskell solution (see http://bonsaicode.wordpress.com/2010/05/04/programming-praxis-spectacular-seven/ for a version with comments):

In python:

jai_alai_match() accepts a list of ratings to indicate the relative strengths of the players. The probablility of a player winning a point is the ratio of the players rating to the sum of both players ratings (see the threshold calculation below). The default is that each player is equally likely to win a point.

A Ruby implementation. There’s quite a few improvements to make, but I’m getting tired of looking at it ;-). This is quite a few more lines than the other implementations, but maybe someone will find it useful.

I haven’t posted here before, but it looks like a great site.