/*********************************************************************** SIMPLE GENETIC ALGORITHM ZERO-ONE KNAPSACK WHO: Robert Walsh WHAT: CSCI 475 WHEN: Jan 10, 1995 This is a simple genetic algorithm which attempts to solve the zero/one knapsack problem. ************************************************************************/ #include #define NObj 50 #define NPop 50 #define NCap 500 #define NMut 1 #define NCrs 50 short int Item[200], G; struct Objects { char Bit[NObj]; int Fitness; }; struct Objects Chrome[NPop][2]; void GetData() /********************************************************************** WHAT: Reads the data from a file and stores it in the array, Item[]. The data in this array is assumed to be formated as follows: Item[0] = Value, Item[1] = Weight Item[2] = Value, Item[3] = Weight | | Item[198] = Value, Item[199] = Weight ***********************************************************************/ { FILE *In, *fopen(); if(In = fopen("KSData", "r")) { fread(Item, 2, 200, In); fclose(In); } } void InitPop() /********************************************************************** WHAT: Randomly creates an initial population of size NPop by assigning a binary value to the array Chrome[][].Bit[j] which acts as the chromosome. ***********************************************************************/ { int t, i; for(t=0; tHigh) High=Value; } else Chrome[t][G].Fitness=0; } return High; } void Crossover(M, F, T) register int M, F, T; /********************************************************************** WHAT: Creates two new offsprings from parents. The offsprings are born in the alternate population buffer. Therefore, this routine write to every data bit in the alternate buffer. However, to prevent every generation from simply be a clone of the last, there is a NCrs% chance that the bits of the parents wil be swapped at a random point. IN: int M : One of the parents int F : The other parent int T : The offsprings number in the new generation ***********************************************************************/ { register int i, z; z=RangeRand(NObj); for(i=0; i=NPop) M=RangeRand(NPop); X=RangeRand(TotFit); i=0; while((Wheel[i]=NPop) F=RangeRand(NPop); Crossover(M, F, t); } } void Mutation() /********************************************************************** WHAT: This routine mutates chromosomes by changing 0 to 1 and vice versa. There is a NMut percent chance that any 0 or 1 will be changed. ***********************************************************************/ { register int t, i; for(t=0; tOptTot) { AtGen=Gen; OptTot=OptGen; } Select(); Mutation(); G=1-G; } printf("Optimum Value: %d\nFound at Generation: %d\n", OptTot, AtGen); scanf("%d",t); }