如何使用一组数字生成每个整数?

时间:2013-07-23 08:01:12

标签: java algorithm

如果设置较大,我想生成包含int(或0,1,2,2,4,4 s)的每个long。 对于少量数字,手动很容易实现,但我不明白我是如何做到的。

对于一个不那么大的整数集,就像我的样本一样,我们可以使用类似的东西:

for(i = 102244; i <= 442210; i++){
   //check if the digits are in the number
   //add it to a tree
}

但正如你所看到的,对于一个更大的集合,复杂性远远不是我们能做的最好的(O(10 n ),但我可能错了)。你有什么提示怎么做吗?

样本是随机选择的,不是作业!

这是我的解决方案,但它并没有真正针对庞大数字进行优化,但可能对某些人有所帮助:

@Test
public void testPossibleNumbers(){
    TreeSet<Long> possibleNumbers = new TreeSet<Long>();
    String a = "012244";
    permutation("",a,possibleNumbers);
    LOGGER.info("Array of possible numbers"); //breapoint: 150 solutions
}

private static void permutation(String prefix, String str, TreeSet<Long> tree) {
    int n = str.length();
    if (n == 0 && !prefix.startsWith("0")){
        tree.add(Long.parseLong(prefix));
    }
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n), tree);
    }
}

2 个答案:

答案 0 :(得分:1)

您只需枚举起始“集合”的所有排列(它不是真正的集合,它包含重复项)。当然,你可能会得到一些重复的东西(因为你没有从一组开始)和以(任意数量)0(es)开头的数字,你应该考虑到这些。

我要做的是使用某种容器(std :: set in c ++),它不接受重复,然后开始使用排列推送数字,如012244 012244 012424 012442 ... 442210

容器会考虑重复项,零“问题”不会成为问题,因为0 * 10 ^ 5 + 1 * 10 ^ 4 + ... + 2不会跟踪领先“0”。

答案 1 :(得分:1)

我首先将数据从重复列表转换为将10个可能数字中的每一个映射到可用数字的字典。某些条目的重复次数为0,表示不使用该数字。

我们将从左到右进行,这样我们就可以处理在最左边位置不使用0的业务。

1)对于最左边的位置,使用字典构建候选数字列表。将0从此列表中删除。 2)考虑以前的选择,为下一个地方建立候选人名单。每个候选列表都放在一个堆栈上。

对于OP给出的数据0,1,2,4,4,我们构建了以下堆栈:

{4}        num = 102244
{4}        num = 10224_
{2, 4}     num = 1022__
{2, 4}     num = 102___ (0 and 1 are all used)
{0, 2, 4}  num = 10____ (since we've used all the ones)
{1, 2, 4}  num = 1_____ (since 0 is not allowed on the left)

3)回溯。从堆栈顶部的选项列表中删除第一个数字,它已被使用。将下一个选项放在整数的适当槽中。如果没有其他选择,请弹出堆栈,直到可以做出选择。

所以在第3步之后,堆栈看起来像:

{4}        num = 1024__
{2, 4}     num = 102___ (0 and 1 are all used)
{0, 2, 4}  num = 10____ (since we've used all the ones)
{1, 2, 4}  num = 1_____ (since 0 is not allowed on the left)

4)按照步骤1和2重建堆栈。

{4}        num = 102424
{2, 4}     num = 10242_
{4}        num = 1024__
{2, 4}     num = 102___ (0 and 1 are all used)
{0, 2, 4}  num = 10____ (since we've used all the ones)
{1, 2, 4}  num = 1_____ (since 0 is not allowed on the left)

5)继续这种方式,直到不再做出选择。

请注意,此方法仅发出有效数字,而且不会重复。

使用python代码:

data = [0, 1, 2, 2, 4, 4]
results = []

# Number of digits
n = len(data)

# initialize the counts
counts = dict((i, 0) for i in range(10))
for digit in data:
    counts[digit] += 1

# We use this to keep track of the digits that have been used
used = dict((i, 0) for i in range(10))


choice_stack = []

# This is where we'll store the digits
slots = []

first = True
while first or len(choice_stack) > 0:

    # build phase
    while True:
        choices = []
        for i in range(10):
            # no 0 allowed in the left-most place
            if i == 0 and first:
                first = False
                continue
            if counts[i] - used[i] > 0:
                choices.append(i)

        # Leave the build phase if we've used all of our digits
        if len(choices) == 0:
            break;

        choice_stack.append(choices)
        slots.append(choices[0])
        used[choices[0]] += 1

    # Compute the integer
    num = 0
    for i in range(n):
        num += 10**i * slots[-i - 1]
    results.append(num)

    # backtrack phase
    while len(choice_stack) > 0:
        choices = choice_stack.pop()
        slots.pop()
        used[choices[0]] -= 1

        del choices[0]
        if len(choices) == 0:
            continue

        # next choice
        choice_stack.append(choices)
        slots.append(choices[0])
        used[choices[0]] += 1
        break

# Format the results
import sys
for i in range(len(results)):
    if i%6:
        sys.stdout.write(' ')
    else:
        sys.stdout.write('\n')
    sys.stdout.write(str(results[i]))
sys.stdout.write('\n')

输出结果为:

102244 102424 102442 104224 104242 104422
120244 120424 120442 122044 122404 122440
124024 124042 124204 124240 124402 124420
140224 140242 140422 142024 142042 142204
142240 142402 142420 144022 144202 144220
201244 201424 201442 202144 202414 202441
204124 204142 204214 204241 204412 204421
210244 210424 210442 212044 212404 212440
214024 214042 214204 214240 214402 214420
220144 220414 220441 221044 221404 221440
224014 224041 224104 224140 224401 224410
240124 240142 240214 240241 240412 240421
241024 241042 241204 241240 241402 241420
242014 242041 242104 242140 242401 242410
244012 244021 244102 244120 244201 244210
401224 401242 401422 402124 402142 402214
402241 402412 402421 404122 404212 404221
410224 410242 410422 412024 412042 412204
412240 412402 412420 414022 414202 414220
420124 420142 420214 420241 420412 420421
421024 421042 421204 421240 421402 421420
422014 422041 422104 422140 422401 422410
424012 424021 424102 424120 424201 424210
440122 440212 440221 441022 441202 441220
442012 442021 442102 442120 442201 442210