/* * Copyright (c) Camden Dixie O'Brien * SPDX-License-Identifier: AGPL-3.0-only */ #include "puzz.h" #include #include #include #include #include #include #include #define NRUNS 1000 enum { UNKNOWN = 0xfe, KILLER = 0xfd }; static void setadj(puzz_t field, int x, int y, uint8_t from, uint8_t to) { for (int yp = y - 1; yp < y + 2; ++yp) { for (int xp = x - 1; xp < x + 2; ++xp) { if (xp < 0 || xp >= WIDTH || yp < 0 || yp >= HEIGHT || (xp == x && yp == y)) continue; field[xp][yp] = field[xp][yp] == from ? to : field[xp][yp]; } } } static void getadj(puzz_t field, int *x, int *y, uint8_t val) { for (int yp = *y - 1; yp < *y + 2; ++yp) { for (int xp = *x - 1; xp < *x + 2; ++xp) { if (xp < 0 || xp >= WIDTH || yp < 0 || yp >= HEIGHT || (xp == *x && yp == *y)) continue; if (field[xp][yp] == val) { *x = xp; *y = yp; return; } } } assert(false); } static status_t solve(void) { puzz_t field; memset(field, UNKNOWN, sizeof(field)); status_t status; int total_mines = 0, total_unknowns = WIDTH * HEIGHT; do { int x = rand() % WIDTH; int y = rand() % HEIGHT; probe: if (field[x][y] != MINE && (status = probe(x, y, field)) == DEAD) { field[x][y] = KILLER; break; } update: total_mines = total_unknowns = 0; for (y = 0; y < HEIGHT; ++y) { for (x = 0; x < WIDTH; ++x) { total_mines += field[x][y] == MINE ? 1 : 0; total_unknowns += field[x][y] == UNKNOWN ? 1 : 0; } } for (y = 0; y < HEIGHT; ++y) { for (x = 0; x < WIDTH; ++x) { if (field[x][y] == UNKNOWN || field[x][y] == MINE) continue; const int mines = countadj(field, x, y, MINE); const int unknowns = countadj(field, x, y, UNKNOWN); if (unknowns == 0) continue; if (mines + unknowns == field[x][y]) { setadj(field, x, y, UNKNOWN, MINE); goto update; } if (mines == field[x][y]) { getadj(field, &x, &y, UNKNOWN); goto probe; } } } } while (total_mines < NMINES); return status; } int main(void) { struct timeval tv; if (gettimeofday(&tv, NULL) != 0) { perror("Failed to get time"); exit(1); } srand(tv.tv_usec); int nsolved = 0; for (int i = 0; i < NRUNS; ++i) { gen(); nsolved += solve() == OK ? 1 : 0; } const double prop = (double)nsolved / NRUNS; printf("Solved %d/%d (%0.1f%%)\n", nsolved, NRUNS, 100 * prop); return 0; }