# counting runs

Dick Kriesel dick.kriesel at mail.com
Mon Oct 31 21:09:12 EST 2005

```On 10/31/05 4:22 PM, "Jason Tangen" <j.tangen at unsw.edu.au> wrote:

> Hello,
>
> I'm trying to solve a seemingly simple problem and I could use some
> help. A coin flip will come out "Heads" or "Tails" and will produce,
> for example, the following series for 20 flips:
>
> T,T,H,T,T,H,H,H,T,T,H,T,H,H,H,T,H,T,H,T
>
> I need to count up the number events for a particular run.  For example,
>
> Heads x 3 = 2
> Heads x 2 = 0
> Heads x 1 = 4
> Tails x 1 = 4
> Tails x 2 = 3
> Tails x 3 = 0
>
> I need to account for runs up to 60 (rather than 3 above) for
> hundreds of flips (rather than 20 above).
>
> I've been using a very clumsy multiple if-then solution to date, but
> this quickly becomes difficult with many runs.
>
> Can someone point me in the right direction?
>
> Cheers,
> Jason

Here's yet another solution.  At the core, it uses an array like Alex's
solution, but with slightly fewer instructions.  So all it really adds to
suggestions already posted is a technique for reporting results as the
original example suggests: runs of heads first sorted by descending run
length, followed by runs of tails sorted by ascending run length, with no
run lengths missing.

-- Dick

post script:

local sArray,sChar,sCount,sMax

on mouseUp
ask "enter a comma-delimited sequence of H's and T's" \
with "T,T,H,T,T,H,H,H,T,T,H,T,H,H,H,T,H,T,H,T"
recordFlips it
putResults
end mouseUp

on recordFlips pSequence
put "" into sArray
put char 1 of pSequence into sChar
put 0 into sCount
put 0 into sMax
repeat for each item tChar in pSequence
recordFlip tChar
end repeat
end recordFlips

on recordFlip pChar
if pChar = sChar then
if sCount > sMax then
put sCount into sMax
end if
else
put pChar into sChar
put 1 into sCount
end if
end recordFlip

on putResults
-- note: fill in any missing runs
put the keys of sArray into tKeys
repeat with i = 1 to sMax
if sArray["H",i] is empty then put 0 into sArray["H",i]
if sArray["T",i] is empty then put 0 into sArray["T",i]
end repeat
-- note: sort runs of heads descending, then runs of tails ascending
put the keys of sArray into tKeys
sort tKeys numeric descending by sortKey(each)
-- note: put the results
put ""
repeat for each line tKey in tKeys
put item 1 of tKey && "x" && item 2 of tKey & ":" && sArray[tKey] & cr
after msg
end repeat
end putResults

function sortKey pKey
if item 1 of pKey is "H" then put item 2 of pKey into tSortKey
else put 0 - item 2 of pKey into tSortKey
return tSortKey
end sortKey

```