/* -*- c -*- */
/* shannon oracle. */

/*
 * Author: Nikita Danilov <NikitaDanilov@yahoo.COM>
 * Keywords: shannon, oracle, fortune teller.
 *
 * Copyright 2002 by Nikita Danilov <NikitaDanilov@yahoo.COM>
 *
 * This file is part of shannon oracle.
 *
 * Shannon oracle is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; see the file COPYING.  If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define DEPTH (5)

typedef enum { EVEN, ODD } event_t;
typedef double history_t[2][2][2][2][2][2];
typedef event_t memory_t[DEPTH];

double *
drill(history_t history, memory_t memory)
{
	return history[memory[0]][memory[1]][memory[2]][memory[3]][memory[4]];
}

void
store(memory_t memory, event_t event)
{
	int i;

	for (i = 1 ; i < DEPTH ; ++ i) {
		memory[i - 1] = memory[i];
	}
	memory[DEPTH - 1] = event;
}

event_t
get_event()
{
	int datum;

	switch(scanf("%i", &datum)) {
	case 1:
		return datum ? ODD : EVEN;
	case 0:
		fprintf(stderr, "Conversion failed.\n");
	case EOF:
	default:
		exit(1);
	}
	return 0;
}

event_t
guess(history_t history, memory_t memory)
{
	double *future;

	future = drill(history, memory);
	if (future[ODD] == future[EVEN]) {
		return (event_t) (2.0 * rand() / RAND_MAX);
	} else if (future[ODD] > future[EVEN])
		return ODD;
	else
		return EVEN;
}

void
init_history(history_t history, int elms)
{
	int i;
	double *raw;

	raw = (double *)history;
	for (i = 0 ; i < elms ; ++ i)
		raw[i] = 1.0;
}

void usage()
{
	fprintf(stderr, "\nshannon [-h]\n");
	exit(0);
}

void
shannon(int human)
{
	history_t history;
	memory_t memory;
	int hit;
	int total;

	init_history(history, sizeof (history) / sizeof (double));
	memset(memory, 0, sizeof memory);

	hit = 0;
	for (total = 1 ;; ++ total) {
		event_t prediction;
		event_t reality;

		prediction = guess(history, memory);
		printf("%s%i\n", human ? "My guess: " : "", prediction);
		reality = get_event();
		drill(history, memory)[reality] *= 1.1;
		store(memory, reality);
		if (reality == prediction)
			++ hit;
		if (human)
			printf("hits: %i/%i (%f)\n", 
			       hit, total, ((double)hit)/total);
	}
}

int
main(int argc, char **argv)
{
	int ch;
	int human;

	human = 0;
	while ((ch = getopt(argc, argv, "h")) != -1) {
		switch (ch) {
		case 'h':
			++ human;
			break;
		default:
			usage();
		}
	}

	shannon(human);
	return 0;
}
