Commit 946f405c authored by Renk, Jonas's avatar Renk, Jonas
Browse files

Use context free grammer to generate a random tree string

parent 005f9ccc
......@@ -182,7 +182,7 @@ public class MyTreeTest {
assertTrue((Boolean) isIsomorphic.invoke(instance1, instance2), "Trees are isomorphic");
assertTrue((Boolean) isIsomorphic.invoke(instance2, instance1), "Trees are isomorphic");
String nonIsomorphicTreeString = RandomTreeProvider.randomTreeString(3, 2);
String nonIsomorphicTreeString = RandomTreeProvider.randomTreeString(2);
Object nonIsomorphicInstance = constructor.newInstance(new StringReader(nonIsomorphicTreeString), false);
assertFalse((Boolean) isIsomorphic.invoke(instance1, nonIsomorphicInstance), "Trees are not isomorphic");
......
......@@ -10,36 +10,21 @@ import java.util.stream.Stream;
public class RandomTreeProvider implements ArgumentsProvider {
private static final int MAX_STREAM_SIZE = 5;
private static final int MAX_TREE_DEPTH = 3, MAX_NODES = 10;
private static final int MAX_TREE_DEPTH = 5;
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
return Stream.generate(() -> Arguments.of(randomTreeString(MAX_NODES, MAX_TREE_DEPTH))).limit(MAX_STREAM_SIZE);
return Stream.generate(() -> Arguments.of(randomTreeString(MAX_TREE_DEPTH))).limit(MAX_STREAM_SIZE);
}
public static String randomTreeString(int maxNodes, int maxTreeDepth) {
int unclosedParentheses = 0, numberOfNodes = 0;
StringBuilder builder = new StringBuilder();
while (numberOfNodes < maxNodes)
if (Utils.RANDOM.nextBoolean() && unclosedParentheses < maxTreeDepth) {
builder.append('(');
unclosedParentheses++;
numberOfNodes++;
} else {
if (unclosedParentheses > 0) {
builder.append(')');
unclosedParentheses--;
} else {
builder.append('(');
unclosedParentheses++;
numberOfNodes++;
}
}
for (; unclosedParentheses > 0; unclosedParentheses--)
builder.append(')');
return builder.toString();
public static String randomTreeString(int maxTreeDepth) {
var x = Utils.RANDOM.nextDouble();
if (x < 0.2 || maxTreeDepth == 0) {
return "";
}
if (x < 0.6) {
return "(" + randomTreeString(maxTreeDepth-1) + ")";
}
return randomTreeString(maxTreeDepth-1) + randomTreeString(maxTreeDepth-1);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment