/* puts each element into bit vector to check digits */ void check_setof9(int col, int row, UArray2_T a, void *elem, void *bit) { int digit = *(int *)elem; Bit_T b = bit; if (digit < 1 || digit > 9) { Bit_free(&b); UArray2_free(&a); exit(1); /* digit is already in vector */ } if (Bit_get(bit, digit) == 1) { Bit_free(&b); UArray2_free(&a); exit(1); /* if digit isn't in vector, change bit to 1 */ } else { Bit_put(bit, digit, 1); /*all nine digits are present, reset bit vector*/ } if (Bit_count(bit) == 9) { Bit_clear(bit, 1, 9); } (void) col; (void) row; (void) a; }
/*-----------------------------------------------------------------------------* | Bit2_free | Purpose: frees the memory allocated for the given Bit2 | Arguments: a pointer to a pointer to a 2D bit array | Returns: - | Fail cases: | - the pointer to the pointer to the 2D bit array is null | - the pointer to the 2D bit array is null *-----------------------------------------------------------------------------*/ void Bit2_free (Bit2_T *bit2) { assert((bit2 != NULL) && (*bit2 != NULL)); Bit2_T temp = *bit2; Bit_T bit_array = temp->bitmap; Bit_free(&bit_array); free(temp); }
/* checks that each row, column, and 3x3 box has digits 1 through 9*/ void correct_sudoku(UArray2_T uarray2) { Bit_T bit = Bit_new(10); UArray2_map_row_major(uarray2, check_setof9, bit);; UArray2_map_col_major(uarray2, check_setof9, bit); UArray2_map_3x3_box(uarray2, check_setof9, bit); Bit_free(&bit); }
int main(int argc, char *argv[]) { int k, n, i; Bit_T bits; if (argc != 3) usage(); k = atoi(argv[1]); n = atoi(argv[2]); srand(time(0)); bits = Bit_new(n); for (i = 0; i < k; i++) { int j; do { j = rand()%n; } while (Bit_get(bits, j)); Bit_put(bits, j, 1); printf("%d\n", j); } Bit_free(&bits); return 0; }
/* * Deallocates and clears *bit2. */ extern void Bit2_free(T *bit2) { assert(bit2 && *bit2); Bit_free(&(*bit2)->bit_vector); FREE(*bit2); }