views:

96

answers:

2

What's a good way to determine the following.

You have a table of game players, in an array of size N. Each round, each player takes a turn.

You know the index of the player that should go first, and each player will take a turn ascending the array, and looping back to 0 when it hits the last index. For example, if player at index 3 went first, then 4 would go second, and 2 would go last.

How do you calculate the index of the player that goes last in the round?

Here's one way:

var startPosition = 3;
var numberOfPlayers = 10;

for (var i=0;i<numberOfPlayers;i++) {
  startPosition++;
  if (startPosition == numberOfPlayers) startPosition = 0;
}
+1  A: 

Isn't the result always the startPosition > 0 ? startPosition - 1 : numberOfPlayers - 1, i.e. it's always one less than the startPosition except for the case when the startPosition is 0..

The even more "elegant" modulo could be something like (startPosition + numberOfPlayers - 1) % numberOfPlayers.

Thomas Wanner
I was going to post this too, but felt stupid. I thought I was missing something in the question.
Kylar
It also seems a little bit trivial for me, but probably that's really what Andrew wanted..
Thomas Wanner
Yeah, that's what I was looking for... I knew it was trivial when I came looking for it, but for some reason I couldn't figure it out :P
Andrew Johnson
+6  A: 
(startPos + numberOfPlayers - 1) % numberOfPlayers
Ignacio Vazquez-Abrams
this is even better than the modulo I initially posted, I was not sure what (-1 % n) is :)
Thomas Wanner
The worst part is that the result of `-1 % n` depends on what language your using.
Ignacio Vazquez-Abrams