约瑟夫环问题(JAVA)

约瑟夫环问题(JAVA版)

【问题描述】

约瑟夫环问题是,编号为1,2,3,…,n的n个人按顺时针方向围坐一圈,每人持有一个密码。开始时任选一个正整数作为报数上限值m,从第一个人开始顺时针方向自1开始顺序报数,报到m时停止报数。报m的人出列,将他的密码作为新的m值,从他在顺时针方向上的下一个人开始重新从1报数,如此下去,直至所有人全部出列为止。

【测试数据】

标题M的初值为20,n=7,7个人的密码依次为3,1,7,2,4,8,4。则首先出列的人是6号,依次正确的出列顺序应该为6,1,4,7,2,3,5。

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;


public class ysf {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Map<Integer, Integer> map =new HashMap<Integer, Integer>();
		Scanner in =new Scanner(System.in);
		int n=in.nextInt();
		in.close();
		map.put(1, 3);
		map.put(2, 1);
		map.put(3, 7);
		map.put(4, 2);
		map.put(5, 4);
		map.put(6, 8);
		map.put(7, 4);
		int b=1,t=0;
		while(t<=7) {
			Iterator<Map.Entry<Integer, Integer>> it =map.entrySet().iterator();
			while(it.hasNext()) {
				Map.Entry<Integer, Integer> entry =it.next();
				if(b==n) {
					System.out.println(entry.getKey());
					t++;
					n=entry.getValue();
					b=0;
					it.remove();
				}
				b++;
			}
		}
	}
}
约瑟夫环问题是一个经典的数学问题,涉及到一个由`n`个人组成的环,每次数到一个特定的数字`m`,该人将被移除,然后从下一个人重新开始数,直到环中只剩下最后一个人。以下是几种Java实现约瑟夫环问题的解决方案: ### 数组模拟法 通过数组来模拟整个报数和移除人的过程。 ```java public class Josephus { public static void main(String args[]) { final int N = 13, S = 3, M = 5; int i = S - 1, k = N, g = 1, j; int a[] = new int[N]; for (int h = 1; h <= N; h++) { a[h - 1] = h; } System.out.println("出圈顺序为:"); do { i = i + (M - 1); while (i >= k) { i = i - k; } System.out.print(" " + a[i]); for (j = i; j < k - 1; j++) { a[j] = a[j + 1]; } k--; g++; } while (g <= N); } } ``` 此代码中,`N`表示总人数,`S`表示从第`S`个人开始报数,`M`表示数到`M`的人出圈。通过数组`a`来存储每个人的编号,在循环中模拟报数和移除人的操作,直到所有人都出圈 [^2]。 ### 通用输入输出法 该方案允许用户输入总人数`n`和报数上限`m`,并输出出圈序列。 ```java import java.util.Scanner; public class JosephusSolution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入总人数 n: "); int n = scanner.nextInt(); System.out.print("请输入报数上限 m: "); int m = scanner.nextInt(); boolean[] people = new boolean[n]; for (int i = 0; i < n; i++) { people[i] = true; } int count = 0; int index = 0; int outCount = 0; System.out.print("出圈顺序为:"); while (outCount < n) { if (people[index]) { count++; if (count == m) { System.out.print((index + 1) + " "); people[index] = false; count = 0; outCount++; } } index = (index + 1) % n; } scanner.close(); } } ``` 在这个代码里,使用`boolean`类型的数组`people`来标记每个人是否还在圈中。通过`Scanner`类获取用户输入的`n`和`m`,然后模拟报数和出圈过程,输出出圈顺序 [^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值