我想在java中创建一个生成器类来生成下一个最小的唯一ascii字符串,其中结果字符串必须以a-Z开头,并且每个后续字母可以是a-Z或0-9。
这些字符串用于缩小javascript文件中的变量。
有关工具的任何建议可以执行此操作或一些关于如何实施的粗略代码吗?
答案 0 :(得分:1)
如果您需要使用其他选择的字符,可以使用
public static void main(String... ignored) {
String prev = "";
for (int i = 0; i < 40000000; i++) {
String s = asId(i);
if (s.length() > prev.length())
System.out.print(prev + "\n" + s + " to ");
prev = s;
}
}
static char[] CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static String asId(long number) {
StringBuilder sb = new StringBuilder();
long div = number < 52 ? 1 : 52;
while (div <= number / 62) div *= 62;
while (div > 0) {
sb.append(CHARS[((int) (number / div % 62))]);
div /= 62;
}
return sb.toString();
}
打印
0 to Z
10 to ZZ
100 to ZZZ
1000 to
您可以在Java中使用以下内容。
public static String asId(long number) {
return (char) ('a' + number % 26)
+ (number >= 26 ? Long.toString(number / 26, 36) : "");
}
如果您担心负数可以使用。
public static String asId(long number) {
long lowBit = number & 1;
long highBits = number >>> 1;
return (char) ('a' + highBits % 13 + lowBit)
+ (number >= 26 ? Long.toString(highBits / 13, 36) : "");
}
答案 1 :(得分:0)
以下是一些想法(未经过全面测试!!!)
import java.lang.*;
import java.util.*;
public class Test
{
static class VariablesIterator implements Iterator<String>
{
private List<Character> characters = new ArrayList<Character>();
private List<Integer> indices = new ArrayList<Integer>();
public VariablesIterator(String start)
{
char[] cs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
for (char c : cs)
{
characters.add(c);
}
for (int i = 0; i < start.length(); ++i)
{
indices.add(characters.indexOf(start.charAt(i)));
}
}
public boolean hasNext()
{
return true;
}
public String next()
{
String current = "";
for (int i = 0; i < indices.size(); ++i)
{
current += characters.get(indices.get(i));
}
Integer last = indices.get(indices.size() - 1);
if (indices.size() != 1 && last != 2*26 + 10 - 1 || indices.size() == 1 && last != 2*26 - 1)
{
indices.set(indices.size() - 1, last + 1);
}
else
{
indices.add(0);
}
return current;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
static class Variables implements Iterable<String>
{
public Iterator<String> iterator()
{
return new VariablesIterator("a");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
for (String variable : new Variables())
{
System.out.println(variable);
in.nextLine();
}
}
}