服务器之家

服务器之家 > 正文

java实现的海盗算法优化版

时间:2020-12-02 10:41     来源/作者:超级学渣渣

本文实例讲述了java实现的海盗算法。分享给大家供大家参考,具体如下:

前面介绍了《C#实现的海盗分金算法》,这里再给出一个Java优化版的算法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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程序设计有所帮助。

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部