java中遇到的类似约瑟夫问题

本文讲述暑假学习Java时遇到的类似约瑟夫问题,因Java无指针,用数组实现。问题是M位食客围坐圆桌,从begin号开始报数,报到N的离席,最后留下的请客。程序通过数组模拟,不断循环,直至数组只剩一个非0元素,输出该元素对应食客编号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

暑假中学习java过程中遇到的类似的约瑟夫问题,由于java没有指针, 所以有数组实现.

/*问题描述:
 *假设M位食客围坐圆桌边,按顺时针依次编号。从begin(begin<=M)号食客开始按顺时针不断报数,
 *报数时依次从1~N,报到N的食客离席,由下位食客继续从1开始报数,最后留下的那位请客。
 *例如M=5,N=3,begin=1时,将由4号食客请客;M=5,N=3,begin=1时,将由1号食客请客。(N不一定小于M)
 *
 *程序主要运用数组进行模拟,通过不断的循环,实现数组中只有一个元素不为0,则该元素的值就是
 *食客的编号。
 *该问题类似约瑟夫问题,这是不用C++中的结构类型和指针来实现的一种代码。
 *Finish at 2005/08/06
*/
import java.io.*;
public class RoundTable{
 public static void main(String args[]){
  //M表示人数
  int M;
  //N表示报数得最大值
  int N;
  //begin表示开始报数的位置
  int begin;
  //进入循环,当用户输入M的值小于0时,退出
  while(true){
  try{
  System.out.println("if you want to end the program,you should initialize the M

<=0");
  System.out.print("Please input the M:");
  BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
  String input0=in.readLine();
  M=Integer.parseInt(input0);
  if(M<=0)break;//当M<=0,退出
  System.out.print("Please input the N:");
  String input1=in.readLine();
  N=Integer.parseInt(input1);
  System.out.print("Please input the begin:");
  String input2=in.readLine();
  begin=Integer.parseInt(input2);
  }catch(Exception exc){
   System.out.println("Input Error!");
   continue;
  }if(N<=0||begin<=0){
   System.out.println("N or begin can't be the NEGATIVE!");
   continue;    //当N或begin小于0时,重新输入
  }
  //创建一个长度为M的数组
  int []array=new int[M];
  //初始化数组,使数组元素的值为1~M
  for(int i=0;i<M;i++){
   array[i]=i+1;
   }
  //声明变量count1,count2作为计数器
  int count1,count2,check=0;
  count1=1;
  //count2的值初始化为开始的位置
  count2=begin;
  //进入循环,直到check=M-1
  while(true){
   if(count1%N==0&&array[count2-1]!=0){
    array[count2-1]=0;
    check++;
    }
   count2++;
   if(count2>M)count2=count2-M;
   if(array[count2-1]!=0)count1++;
   if(M-check==1)break;
   }
  //输出
  for(int i=0;i<M;i++){
   if(array[i]!=0)System.out.println("该由第"+array[i]+"食客请客!");
   }
  }
 System.out.println("The End!/nThank You For Using!");
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值