【问题标题】:doing arithmetic on a base N number system using arbitrarily defined characters使用任意定义的字符在 N 基数系统上进行算术运算
【发布时间】:2018-09-10 14:51:11
【问题描述】:

首先,这不是家庭作业。我需要这个解决方案来为连接到 AWS EC2 实例的设备分配设备名称。我正在使用 Java。

我正在寻找一种解决方案,我可以定义任意一组字符作为数字来表示基数 N 的数字,然后能够增加和减少这些值。例如,假设我用数字集 {f,g,h} 定义了一个以 3 为底的数字系统。因此,从十进制的“0”开始并递增,我们将有以下序列: f, g, h, gf, gg, gh, hf, hg, hh

这需要处理大于基数 10 的数字,因此字符和罗马数字之间的简单映射将无法解决问题。

至于我的具体用例,我将通过分配连接到机器的设备名称来完成此操作,但禁止使用某些字母,因此我将定义一组自定义的允许字符。

我尝试自己实现这一点,但很快就陷入了让我绊倒的逻辑兔子洞。似乎其他人可能已经实施了一些东西,或者至少部分实施了。有什么想法吗?

【问题讨论】:

  • 这听起来就像你想要一组符号的排列。如果您查找现有的解决方案,您可能会找到答案。
  • 你搞错顺序了!!正确的应该是:f, g, h, gf, gg, gh, hf, hg, hh.
  • @dbl 谢谢,我修好了。这就是为什么我喜欢电脑做这些事情,而不是我!

标签: java numbers increment


【解决方案1】:

这样的?我在幕后使用BigInteger 来避免所有溢出,并在toString 中即时生成数字。

class Counter {
    // My current value.
    private BigInteger n;
    // The character set to use.
    private char[] digits = "0123456789".toCharArray();

    public Counter() {
        this(0);
    }

    public Counter(long start) {
        n = BigInteger.valueOf(start);
    }

    public void inc() {
        n = n.add(BigInteger.ONE);
    }

    public void dec() {
        n = n.subtract(BigInteger.ONE);
    }

    public void setDigits(char[] digits) {
        this.digits = digits;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        BigInteger base = BigInteger.valueOf(digits.length);
        for (BigInteger v = n; v.compareTo(BigInteger.ZERO) > 0; v = v.divide(base)) {
            sb.append(digits[v.mod(base).intValue()]);
        }
        return sb.length() == 0 ? "" + digits[0] : sb.reverse().toString();
    }

}

private void test(String s) {
    Counter counter = new Counter();
    counter.setDigits(s.toCharArray());
    for (int i = 0; i < 100; i++, counter.inc()) {
        System.out.println(counter);
    }
}

private void test() {
    test("0123456789");
    test("fgh");
    test("QwErTyUiOpAsDfGhJkLzXcVbNm");
}

【讨论】:

    猜你喜欢
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多