001 package aima.search.csp; 002 003 import java.util.ArrayList; 004 import java.util.List; 005 006 import aima.util.Util; 007 008 /** 009 * @author Ravi Mohan 010 * 011 */ 012 013 public class CSP { 014 015 // private Assignment assignment; 016 017 private Domain domains; 018 019 private Constraint constraints; 020 021 private List<String> variables; 022 023 public CSP(List<String> variables, Constraint constraints) { 024 this.variables = variables; 025 // this.assignment = new Assignment(variables); 026 this.domains = new Domain(variables); 027 this.constraints = constraints; 028 } 029 030 public CSP(List<String> variables, Constraint constraints, Domain domains) { 031 this.variables = variables; 032 // this.assignment = new Assignment(variables); 033 this.domains = domains; 034 this.constraints = constraints; 035 } 036 037 public List defaultOrderDomainOf(String variable) { 038 return domains.getDomainOf(variable); 039 } 040 041 public Assignment backTrackingSearch() { 042 return recursiveBackTrackingSearch(new Assignment(variables)); 043 } 044 045 private Assignment recursiveBackTrackingSearch(Assignment anAssignment) { 046 if (anAssignment.isComplete()) { 047 return anAssignment; 048 } 049 String variable = anAssignment.selectFirstUnassignedVariable(); 050 List domainValues = defaultOrderDomainOf(variable); 051 for (int i = 0; i < domainValues.size(); i++) { 052 Object value = domainValues.get(i); 053 054 if (constraints.isSatisfiedWith(anAssignment, variable, value)) { 055 anAssignment.setAssignment(variable, value); 056 Assignment result = recursiveBackTrackingSearch(anAssignment); 057 if (result != null) { 058 return result; 059 } 060 anAssignment.remove(variable); 061 } 062 } 063 return null;// failure 064 } 065 066 public Assignment mcSearch(int maxSteps) { 067 Assignment randomAssignment = generateRandomAssignment(); 068 069 for (int i = 0; i < maxSteps; i++) { 070 071 if (randomAssignment.satisfies(constraints)) { 072 return randomAssignment; 073 } else { 074 String conflictedVariable = Util 075 .selectRandomlyFromList(randomAssignment 076 .getConflictedVariables(constraints)); 077 Object minConflictValue = randomAssignment 078 .getMinimumConflictingValueFor(conflictedVariable, 079 domains.getDomainOf(conflictedVariable), 080 constraints); 081 randomAssignment.setAssignment(conflictedVariable, 082 minConflictValue); 083 } 084 } 085 return null; 086 087 } 088 089 private Assignment generateRandomAssignment() { 090 List<String> vars = new ArrayList<String>(); 091 for (int i = 0; i < variables.size(); i++) { 092 vars.add(variables.get(i)); 093 } 094 Assignment assignment = new Assignment(vars); 095 for (int i = 0; i < variables.size(); i++) { 096 String variable = variables.get(i); 097 Object randomValue = Util.selectRandomlyFromList(domains 098 .getDomainOf(variable)); 099 // System.out.println("in generate Assignment setting"); 100 assignment.setAssignment(variable, randomValue); 101 } 102 return assignment; 103 } 104 105 }