代码之家  ›  专栏  ›  技术社区  ›  Woot4Moo

交叉算法实现

  •  4
  • Woot4Moo  · 技术社区  · 15 年前


    Father = [A,B,B,A,C]
    Mother = [D,D,B,A,A]

    void reproduce(String[] father, String[] mother) {
    double choice = Math.random() * 100;
    if((int) choice % 10 < 2){
    //start at father[1] and swap.
    //Continue for other choices

    这是一个小部分,我正在使用的逻辑。所以我的问题又回到了,我如何合理地决定何时停止创造孩子?或者这只是一个数学问题,我应该只看一个直接的置换生成器,而暂时忽略遗传算法?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Ishtar    15 年前

    首先,这应该是一个不太坏的方法,使一个孩子从父母。这是单点交叉。

    public String[] reproduce(String[] father, String[] mother) {
      int[] child=new String[father.length];
      int crossPoint = Math.random()*father.length;//make a crossover point
      for (int i=0;i<father.length;++i)
      {
        if (i<crossPoint)
          child[i]=father[i];
        else
          child[i]=mother[i];
      }
      return child;
    }
    

    没有咖啡,所以没有保证。你可能要检查一个错误。

        2
  •  1
  •   AmaDaden    15 年前

    因为你用随机数来做改变,你不能保证在X个孩子之后你会尝试一切。如果你想尝试每个选项,你不应该使用随机数。所以是的,用一个直接排列发生器,忽略遗传算法。