The TokenPass problem from the 2013 AP Computer Science Exam is typical of free response problems that test arrays.

TokenPass is #2 from the from the 2013 AP Computer Science A Free Response problems.

http://media.collegeboard.com/digitalServices/pdf/ap/apcentral/ap13_frq_comp_sci.pdf

## TokenPass Part (a): TokenPass constructor

```
public TokenPass(int playerCount)
{
board = new int[playerCount];
for(int i = 0; i < board.length; i++)
board[i] = (int) (Math.random() * 10 + 1);
currentPlayer = (int) (Math.random() * playerCount);
}
```

A regular for loop through board is necessary for initialization of each element. A foreach loop won’t work since changes will not affect the array itself.

Math.random returns a value in the range of 0 <= r < 1. Multiplying the result by 10 and casting to an int results in values in the range of 0 <= r <= 9. Adding one results in the desired range of 1 <= r <= 10.

currentPlayer must be set to a random valid index in board. This is a very common task that can be accomplished by multiplying the return value of Math.random by the length or size of the structure and casting the result to an int.

See my Random number generation practice problem for additional practice and explanation.

## TokenPass Part (b): distributeCurrentPlayerTokens

```
public void distributeCurrentPlayerTokens()
{
int tokens = board[currentPlayer];
board[currentPlayer] = 0;
int targetIndex = currentPlayer + 1;
while(tokens > 0)
{
if(targetIndex == board.length)
targetIndex = 0;
board[targetIndex]++;
tokens--;
targetIndex++;
}
}
```

This problem requires traversal of an array with modification of each element, which precludes a foreach loop. This solution loops while there is at least one token remaining to distribute. A for loop that runs for the number of tokens is also possible.

There are 2 common approaches to ensuring that targetIndex remains a valid index in board. The solution above explicitly checks for validity and resets targetIndex to 0 when it exceeds the array bounds. An alternative is to use modular division (%) to constrain targetIndex.

## 2013 AP CS Exam Free Response Solutions |

On your first answer, Math.random() * 10 + 1 would give values between 1 and 11, not 1 and 10.

`Math.random()`

never returns 1. The code works as intended.In part b in the if statement shouldn’t you also increment board[targetIndex] and decrement tokens–?