18. While Loop Example
This example models a competition among a group of players where each player achieves a set of points and there is a prize for the individual highest score. If there is a tie for the highest score, then the next highest score among those tied is considered to break the tie.First we find all occurrences of the maximum score, then eliminate duplicates using sort with the uniq option. Then the tied players scores are copied and sorted in decreasing order:
% cat while.ss
srand 1374760505; // just to make the docs reproducible, // remove to use default srand(time()) // players // a0:a4 = { "Rick", "Phil", "Harry", "Sam", "Joe" }; // simulated scores // b0:g4 = { irand(11) }; // find all occurrences of max score // {h0,h1:i1} = find(b0:g4,max(b0:g4)); eval; // range 1...h0 in column c // #define H0(c) Cell(c,1):Cell(c,h0) // column j will hold the unique row indices from column i // copy H0("j") H0("i"); sort H0("j") uniq j0; // n will remain constant while j0 counts down to zero // n = j0; eval symbols; format "%g"; print; // source and destination for copy // #define N 5 // number of players #define C1 "a" // start column for scores #define CM "g" // end column for scores #define RROW n-j0 // row index for find result #define SROW cell("j",RROW) // source row from find result #define DROW N+RROW // destination row #define SRC Cell(C1,SROW):Cell(CM,SROW) #define DEST(c1,cM) Cell(c1,DROW):Cell(cM,DROW) // copy and sort the tied players scores // while( j0-- > 0) { copy DEST(C1,CM) SRC; sort DEST(CM,C1); } print Cell(C1,N+1):Cell(CM,N+n);
% SS while.ss A B C D E F G H I J 0 Rick 7 10 9 8 0 2 5 3 1 Phil 6 7 4 7 9 5 2 0 0 2 Harry 9 10 1 9 8 10 2 2 2 3 Sam 10 10 2 1 7 2 6 2 3 4 Joe 9 1 3 4 9 8 1 3 5 2 3 A B C D E F G 6 Rick 10 9 8 7 2 0 7 Harry 10 10 9 9 8 1 8 Sam 10 10 7 2 2 1H0 is the number of times the highest score occurred (5), and H1:I5 are the corresponding column and row positions. J0 is the number of unique players with the highest score (3), and J1:J3 are the corresponding row positions.
The result is that Rick, Harry, and Sam are tied for the highest score. Looking at their next highest scores, Harry and Sam are still tied but Rick is eliminated, and then the next next highest scores show that Harry is the winner with 9 points vs. Sam's 7.