Utility to generate all Applesoft variable names.

This commit is contained in:
Rob Greene 2018-06-10 10:38:08 -05:00
parent edb91e9f96
commit 187c926017
2 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package io.github.applecommander.bastokenizer.api.utils;
import java.util.Optional;
import java.util.function.Supplier;
/** Generate all Applesoft BASIC FP variable names. */
public class VariableNameGenerator implements Supplier<Optional<String>> {
public static final String CHAR1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String CHAR2 = " " + CHAR1 + "0123456789";
public static final int LENGTH = CHAR1.length() * CHAR2.length();
private int n = 0;
@Override
public Optional<String> get() {
try {
if (n >= 0 && n < LENGTH) {
return Optional.of(String.format("%s%s",
CHAR1.charAt(n % CHAR1.length()),
CHAR2.charAt(n / CHAR1.length())
).trim());
}
return Optional.empty();
} finally {
n += 1;
}
}
}

View File

@ -0,0 +1,41 @@
package io.github.applecommander.bastokenizer.api.utils;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class VariableNameGeneratorTest {
@Test
public void testNameSequence() {
Map<Integer,String> expecteds = new HashMap<>();
expecteds.put(0, "A");
expecteds.put(25, "Z");
expecteds.put(26, "AA");
expecteds.put(51, "ZA");
expecteds.put(52, "AB");
expecteds.put(77, "ZB");
// very last name in sequence
expecteds.put(VariableNameGenerator.LENGTH-1, "Z9");
int lastCheck = expecteds.keySet().stream().max(Integer::compare).get();
VariableNameGenerator gen = new VariableNameGenerator();
for (int i = 0; i <= lastCheck; i++) {
String varName = gen.get().orElseThrow(() -> new RuntimeException("Ran out of variable names too early!"));
if (expecteds.containsKey(i)) {
assertEquals(expecteds.get(i), varName);
}
}
}
@Test
public void testSequenceLength() {
VariableNameGenerator gen = new VariableNameGenerator();
int count = 0;
while (gen.get().isPresent()) count++;
assertEquals(VariableNameGenerator.LENGTH, count);
}
}