7-1 Joseph ring problem-hebust (20 points) Joseph ring problem

Review of old java questions
7-1 Joseph ring problem-hebust (20 points)
Joseph ring problem

The Joseph ring is a mathematical application problem: It is known that n people (represented by numbers a, b, c...) are sitting around a round table. Start counting from the person numbered 1, and the person who counts to m goes out; his next person starts counting from 1, and the person who counts to m goes out again; repeat this pattern until the round table is around All the people are out.

Input format:
fixed to 2 lines, the first line is m, and the second line is a list of names of n individuals, represented by English letters, and the elements are directly separated by English commas.

Output format:
one line, which is a sequence of dequeue elements, with English commas between the elements, separated [Note: there is no comma after the end element]

Input sample:
Here is a set of input. E.g:

3
a,b,c,d,e,f,g

Output sample:
The corresponding output is given here. E.g:

c,f,b,g,e,a,d

years:

import java.util.*;
public class Main {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Scanner in=new Scanner(System.in);
		int m=in.nextInt();
		String s=in.next();
		String[] arr=s.split(",");//用split将其化为字符串数组
		List<String> list=new ArrayList<>();//使用链表解决
		
		for(int i=0;i<arr.length;i++) {
    
    
			list.add(arr[i]);//添加到list中
		}
		int cnt=0;
		
		String[] ans=new String[list.size()];
		int len=0;
		while(list.isEmpty()==false) {
    
    
			Iterator it=list.iterator();
			while(it.hasNext()) {
    
    
				cnt++;
				if(cnt==m) {
    
    //当cnt==m时就将其输入到ans数组中
					ans[len++]=(String)it.next();
					it.remove();//将其从链表中移除
					cnt=0;
				}else {
    
    
					it.next();
				}
			}
		}
		for(int i=0;i<len;i++) {
    
    //输出ans数组
			System.out.print(ans[i]);
			if(i<len-1)System.out.print(",");
		}
	}
}

Guess you like

Origin blog.csdn.net/timelessx_x/article/details/111906627