今天就跟大家聊聊有关怎么在java项目中实现一个海盗算法,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
具体方法如下:
package unit4;public class Pirate{ private String name; private int[] schemes; private int index; public Pirate(int t,int i) { name="unknow"; index=i; schemes=makeSchemes(t); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getIndex(){return index;} public int[] getSchemes() {return schemes;} public int handvote(int table[]) { return myhandvote(table,index); } private int myhandvote(int []t,int i) { if(t[i]==0) return 0; if(i==1) return 0; return 1; } public int[] makeSchemes(int t) { int vote=0; schemes =new int[t-index]; do{ for(int i=0;i<schemes.length;i++){ schemes[i]=(i+1)%2; } for(int i=0;i<schemes.length;i++){ vote=vote+myhandvote(schemes,i); } }while(!(2*vote>t/2)); return schemes; }}
package unit4;public class Judger { int[] allot; Pirate[] pirates; public Judger(Pirate []pirates,int[]a) { this.pirates=pirates; allot=a; } public int[] getAllot() { return allot; } public void setAllot(int[] allot) { this.allot = allot; } public Pirate[] getPirates() { return pirates; } public void setPirates(Pirate[] pirates) { this.pirates = pirates; } public boolean evaluate(){ int vote=0; for(int i=0;i<pirates.length;i++){ vote+=pirates[i].handvote(allot); } if(2*vote>=pirates.length) return true; else return false; }}
package unit4;public class MaxInterest { public static void main(String[] args) { int piratecounts=5; Pirate[]pirates=new Pirate[piratecounts]; for(int i=0;i<piratecounts;i++){ pirates[i]=new Pirate(piratecounts,i); pirates[i].setName("name"+i); } int[]table =pirates[0].getSchemes(); Judger ajudge=new Judger(pirates,table); if(ajudge.evaluate()){ int[]scheme=ajudge.getAllot(); for(int i=0;i<scheme.length;i++) System.out.println(" "+scheme[i]); } }}
看完上述内容,你们对怎么在java项目中实现一个海盗算法有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网行业资讯频道,感谢大家的支持。