#include #include #include #include #define DICEFACES 6 #if ! defined(__cplusplus) typedef unsigned char bool; #define false 0 #define true 1 #endif typedef struct { long price; long next; } cell; static long minimum = 0; static long maximum = 0; static long increment = 0; static long iterations = 0; static long cell_count = 0; cell* board = NULL; static long initial_investment = 0; static long average_balance = 0; static long reached_goals = 0; static long game_balance = 0; static bool game_reached_goal = false; void reset_file_variables() { cell_count = 0; free(board); board = NULL; initial_investment = 0; average_balance = 0; reached_goals = 0; game_balance = 0; game_reached_goal = false; } bool process_params(int argc, char* argv[]) { if ( argc < 6 ) return false; minimum = atol(argv[1]); maximum = atol(argv[2]); increment = atol(argv[3]); iterations = atol(argv[4]); return true; } int print_usage() { fprintf(stderr, "%s\n", "usage: escser min max increment iterations file1 [file2 ... fileN]"); return 1; } bool count_lines(FILE* file) { for ( int ch = 0; (ch = fgetc(file) ) != EOF; ) if ( ch == '\n' ) ++cell_count; return true; } bool load_file(FILE* file) { board = (cell*) malloc( cell_count * sizeof(cell) ); assert(board); for ( long i = 0; i < cell_count; ++i ) { fscanf(file, "%li", & board[i].price); fscanf(file, "%li", & board[i].next); } return true; } bool simulate_game() { game_reached_goal = false; game_balance = initial_investment; long position = -1; while ( game_balance >= 0 ) { position += rand() % DICEFACES + 1; if ( position >= cell_count ) position = cell_count - 1; game_balance += board[position].price; if ( position == cell_count - 1 ) return game_reached_goal = true; if ( board[position].next ) position = board[position].next - 1; } return false; } void simulate_games() { reached_goals = 0; long total_balances = 0; for ( long i = 0; i < iterations; ++i ) { simulate_game(); total_balances += (game_balance - initial_investment); reached_goals += game_reached_goal; } average_balance = (long)(total_balances / (double)iterations); } void simulate_investments() { printf("%18s %18s %18s\n", "InitialInvestment", "AverageBalance", "ReachedGoals"); for ( initial_investment = minimum; initial_investment <= maximum; initial_investment += increment) { simulate_games(); printf("%18li %18li %18li\n", initial_investment, average_balance, reached_goals); } } bool process_filename(const char* filename) { printf("\n%s:\n", filename); FILE* file = fopen(filename, "r"); if ( ! file ) return false; reset_file_variables(); count_lines(file); rewind(file); if ( load_file(file) ) simulate_investments(); free(board); board = NULL; fclose(file); return true; } int main(int argc, char* argv[]) { if ( ! process_params(argc, argv) ) return print_usage(); srand( time(NULL) ); for ( int i = 5; i < argc; ++i ) process_filename(argv[i]); return 0; }