import java.util.*; public class Room { public static void main(String args[]) { ArrayList list = new ArrayList(); for(int i=1;i<10;i++) { list.add(i+""); } int j=1;int k=0; while(list.size()>1) { if(k>=list.size()) { k=0; } if(j==5) { System.out.print(list.get(k)+"-"); list.remove(k); j=0; k--; } j++; k++; } System.out.println(list.get(0)); } }
class er { public static void main(String[] args) { StringBuffer x=new StringBuffer("123456789"); int index = 0; for(int i = 0; x.length() > 1/*改了这里*/;i++) { if(i == 4) { //x.delete(index-1,index); x.deleteCharAt(index); //改了这里 i=0; System.out.println(x); } index++; if(index>=x.length() ) //改了这里 index = 0; } System.out.println("最后一个数:" + x); } }
约瑟夫环问题,很经典的,我来个HashMap的来实现这个的,效率怎么样,看你要做什么了: package test02; import java.io.*; import java.util.*; public class ChoosePerson { private int n; private int flag; public ChoosePerson() { this.initialization(); } private void initialization(){ boolean f = true; while(f){ System.out.print("请输入总人数:"); try{ n = input(); }catch(IOException ae){ ae.printStackTrace(); continue; }catch(NumberFormatException be){ be.printStackTrace(); continue; } f = false; } f = true; while(f){ System.out.print("输入出圈时报到的数字:"); try{ flag = input(); }catch(IOException ae){ ae.printStackTrace(); continue; }catch(NumberFormatException be){ be.printStackTrace(); continue; } f = false; } } public static int input() throws IOException,NumberFormatException{ int n = 0; InputStreamReader ir = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir); n = Integer.parseInt(br.readLine()); return n; } public void choose(){ LinkedHashMap<Integer,String> lhmp = new LinkedHashMap<Integer,String>(); String s = null; for(int i = 0 ; i < n ; i++){ s = "第" + (i+1) + "号"; lhmp.put(i , s); } Object[] num = lhmp.keySet().toArray(); int count = 0; int order = 1; System.out.println("将这些人分别标记为1-" + n +"号,依次出列的情况如下:"); while(lhmp.size() != 1){ for(int i = 0 ; i < num.length ; i++){ count++; if(count % flag == 0){ if(order < 10){ System.out.println("第 " + (order++) + "个出列的人 : " + lhmp.get(num[i])); } else System.out.println("第" + (order++) + "个出列的人 : " + lhmp.get(num[i])); lhmp.remove(num[i]); } } num = lhmp.keySet().toArray(); } System.out.println("最后剩下的人为 : " + lhmp.get(num[0])); } /** * @param args */ public static void main(String[] args){ ChoosePerson c = new ChoosePerson(); c.choose(); } }