Java實現約瑟夫環
約瑟夫環問題是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重複下去,直到只剩1人。
(1)定義一個Person類,該類有成員屬性name、age,成員方法toString,將name和age屬性的值作為字串返回,為該類編寫構造方法。
(2)使用泛型定義一個順序表類OrderList,參考上課所講內容及資料結構相關要求完成該類。
(3)定義測試類,在改類中建立n個Person類的物件並插入順序表中,從第1個人開始數數到第m個人時刪除,然後接著從下一個人開始數,數到第m
Person.java
public class Person {
String name;
int age;
public Person(){}
public Person(String S,int a)
{this.name=S;
this.age=a;}
public String toString()
{return "姓名: "+name+"年齡: "+age;}
}
OrderList.java
public class OrderList<Type1> {
Type1 orderlist[];
int Length;
public OrderList()
{
this.Length=0;
}
boolean isFuLL()
{
if(Length==orderlist.length)
return true;
else
return false;
}
boolean isEmpty()
{
if(Length==0)
return true;
else
return false;
}
void insert(Type1 p)
{
if(isFuLL())
{System.out.print("線性表已經滿了,不能插入元素了!");
System.out.println();
return ;}
orderlist[Length]=p;
Length++;
}
void insert(Type1 p,int i)
{
if(isFuLL())
{
System.out.print("線性表已經滿了,不能插入元素了!");
System.out.println();
return ;
}
for(int j=Length;j>i;j--)
orderlist[j]=orderlist[j-1];
orderlist[i]=p;
Length++;
}
Type1 delete(int i)
{
if(isEmpty())
{
System.out.print("線性表已經空了,不能再刪除元素了!");
System.out.println();
return null;
}
if(i>=Length)
{
System.out.print("刪除位置錯誤,不能再刪除元素了!");
System.out.println();
return null;
}
Type1 p=orderlist[i];
for(int j=i;j<Length-1;j++)
orderlist[j]=orderlist[j+1];
Length--;
return p;
}
}
joserf.java
public class joserf <Type1>{
OrderList<Type1>jos=null;
void killed(int m,int n)
{
int k;
while(jos.Length>1)
{
k=(m+n-1)%jos.Length;
Type1 p=jos.delete(k);
System.out.print(p.toString()+" 被殺");
System.out.println();
}
System.out.print(jos.orderlist[0].toString()+" 赦免");
System.out.println();
}
}
Test.java
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
System.out.print("請輸入總人數:");
int n;
n=cin.nextInt();
int i;
OrderList<Person>p=new OrderList<Person>();
p.orderlist=new Person[n];
Scanner str=new Scanner(System.in);
Person p2[]=new Person[n];
for( i=0;i<n;i++)
{
p2[i]=new Person();
p2[i].name=str.nextLine();
p2[i].age=cin.nextInt();
}
for( i=0;i<n;i++)
{
p.insert(p2[i] );
}
joserf<Person>j=new joserf<Person>();
j.jos=p;
int m;
System.out.print("請輸入要數的數:");
System.out.println();
m=cin.nextInt();
j.killed(m, n);
}
}