具有多字符替换的字符串组合(Java的yield return替代重写)

时间:2018-03-19 20:04:37

标签: java combinations

为与车辆登记号码相关的算法创建了另一个Stack Overflow帖子......

  

根据输入的牌照(例如ABC123)和列表   替换值(例如1替换为I)。我需要尽一切可能   组合

@ArturoMenchaca的答案对C#来说是完美的,但是我喜欢Java,但是考虑到这一点,' yield'不可用我真的无法绕过如何转换它。

您如何将此代码翻译为Java?

Dictionary<char, char> dict = new Dictionary<char,char>();
dict['1'] = 'I';
dict['3'] = 'B';
dict['A'] = 'H';
dict['O'] = '0';
dict['0'] = 'O';

var combs = Combinations("ABC123", dict);

你会打电话然后调用这样的方法..

.toPromise().then((res) => {

1 个答案:

答案 0 :(得分:2)

Java没有使用&#34; push&#34;迭代值的功能。逻辑,就像C#yield return那样。

Java仅支持&#34; pull&#34;逻辑,使用EnumerationIteratorSpliterator Stream使用的内容)

如果你有记忆,你当然可以&#34;推&#34;所有组合成ArrayList,然后&#34;拉&#34;那里的价值观。将yield return逻辑转换为list.add()来电很容易,因此我假设您不希望这样。

IEnumerable的Java等效项为Iterable,因此您需要Iterator实现。

下面的代码会这样做。它基于my answer to another question,所以请阅读该答案以获得对整体逻辑的解释,但基本上,您的示例就像在这个锯齿状数组中生成字符组合一样:

{{'A', 'H'}, {'B'}, {'C'}, {'1', 'I'}, {'2'}, {'3', 'B'}}

在下面的代码中,这个锯齿状数组是textChars数组,但它使用char[]而不是String,因为String实际上只是一个读数 - 仅char[]

public static Iterable<String> combinations(String text, String... replacements) {
    Map<Character, String> repl = new HashMap<>();
    for (String r : replacements)
        if (repl.putIfAbsent(r.charAt(0), r) != null)
            throw new IllegalArgumentException("Duplicate replacement: [" + repl.get(r.charAt(0)) + "] vs [" + r + "]");
    String[] textChars = new String[text.length()];
    long count = 1;
    for (int i = 0; i < textChars.length; i++) {
        textChars[i] = repl.getOrDefault(text.charAt(i), text.substring(i, i+1));
        count = Math.multiplyExact(count, textChars[i].length());
    }
    long comboCount = count;
    return () -> new Iterator<>() {
        private long combo = 0;
        @Override
        public boolean hasNext() {
            return (this.combo < comboCount);
        }
        @Override
        public String next() {
            if (this.combo >= comboCount)
                throw new NoSuchElementException();
            long c = this.combo++;
            char[] buf = new char[textChars.length];
            for (int i = buf.length - 1; i >= 0; i--) {
                buf[i] = textChars[i].charAt((int) (c % textChars[i].length()));
                c /= textChars[i].length();
            }
            return new String(buf);
        }
    };
}

测试

combinations("ABC123", "1I", "3B", "AH", "O0", "0O").forEach(System.out::println);

输出

ABC123
ABC12B
ABCI23
ABCI2B
HBC123
HBC12B
HBCI23
HBCI2B
相关问题