将类创建并添加到数组会导致奇怪的结果-Java

时间:2018-09-03 08:55:46

标签: java brute-force

我一直沉迷于无法解释自己的代码行为。我将发布相关代码,然后提出问题:

//Uses brute force and existing functions to create and check for equilibria
static void getEquis(List<Integer> values, int depth) {
  if (values.size() == depth) {
    for(int i = 0; i < numOfAgents; i++) {
      agents[i].setVote(values.get(i).intValue());
    }
    for(int i = 0; i < numOfAgents; i++) {
      agents[i].setDoVote(true);
      if(isEqui()==true) {
        int votes[] = new int[numOfAgents];
        boolean doVotes[] = new boolean[numOfAgents];
        for(int j = 0; j < numOfAgents; j++) {
          votes[j] = 5;
          doVotes[j] = true;
          //votes[j] = agents[j].getVote();
          //doVotes[j] = agents[j].getDoVote();
        }
        addEqui(new Equi(votes, doVotes));
      }
      agents[i].setDoVote(false);
      if(isEqui()==true) {
        int votes[] = new int[numOfAgents];
        boolean doVotes[] = new boolean[numOfAgents];
        for(int j = 0; j < numOfAgents; j++) {
          votes[j] = 5;
          doVotes[j] = true;
          //votes[j] = agents[j].getVote();
          //doVotes[j] = agents[j].getDoVote();
        }
        addEqui(new Equi(votes, doVotes));
      }
    }

请注意,我故意将评论(votes [j] = agent [j] .getVote();)留在其中,因为这是应该做的事,票数[j] = 5;和以下行仅用于测试。

private static class Equi
{
  private int vote[] = new int[numOfAgents];
  private boolean doVote[] = new boolean[numOfAgents];   

  public Equi(int[] votes, boolean[] doVotes)
  {
    for(int i = 0; i < numOfAgents; i++) {
      this.vote[i] = votes[i];
      this.doVote[i] = doVotes[i];      
    }
  }
  public int[] getVote() {
    return this.vote;
  }
  public boolean[] getDoVote() {
    return this.doVote;
  }
  public void print() {
    for(int i = 0; i < numOfAgents; i++) {
      System.out.println("Agent " + (i+1) + ": " + agents[i].doVote + " Wahl: " + agents[i].vote);
    }
    System.out.println("Solution: " + computeMean());
  }
}

//Adds a new equilibrium to the equilibria array
public static void addEqui(Equi equi)
{ 
  Equi store[] = new Equi[equilibria.length + 1]; 
  for(int i = 0; i< equilibria.length; i++) {
    store[i] = equilibria[i];
  }
  store[equilibria.length] = equi;
  equilibria = store;
}

现在,如果我打印出均衡数组的结果,我将得到

  

代理商1:错误的Wahl:100代理商2:错误的Wahl:100解决方案:0.0代理商   1:错误的Wahl:100代理2:错误的Wahl:100解决方案:0.0代理1:   假Wahl:100特工2:假Wahl:100解决方案:0.0特工1:假   瓦尔:100特工2:假瓦尔:100解决方案:0.0

这是通过在main中运行它来实现的:

for(int i = 0; i < equilibria.length; i++) {
  equilibria[i].print();
}

以我的理解,它应该总是给我5个真实值,但是这种行为对我来说很奇怪。您对此有解释吗?如果您需要代码的其他任何部分,请发表评论,我将对其进行编辑和添加。

0 个答案:

没有答案