开发者

What's that elegant modulo that I can't figure out?

开发者 https://www.devze.com 2022-12-19 21:20 出处:网络
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.

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 d开发者_JAVA技巧o 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;
}


(startPos + numberOfPlayers - 1) % numberOfPlayers


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号