⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smoother.java

📁 经典的货郎担问题解决办法
💻 JAVA
字号:
/*** This code was written by Kent Paul Dolan, from scratch.  So far as I** know, it is an original (though obvious) algorithm.  See accompanying** file TravellerDoc.html for status for your use.*/package com.well.www.user.xanthian.java.genetic.reproducers.asexual;import com.coyotegulch.tools.*;import com.coyotegulch.genetic.*;import com.well.www.user.xanthian.java.genetic.*;import com.well.www.user.xanthian.java.tools.*;import com.well.www.user.xanthian.java.ui.*;public class Smoother    implements AsexualReproducer{/*** Because we do (perhaps may times) N*( M! ) permutations, we cannot** afford the computational burden of the global permute limit; support** a local one as well.  Unlike Optimize Near A Point, we are not helped** particularly by favorable geometry as we approach the solution,** either, and for large genomes, our worst case is our usual case.** ** FIXME Tune this limit; the algorithm grows immensely more powerful** with increased limit, but it also grows sloooooow!*/  private static final int LOCAL_PERMUTE_LIMIT = 6;  private static boolean DB = false;  private static boolean VDB = false;  private static VisualDebugger m_vdb = null;  public Chromosome reproduce(Chromosome parent)  {    try    {/*** Debugging hook abbreviation.  During development, turn on debugging** just for this class by setting this variable to true, here.  When the** code is stable, set it to false here, and control debugging from the** checkbox controls panel, instead.  This variable is global to this** class, so it controls debugging thoughout the class when set here at** the top of the entry method for the class.*/      DB = false;      if (CheckBoxControls.getState(CheckBoxControls.CBC_DEBUG_PRINTOUTS))      {        DB = true;        System.out.println        (          "Entered Smoother.reproduce( Chromosome parent)"        );      }/*** Pass the input as a less burdensome type.*/      TravellerChromosome child = algorithm( (TravellerChromosome) parent );      child.setOriginator( "Smoother" );      child.checkValidity();      return (Chromosome) child;    }    catch (Exception e)    {      System.err.println      (        "Smoother.reproduce() threw!"      );    }/*** This code should never be reached, it is just here to pacify javac.*/    return parent;   }  private TravellerChromosome algorithm( TravellerChromosome parent )  {    VDB = false;    if (CheckBoxControls.getState(CheckBoxControls.CBC_DEBUG_VISUAL_WINDOWS))    {      VDB = true;    }    if (VDB)    {      if ( m_vdb == null )      {        m_vdb = new VisualDebugger( "Smoother" );      }    }    else    {      if ( m_vdb != null )      {        m_vdb.closeWindow();        m_vdb = null;      }    }    if (VDB) { m_vdb.toFront(); }    MersenneTwister mt = MersenneTwister.getTwister();    TravellerChromosome offspring = new TravellerChromosome( parent );    offspring.canonicalize();    double startingFitness = offspring.testFitness();    if (VDB) { m_vdb.setup( offspring ); }    TravellerWorld world = parent.getWorld();    int genomeLength = ValuatorControls.getNumberOfCities();/*** To cut off N points, we need N + 1 cleavage indices; the rest of the** genome acts as the N+1st permutee.*/    int permuteSize = 1 + ( new PermutationController() )      .getAPermuteSize      (        Math.min        (          genomeLength - 1,          LOCAL_PERMUTE_LIMIT        )      );    int cleavageIndices[] = new int[permuteSize];    pickCleavageIndices( cleavageIndices, genomeLength, mt );    int failureCount = 0;    while( failureCount < genomeLength )    {      if ( bladeful( cleavageIndices, offspring, world, mt ) )      {        failureCount = 0;      }      else      {        failureCount++;      }      advanceBlade( cleavageIndices, genomeLength );      if (VDB) { m_vdb.step( offspring ); }    }/*** Who knows what order the result has?  Better fix it.*/    offspring.canonicalize();    double finalFitness = offspring.testFitness();/*** We only change for the better, so if we haven't changed, we haven't** improved.  Report back so that adaptive permutation high limit can** eventually be updated.*/    if    (      Math.abs( finalFitness - startingFitness )      <      TravellerStatus.LITTLE_FUZZ    )    {      PermutationController.reportFailure();    }    else    {      PermutationController.reportSuccess();    }    if (VDB) { m_vdb.done( parent, offspring ); }    return offspring;   }  private boolean inList( int c, int list[] )  {    for (int i = 0; i < list.length; i++)    {      if (c == list[i]) { return true; }    }    return false;  }  private int listIndex( int c, int list[] )  {    for (int i = 0; i < list.length; i++)    {      if (c == list[i]) { return i; }    }    return -1;  }  private boolean bladeful  (    int cleavageIndices[],    TravellerChromosome mutant,    TravellerWorld world,    MersenneTwister mt  )  {    double fitnessAtStart = mutant.testFitness();    if (DB)    {      System.out.println( fitnessAtStart + " fitness at start of bladeful" );    }/*** Create a local _copy_ of the input parameter; remind self not to** scribble on it!*/    TravellerChromosome readOnlyVersion = new TravellerChromosome( mutant );    int permuteSize = cleavageIndices.length;    int genomeLength = ValuatorControls.getNumberOfCities();    PermutationGenerator pg = new PermutationGenerator( permuteSize, false );/*** Create cleavage point auxiliary arrays.*/    int sublistBeginCities[]   = new int[permuteSize];    int sublistEndCities[]     = new int[permuteSize];    for (int i = 0; i < permuteSize; i++)    {      sublistBeginCities[i] = -1;      sublistEndCities[i] = -1;    }/*** Fill in auxiliary array information.  For computing relative fitness,** we don't need the whole sublists, the interior lengths don't change.** We just need the end points to connect to each other.*/    for (int i = 0; i < permuteSize; i++)    {      sublistBeginCities[i] = mutant.getCity(cleavageIndices[i]);      sublistEndCities[i]   =        mutant.getCity        (          (            cleavageIndices[(i + 1) % permuteSize]            - 1            + genomeLength          ) % genomeLength        );    }    int bestPermutation[] = new int[permuteSize];/*** Choose the original configuration as the best found, for a start.*/    for (int i = 0; i < permuteSize; i++)    {      bestPermutation[i] = i;    }    double bestFitness = Double.MAX_VALUE;    Integer [] nextPermutation = null;    while ( pg.morePermutations() )    {      try      {        nextPermutation = pg.getNext();      }      catch (Exception e)      {        System.out.println        (          "caught pg.getNext() throw in Smoother"        );      }      double currentFitness = 0.0D;      for (int i = 0; i < permuteSize; i++)      {        int nextIndex = ( i + 1 ) % permuteSize;        currentFitness +=          world.getDistance         (           (             sublistEndCities[nextPermutation[i].intValue()]           ),           (             sublistBeginCities[nextPermutation[nextIndex].intValue()]           )         );      }      if (currentFitness < bestFitness)      {        bestFitness = currentFitness;        // Notice that this time we are actually capturing the        // permutation rather than what it indexes; we have a        // bunch of work to do to construct the final product        // mutant at the end of all this foolishness.        for (int i = 0; i < permuteSize; i++)        {          bestPermutation[i] = nextPermutation[i].intValue();        }      }    }    // We are going to scribble on mutant, so use the local name of    // the input parameter as an unclobbered data source for city names.    // Starting at the beginning of the output chromosome, mutant,    // write the sublists in their permuted order, flipped as needed.    int writeToIndex = 0;    for (int i = 0; i < permuteSize; i++)    {      int currentCleavageIndicesIndex = bestPermutation[i];      int nextCleavageIndicesIndex =        ( currentCleavageIndicesIndex + 1 ) % permuteSize;      int currentChromosomeIndex =        cleavageIndices[currentCleavageIndicesIndex];      int nextChromosomeIndex =        ( cleavageIndices[nextCleavageIndicesIndex] - 1 + genomeLength )        % genomeLength;      int j = currentChromosomeIndex;      while ( true )      {        mutant.setCity( writeToIndex, readOnlyVersion.getCity(j));        writeToIndex++;        if ( j == nextChromosomeIndex ) { break; }        j = ( j + 1 ) % genomeLength;      }    }/*** This is dubious; we are modifying mutant during the cycle.  Luckily,** this only changes mutant at the beginning and end of the genome** array, and we also walk the array from end to end.  Still, the first** two steps and the last two steps may rearrange the genome under us,** so this algorithm isn't perfect.  The alternative, used in Dewrinkler** where it is unavoidable, is to new() a temp copy of the genome and** canonicalize so that we can test its fitness.*/    mutant.canonicalize();    // System.out.println( mutant.toString() );    double fitnessAtEnd   = mutant.testFitness();    // System.out.println( fitnessAtEnd + " fitness at end of bladeful " );    return ( ( fitnessAtStart - fitnessAtEnd ) > TravellerStatus.LITTLE_FUZZ );  }  private void pickCleavageIndices  (    int cleavageIndices[],    int genomeLength,    MersenneTwister mt  )  {    int permuteSize = cleavageIndices.length;    for (int i = 0; i < permuteSize; i++)    {      cleavageIndices[i] = i;    }  }  private void advanceBlade  (    int cleavageIndices[],    int genomeLength  )  {    for ( int i = 0; i < cleavageIndices.length; i++ )    {      cleavageIndices[i] = ( (cleavageIndices[i] + 1 ) % genomeLength) ;    }    // System.out.println( Debugging.dump( cleavageIndices ) );  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -