发新话题
移动帖子 加入精华 加入置顶 加入收藏 关注此帖

5n个人围成圈,报数为m的出局顺序问题



5n个人围成圈,报数为m的出局顺序问题

 n个人围成一圈,从第一个人开始依次从1到m循环报数,当报到m的时候此人出圈,然后从下一个人开始重新报数,直到圈中只剩一人为止.打印出最后一个人的原始编号和出圈序列
import java.util.ArrayList;
import java.util.List;

public class TestCircle {
  public static void to(int total, int number) {
    List<Integer> list = new ArrayList<Integer>(total);
    for (int i = 1; i <= total; i++) {
      list.add(i);
    }
    int begin = -1;
    while (total > 0) {
      begin += number;
      System.out.println(list.remove(begin % total));
      begin = (begin % total) - 1;
      total--;
    }
  }

  /**
   * @param args
   */
  public static void main(String[] args) {
    TestCircle.to(10, 3);
  }
}
输出
2
4
1
5
3
快乐渡过每一天,减肥坚持每一天
编辑 回复 快速回复 TOP

Re:5n个人围成圈,报数为m的出局顺序问题

呵呵,不错,收藏了。
love me ,love my bug
编辑 回复 快速回复 TOP

Re:5n个人围成圈,报数为m的出局顺序问题

报数退出时个很经典的范例,学习了。
================================================
            蓝================法================典
================================================
编辑 回复 快速回复 TOP

Re:5n个人围成圈,报数为m的出局顺序问题

public class TestCircle {
public static void to(int total, int number) {
int i, r = 0;
for (i = 2; i <= total; i++)
r = (r + number) % i;
System.out.println(r + 1);

}

public static void main(String[] args) {
TestCircle.to(2, 2);
}
} 这里有一个更精简的算法,贴上,仅供参考。
================================================
            蓝================法================典
================================================
编辑 回复 快速回复 TOP

Re:5n个人围成圈,报数为m的出局顺序问题

----------------------http://michelecindy.javaeye.com
编辑 回复 快速回复 TOP

Re:5n个人围成圈,报数为m的出局顺序问题

编辑 回复 快速回复 TOP
发新话题