Skip to content

Commit

Permalink
Create 3-SAT.c
Browse files Browse the repository at this point in the history
3-SAT

Signed-off-by: Josef Edwards <joed6834@colorado.edu>
  • Loading branch information
bearycool11 authored Nov 13, 2024
1 parent 744f42c commit 166d377
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 3-SAT.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Function to generate a random 3-SAT instance
void generate_3sat_instance(int num_variables, int num_clauses, const char* filename) {
FILE *file = fopen(filename, "w");
if (!file) {
perror("Failed to open file for writing");
return;
}

// Write the header for the 3-SAT CNF instance
fprintf(file, "p cnf %d %d\n", num_variables, num_clauses);

// Randomly generate clauses
srand(time(0)); // Seed the random number generator

for (int i = 0; i < num_clauses; ++i) {
// Each clause consists of 3 literals, choose them randomly
for (int j = 0; j < 3; ++j) {
int var = rand() % num_variables + 1; // Variable between 1 and num_variables
if (rand() % 2 == 0) {
var = -var; // Randomly negate the variable
}
fprintf(file, "%d ", var);
}
fprintf(file, "0\n"); // End of clause
}

fclose(file);
printf("Generated random 3-SAT instance: %s\n", filename);
}

0 comments on commit 166d377

Please sign in to comment.