Skip to content

Commit

Permalink
NearbyHouse support
Browse files Browse the repository at this point in the history
  • Loading branch information
murfffi committed Nov 23, 2020
1 parent 686e038 commit eb5362a
Show file tree
Hide file tree
Showing 8 changed files with 214 additions and 12 deletions.
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,17 @@ With Maven, you can add it as a dependency like this:
...
```

Maven understands "RELEASE" as latest non-SNAPSHOT version. It is recommended to
replace that with a specific version to prevent getting versions with breaking changes
unintentionally.
Maven understands "RELEASE" as latest non-SNAPSHOT version. It is recommended to replace that with a specific version to
prevent getting versions with breaking changes unintentionally.

## Customizing

The puzzles generated by the library can customized by defining Attributes and Facts. Attributes are the traits
of the people in the puzzle like name or favourite pet, while Facts are clues that the players get to solve the puzzle.
You can select from the predefined implementations or implement yourself the Java interfaces with the same names.

`customQuestionPuzzle()` in `Demo.java` demonstrated how to select specific types of Attributes and Facts when
generating puzzles.

## Install library from source

Expand Down
4 changes: 3 additions & 1 deletion src/main/java/zebra4j/AbstractPuzzleGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@
import zebra4j.fact.BothTrue;
import zebra4j.fact.Different;
import zebra4j.fact.Fact;
import zebra4j.fact.NearbyHouse;

@AllArgsConstructor
public abstract class AbstractPuzzleGenerator<P> {

public static final Set<Fact.Type> DEFAULT_FACT_TYPES = SetUtils.unmodifiableSet(BothTrue.TYPE, Different.TYPE);
public static final Set<Fact.Type> DEFAULT_FACT_TYPES = SetUtils.unmodifiableSet(BothTrue.TYPE, Different.TYPE,
NearbyHouse.TYPE);

private final Random rnd;
protected final PuzzleSolution solution;
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/zebra4j/PuzzleSolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ private PuzzleSolution fromChocoSolution(Solution choco, ZebraModel model) {
}
for (IntVar var : retrieveVars(choco)) {
int person = choco.getIntVal(var);
Attribute attribute = model.toAttribute(var.getName());
allAttributes[person].add(attribute);
model.toOptionalAttribute(var.getName()).ifPresent(attr -> allAttributes[person].add(attr));
}
PuzzleSolutionBuilder builder = new PuzzleSolutionBuilder(false);
Stream.of(allAttributes).forEach(list -> builder.add(new SolutionPerson(list)));
Expand Down
11 changes: 9 additions & 2 deletions src/main/java/zebra4j/ZebraModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -55,10 +56,16 @@ public String varName(Attribute attr) {
}

public Attribute toAttribute(String name) {
return toOptionalAttribute(name).get();
}

public Optional<Attribute> toOptionalAttribute(String name) {
Matcher m = VAR_REGEX.matcher(name);
m.matches();
if (!m.matches()) {
return Optional.empty();
}
int attributeId = Integer.parseInt(m.group(2));
AttributeType attrType = typeMap.get(m.group(1));
return attrType.fromUniqueInt(attributeId);
return Optional.of(attrType.fromUniqueInt(attributeId));
}
}
148 changes: 148 additions & 0 deletions src/main/java/zebra4j/fact/NearbyHouse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*-
* #%L
* zebra4j
* %%
* Copyright (C) 2020 Marin Nozhchev
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package zebra4j.fact;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.variables.IntVar;

import lombok.Value;
import zebra4j.AllDifferentType;
import zebra4j.AtHouse;
import zebra4j.Attribute;
import zebra4j.PersonName;
import zebra4j.PuzzleSolution;
import zebra4j.SolutionPerson;
import zebra4j.ZebraModel;

/**
* Facts/clues about people with certain attributes living in adjacent or nearby
* houses.
*
* <p>
* equals/hashCode treats NearbyHouse(PersonA, PersonB) as different from
* NearbyHouse(B, A) even though they are semantically the same.
*/
@Value
public class NearbyHouse implements Fact {

private static final int MAX_DISTANCE = 2;

public static final Type TYPE = new Type() {

@Override
public List<Fact> generate(PuzzleSolution solution) {
List<Fact> result = new ArrayList<>();
List<SolutionPerson> people = new ArrayList<>(solution.getPeople());
for (int i = 0; i < people.size(); ++i) {
SolutionPerson leftPerson = people.get(i);
Attribute leftHouse = leftPerson.findAttribute(AtHouse.TYPE);
if (leftHouse == null) {
continue;
}
int leftPos = leftHouse.asUniqueInt();
for (int j = i + 1; j < people.size(); ++j) {
SolutionPerson rightPerson = people.get(j);
Attribute rightHouse = rightPerson.findAttribute(AtHouse.TYPE);
if (rightHouse == null) {
continue;
}
int rightPos = rightHouse.asUniqueInt();

int distance = Math.abs(leftPos - rightPos);

if (distance > MAX_DISTANCE) {
continue;
}

for (Attribute leftAttr : leftPerson.asList()) {
Attribute rightAttr = rightPerson.findAttribute(leftAttr.type());
if (rightAttr != null && leftAttr.type() instanceof AllDifferentType) {
result.add(new NearbyHouse(distance, leftAttr, rightAttr));
}
}
}
}
return result;
}
};

private final int distance;
private final Attribute left, right;

@Override
public void postTo(ZebraModel model) {
List<Constraint> constraints = new ArrayList<>();

int numHouses = countHouses(model);
IntVar leftAttrVar = model.getVariableFor(left);
IntVar rightAttrVar = model.getVariableFor(right);
for (int leftPos = 1; leftPos <= numHouses - distance; ++leftPos) {
IntVar leftHouseVar = model.getVariableFor(new AtHouse(leftPos));
int rightPos = leftPos + distance;
IntVar rightHouseVar = model.getVariableFor(new AtHouse(rightPos));
Constraint consLeft = model.getChocoModel().arithm(leftHouseVar, "=", leftAttrVar);
Constraint consRight = model.getChocoModel().arithm(rightHouseVar, "=", rightAttrVar);
constraints.add(model.getChocoModel().and(consLeft, consRight));

consLeft = model.getChocoModel().arithm(leftHouseVar, "=", rightAttrVar);
consRight = model.getChocoModel().arithm(rightHouseVar, "=", leftAttrVar);
constraints.add(model.getChocoModel().and(consLeft, consRight));
}

model.getChocoModel().or(constraints.toArray(new Constraint[0])).post();
}

private static int countHouses(ZebraModel model) {
int result = 0;
while (model.getVariableFor(new AtHouse(result + 1)) != null) {
++result;
}
return result;
}

@Override
public boolean appliesTo(PuzzleSolution solution) {
Optional<Integer> leftHousePos = getHousePosition(solution, left);
Optional<Integer> rightHousePos = getHousePosition(solution, right);
return leftHousePos.isPresent() && rightHousePos.isPresent()
&& Math.abs(leftHousePos.get() - rightHousePos.get()) == distance;
}

@Override
public String toString() {
String dist = distance == 1 ? "в съседна къща на" : String.format("през %s къща от", distance - 1);
if (left instanceof PersonName) {
return String.format("%s живее %s %s", left.description(), dist, right.description());
}
return String.format("Този който е %s живее %s този който е %s.", left.description(), dist,
right.description());
}

private static Optional<Integer> getHousePosition(PuzzleSolution solution, Attribute attribute) {
return solution.findPerson(attribute).flatMap(person -> Optional.ofNullable(person.findAttribute(AtHouse.TYPE)))
.map(house -> house.asUniqueInt());
}

}
7 changes: 4 additions & 3 deletions src/test/java/zebra4j/fact/BothTrueTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,14 @@ public static void testPostTo(Fact.Type type) {
// must not contain Criminal
PuzzleSolution solution = PuzzleGeneratorTest.sampleSolution();
List<Fact> facts = type.generate(solution);
testPostTo(facts.get(0), solution);
assertTrue(!facts.isEmpty());
facts.stream().forEach(fact -> testPostTo(fact, solution));
}

public static void testPostTo(Fact fact, PuzzleSolution solution) {
assertTrue(fact.appliesTo(solution));
Puzzle puzzle = new Puzzle(solution.getAttributeSets(), Collections.singleton(fact));
new PuzzleSolver(puzzle).solve().stream()
.forEach(anySolution -> assertTrue(anySolution.toString(), fact.appliesTo(anySolution)));
new PuzzleSolver(puzzle).solve().stream().forEach(
anySolution -> assertTrue(fact + " \n " + anySolution.toString(), fact.appliesTo(anySolution)));
}
}
37 changes: 37 additions & 0 deletions src/test/java/zebra4j/fact/NearbyHouseTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*-
* #%L
* zebra4j
* %%
* Copyright (C) 2020 Marin Nozhchev
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package zebra4j.fact;

import org.junit.Test;

public class NearbyHouseTest {

@Test
public void testGenerate() {
BothTrueTest.testGenerate(NearbyHouse.TYPE);
}

@Test
public void testPostTo() {
BothTrueTest.testPostTo(NearbyHouse.TYPE);
}

}
2 changes: 1 addition & 1 deletion src/test/resources/logback-test.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<logger name="zebra4j" level="debug" />
<logger name="zebra4j" level="info" />
</configuration>

0 comments on commit eb5362a

Please sign in to comment.