#include #include #include #include #include #include #include #include "segmenttree.h" int main(int argc, char *argv[]) { char *file = "cards"; bool verbose = false; bool noninteractive = false; /* Proccess args */ for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-v") == 0) verbose = true; else if (strcmp(argv[i], "-n") == 0) noninteractive = true; else file = argv[i]; } /* Seed the RNG */ srand(time(0)); /* Connect to db */ sqlite3 *db; sqlite3_open(file, &db); /* Get number of cards */ sqlite3_stmt *stmt; sqlite3_prepare_v3(db, "SELECT COUNT(*) FROM cards", -1, 0, &stmt, NULL); sqlite3_step(stmt); int N = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); /* Get card weights */ sqlite3_prepare_v3(db, "SELECT weight FROM cards", -1, 0, &stmt, NULL); seg = (int*)malloc(4 * N * sizeof(int)); build(stmt, 0, N - 1, 1); sqlite3_finalize(stmt); if (verbose) { for (int i = 0; i < 4 * N; i++) { printf("%d ", seg[i]); } printf("\n"); } if (!noninteractive) { /* Disable input buffering */ assert(system("stty -F /dev/tty cbreak min 1") == 0); assert(system("stty -F /dev/tty -echo") == 0); } while (true) { /* Make sure sum of weights is positive */ assert(seg[1] > 0); int x = (long long)rand() * rand() % seg[1]; int res[2]; query(res, x, 0, N-1, 1); int w = res[0], i = res[1]; if (verbose) { printf("%d %d %d %d\n", seg[1], x, w, i); } /* Get card contents from database */ sqlite3_prepare_v3(db, "SELECT key, val FROM cards WHERE idx=?", -1, 0, &stmt, NULL); sqlite3_bind_int(stmt, 1, i); sqlite3_step(stmt); printf("> %s\n", sqlite3_column_text(stmt, 0)); if (noninteractive) { fflush(stdout); } /* Wait for confirmation */ getchar(); if (noninteractive) { /* Skip newline */ getchar(); } printf("%s\n", sqlite3_column_text(stmt, 1)); if (noninteractive) { fflush(stdout); } sqlite3_finalize(stmt); /* Read user input */ char b = getchar(); if (noninteractive) { /* Skip newline */ getchar(); } if (b == 'y') w >>= 1; else if (b == 'n') w <<= 3; else break; /* Update segment tree and database */ update(i, w, 0, N - 1, 1); sqlite3_prepare_v3(db, "UPDATE cards SET weight=? WHERE idx=?", -1, 0, &stmt, NULL); sqlite3_bind_int(stmt, 1, w); sqlite3_bind_int(stmt, 2, i); sqlite3_step(stmt); sqlite3_finalize(stmt); } /* Cleanup */ sqlite3_close(db); }