Josephus算法:比如一群小孩围成一圈,任意假定一个数字m,从第一个小孩起,顺时针方向数,每数到第m个小孩时,该小孩便出局;随小孩不断离开圈子不断缩小,最后剩下一个小孩便是胜利者。该算法用数组循环实现,但数组是线性排列的,而小孩是围成圈的,使用"加1求模"的方法解决循环!
程序如下:
import java.io.*;
class Josephus
{
public static void main(String[] args)
{
int num=10;
int interval=2;
int[] a=new int[num];
for(int i=0;ia[i]=i+1;
System.out.println("please input the interval: ");
try
{InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String s=br.readLine();
interval=Integer.parseInt(s);
}
catch(Exception e)
{System.out.println(e);
}
for(int i=0;iSystem.out.print(a[i]+" ");
System.out.print(" ");
int k=1;
int i=-1;
while(true)
{
for(int j=0;j{i=(i+1)%num;
if(a[i]!=0)
j++;
}
if(k==num) break;
System.out.print(a[i]+" ");
a[i]=0;
k++;
}
System.out.print(" No. "+a[i]+" boy´ve won. ");
}
}[@more@]
程序如下:
import java.io.*;
class Josephus
{
public static void main(String[] args)
{
int num=10;
int interval=2;
int[] a=new int[num];
for(int i=0;ia[i]=i+1;
System.out.println("please input the interval: ");
try
{InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String s=br.readLine();
interval=Integer.parseInt(s);
}
catch(Exception e)
{System.out.println(e);
}
for(int i=0;iSystem.out.print(a[i]+" ");
System.out.print(" ");
int k=1;
int i=-1;
while(true)
{
for(int j=0;j{i=(i+1)%num;
if(a[i]!=0)
j++;
}
if(k==num) break;
System.out.print(a[i]+" ");
a[i]=0;
k++;
}
System.out.print(" No. "+a[i]+" boy´ve won. ");
}
}[@more@]
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9650775/viewspace-923906/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/9650775/viewspace-923906/