misc.c

来自「一遗传算法的例子源程序」· C语言 代码 · 共 56 行

C
56
字号
#include <stdlib.h>
#include "lithos.h"

int score;

void *alloc(int bytes)
{
	void *p = malloc(bytes);
	if (!p)
	{
		printf("Out of memory\n");
		exit(EXIT_FAILURE);
	}
	return p;
}

void writeLog()
{
	FILE *f;
	int i;
	char species[INSTRUCTIONS][INSTRUCTIONS];
	int diversity = 0;

	if (logFrequency == 0)
		return;
	if (generations % logFrequency)
		return;

	memset(species, 0, sizeof species);
	for (i = 0; i < population; i++)
	{
		Program *p = &programs[i];
		int first;
		int last;
		if (!p->size)
			continue;
		first = p->code[0];
		last = p->code[p->size - 1];
		if (!species[first][last])
		{
			species[first][last] = 1;
			diversity++;
		}
	}

	f = fopen("log", "a");
	if (!f)
	{
		printf("Unable to open log file\n");
		exit(EXIT_FAILURE);
	}
	fprintf(f, "%d\t%d\t%d\t%d\n",
		generations, programs[0].size, diversity, score);
	fclose(f);
}

⌨️ 快捷键说明

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