求一个java小程序
(1)要求500个人围成一圈,从第一个开始计数,每次计数到3该人退出,从下一个开始计数,计数到3该人退出,以此类推,循环进行,当生最后一个人时,请问他的位置是多少(2)如...
(1)要求500个人围成一圈,从第一个开始计数,每次计数到3该人退出,从下一个开始计数,计数到3该人退出,以此类推,循环进行,当生最后一个人时,请问他的位置是多少
(2)如果是十个人,是否能通过编程显示中间过程 展开
(2)如果是十个人,是否能通过编程显示中间过程 展开
2个回答
展开全部
简单写了一个,你参考一下吧:
import java.util.*;
public class t
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("输入总人数:");
int n = sc.nextInt();//总人数
int count = 0;//记录出局的人数
int index = 0;//人的序号
int[] array = new int[n];
while(count != n - 1)
{
for(int i = 0;i < 3;i++)
{
if(array[index++] == 1)
{
i--;
}
if(index == n)
{
index = 0;
}
}
if(index == 0)
{
array[n-1] = 1;
}else{
array[index-1] = 1;
}
System.out.println((index==0?n:index)+"号出列");
count ++;
}
for(int i = 0;i < n;i++)
{
if(array[i]==0){
System.out.println("最后剩下的是" + (i+1) + "号");
}
}
}
}
2013-10-05
展开全部
package random;
import java.util.LinkedList;
public class Circular {
LinkedList<Integer> circle;
int counter;
int size;
public Circular(int n){
counter = -1;
size = n;
circle = new LinkedList<Integer>();
for (int i = 1; i<= n; i++){
circle.add(i);
}
}
public boolean stop(){
return circle.size() == 1;
}
public void removeNext(){
for (int i = 0; i < 3; i++){
if (counter < size -1){
counter++;
} else {
counter = 0;
}
}
circle.remove(counter);
counter--;
size--;
}
public void start(boolean print){
while (!stop()){
if (print){
print();
}
removeNext();
}
System.out.println("The last person is: "+ circle.peek());
}
public void print(){
String queue = "";
for (Integer i :circle){
queue += i + " -> ";
}
System.out.println(queue);
}
public static void main(String[] args) {
Circular game1 = new Circular(500);
game1.start(false);
Circular game2 = new Circular(10);
game2.start(true);
}
}
import java.util.LinkedList;
public class Circular {
LinkedList<Integer> circle;
int counter;
int size;
public Circular(int n){
counter = -1;
size = n;
circle = new LinkedList<Integer>();
for (int i = 1; i<= n; i++){
circle.add(i);
}
}
public boolean stop(){
return circle.size() == 1;
}
public void removeNext(){
for (int i = 0; i < 3; i++){
if (counter < size -1){
counter++;
} else {
counter = 0;
}
}
circle.remove(counter);
counter--;
size--;
}
public void start(boolean print){
while (!stop()){
if (print){
print();
}
removeNext();
}
System.out.println("The last person is: "+ circle.peek());
}
public void print(){
String queue = "";
for (Integer i :circle){
queue += i + " -> ";
}
System.out.println(queue);
}
public static void main(String[] args) {
Circular game1 = new Circular(500);
game1.start(false);
Circular game2 = new Circular(10);
game2.start(true);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询