You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.0 KiB

6 years ago
  1. #!/usr/bin/env python3
  2. import numpy as np
  3. import random
  4. import kSAT
  5. def generateRandomKSAT(numberOfClauses,
  6. numberOfVariables,
  7. numberOfVariablesPerClause):
  8. instance = kSAT.kSAT()
  9. clauses = [[] for i in range(numberOfClauses)]
  10. #make sure every variable is bound to at least one clause
  11. for varIndex in range(numberOfVariables):
  12. clauseIndex = random.choice(range(numberOfClauses))
  13. while (len(clauses[clauseIndex]) >= numberOfVariablesPerClause or
  14. varIndex + 1 in clauses[clauseIndex]):
  15. clauseIndex = random.choice(range(numberOfClauses))
  16. clauses[clauseIndex].append(varIndex + 1)
  17. #fill in the missing bindings
  18. for clause in clauses:
  19. tmpClause = []
  20. clauseIsUnique = False
  21. while not clauseIsUnique:
  22. tmpClause = clause.copy()
  23. numRemainingBindings = numberOfVariablesPerClause - len(tmpClause)
  24. variablesNotYetInClause = __getVariablesNotYetInClause(tmpClause,
  25. numberOfVariables)
  26. remainingBindings = random.sample(variablesNotYetInClause,
  27. numRemainingBindings)
  28. tmpClause += remainingBindings
  29. for i in range(len(tmpClause)):
  30. tmpClause[i] *= random.choice([-1, 1])
  31. if tmpClause not in clauses:
  32. clauseIsUnique = True
  33. instance.addClause(tmpClause)
  34. return instance
  35. def __getVariablesNotYetInClause(clause, numberOfTotalVars):
  36. missingVariables = []
  37. prevVar = 1;
  38. for currVar in clause:
  39. missingVariables += list(range(prevVar, currVar))
  40. prevVar = currVar + 1
  41. missingVariables += list(range(prevVar, numberOfTotalVars + 1))
  42. return missingVariables