tselect.cpp

来自「一个遗传算法(GA)的实现。command line 的结构。输入输出格式请见命」· C++ 代码 · 共 95 行

CPP
95
字号
/*----------------------------------------------------------------------------*/
/* tselect.c - Tournament selection 										  */
/* Contributed by Hillol Kargupta, Dept of Engr. Mechanics, U. of Alabama	  */
/*----------------------------------------------------------------------------*/

#include "tselect.h"

#include <stdlib.h>
#include "external.h"	
#include "memory.h"
#include "random.h"

static int	*tourneylist, tourneypos, tourneysize;  
/* tournament list, position in list */

void t_select_memory()
{
	unsigned nbytes;
	//char	   *malloc();
	//int j;
	
	nbytes = popsize*sizeof(int);
	if((tourneylist = (int *) malloc(nbytes)) == NULL)
		//nomemory(stderr,"tourneylist");
		nomemory("tourneylist");
	
	if(numfiles == 0)
		fprintf(outfp," Enter tournament size for selection --> ");
	fscanf(infp,"%d", &tourneysize);
	if(tourneysize > popsize)
	{
		fprintf(outfp,"FATAL: Tournament size (%d) > popsize (%d)\n",
			tourneysize,popsize);
		exit(-1);
	}
	
}

void t_select_free()
{
	free(tourneylist);
}




void t_preselect()
{
	t_reset();
	tourneypos = 0;
}


int t_select()
{
	int pick, winner, i;
	
	/* If remaining members not enough for a tournament, then reset list */
	if((popsize - tourneypos) < tourneysize)
	{
		t_reset();
		tourneypos = 0;
	}
	
	/* Select tourneysize structures at random and conduct a tournament */
	winner=tourneylist[tourneypos];
	for(i=1; i<tourneysize; i++)
	{
		pick=tourneylist[i+tourneypos];
		if(oldpop[pick].fitness > oldpop[winner].fitness) winner=pick;
	}
	
	/* Update tourneypos */
	tourneypos += tourneysize; 
	return(winner);
}


void t_reset()	 
/* Shuffles the tourneylist at random */
{
	int i, rand1, rand2, temp;
	
	for(i=0; i<popsize; i++) tourneylist[i] = i;
	
	for(i=0; i < popsize; i++)
	{
		rand1=rnd(i,popsize-1);
		rand2=rnd(i,popsize-1);
		temp = tourneylist[rand1];
		tourneylist[rand1]=tourneylist[rand2];
		tourneylist[rand2]=temp;
	}
}

⌨️ 快捷键说明

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