Last active
September 11, 2021 19:20
-
-
Save jinahya/c278ccad5df4b2e754667f29751a9e3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
/** | |
* A class for generateing <i>counterstring</i>s. | |
* | |
* @author Jin Kwon <onacit_at_gmail.com> | |
* @see <a href="http://www.satisfice.com/blog/archives/22">Counterstrings: Self-Describing Test Data</a> | |
*/ | |
public class CounterString { | |
/** | |
* Generates a <i>counterstring</i> of specified length by appending characters to given appendable. | |
* | |
* @param appendable the appendable into which generated characters are appended. | |
* @param length the length of the <i>counterstring</i>. | |
* @param radix a radix for numeric characters. | |
* @param <T> appendable type parameter. | |
* @return given appendable. | |
* @throws IOException if an I/O error occurs. | |
* @see Integer#toString(int, int) | |
*/ | |
public static <T extends Appendable> T generate(final T appendable, final int length, final int radix) | |
throws IOException { | |
if (appendable == null) { | |
throw new NullPointerException("appendable is null"); | |
} | |
if (length < 0) { | |
throw new IllegalArgumentException("length(" + length + ") < 0"); | |
} | |
int l = 0; | |
for (int c = 0; l < length; c++) { | |
final String s = Integer.toString(c, radix); | |
if (l + s.length() == c - 1) { | |
if (l + s.length() + 1 > length) { | |
appendable.append(s, 0, length - l); | |
break; | |
} | |
appendable.append(s); | |
l += s.length(); | |
appendable.append('*'); | |
l++; | |
} | |
} | |
return appendable; | |
} | |
/** | |
* The main class of this program whose first argument is the {@code length} and the second optional argument is a | |
* {@code radix}. | |
* | |
* @param args command line argument. | |
* @throws IOException if an I/O error occurs. | |
*/ | |
public static void main(final String... args) throws IOException { | |
final int length = Integer.parseInt(args[0]); | |
int radix = 10; | |
try { | |
radix = Integer.parseInt(args[1]); | |
} catch (final ArrayIndexOutOfBoundsException aioobe) { | |
} | |
final StringBuilder appendable = generate(new StringBuilder(length), length, radix); | |
assert appendable.length() == length; | |
System.out.println(appendable.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment