JosephRing.java 1001 B

1234567891011121314151617181920212223242526272829303132333435
  1. package org.yuesefu;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Scanner;
  5. public class JosephRing {
  6. public static void main(String[] args) {
  7. Scanner scanner=new Scanner(System.in);
  8. System.out.println("请输入人数n和m的值(m为1~5之间的整数):");
  9. int n = scanner.nextInt();
  10. int m = scanner.nextInt();
  11. scanner.close();
  12. List<Integer> people = new ArrayList<>();
  13. for (int i = 1; i <= n; i++) {
  14. people.add(i);
  15. }
  16. josephRing(people, m);
  17. }
  18. public static void josephRing(List<Integer> people, int m) {
  19. int count = 0;
  20. int index = 0;
  21. while (!people.isEmpty()) {
  22. count++;
  23. index = (index + 1) % people.size();
  24. if (count == m) {
  25. System.out.print(people.get(index) + ", ");
  26. people.remove(index);
  27. count = 0;
  28. }
  29. }
  30. }
  31. }