sorting failed error

monarch_dodra monarchdodra at gmail.com
Mon Jul 30 06:52:58 PDT 2012


On Monday, 30 July 2012 at 13:27:58 UTC, maarten van damme wrote:
> My cmp is :
>
> bool fitnessCompare(chromosome first,chromosome second){
> 		return fitness(first)>fitness(second);
> }
>
> float fitness(chromosome victim){
> 	city[] cities=victim.dna;
> 	
> 	//we need to start from home and return to home
> 	cities=city(0,0) ~ cities;
> 	cities~=city(0,0);
> 	
> 	float travelled=0f;
> 	for(int x=0;x<cities.length-1;x++)
> 		travelled+=distance(cities[x],cities[x+1]);
>
> 	return 1/travelled;
> }
>
>
>
> I've posted my code too on pastebin : 
> http://pastebin.com/7927Hpv2

That seems like a reasonable cmp function. But on the expensive 
side, but that is irrelevant.

I can't access any internet share sites from where I am, so I 
can't dig in much further than that. The assertion you are 
hitting is one that is called after the sort is done, to make 
sure the elements are indeed sorted. In your case, after the 
sort, the elements are not sorted :/

The way I see it, there could be 1 of 2 issues:
*A bad cmp function.
*Data that mutates during sort.

Your looks OK, and I doubt you are mutating. I only see floating 
point gotchas:
If a chromosome travels nothing, then his fitness is 1/0 = NaN.

NaN then compares false with everything, making it un-transitive, 
and potentially breaking your cmp. COuld you try the algo with 
"return 1/(1+travelled)".

That, or because of the non-deterministic nature of floating 
point calculation, I'd create an array containing all the 
fitnesses, and sort using that. This should avoid any 
"re-evaluation error".


More information about the Digitalmars-d-learn mailing list