计数在不同的基础上

时间:2012-05-02 06:09:27

标签: algorithm binary decimal

如果要计数超过8位,在基数2中,结果如下:

0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 1 0;
.....
1 1 1 1 1 1 1 1;

但是你如何根据不同的基础制作一个算法 - 对于每个比特来说,ex: 如果根据基数5计算最低有效位,并且最重要的位在基数2上,则结果应如下所示:

0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 0 2;
0 0 0 0 0 0 0 3;
0 0 0 0 0 0 0 4;
1 0 0 0 0 0 0 0;
1 0 0 0 0 0 0 1;
1 0 0 0 0 0 0 2;
...
1 0 0 0 0 0 0 4;

你能告诉我生成这些载体的算法吗?

2 个答案:

答案 0 :(得分:3)

针对此问题的一种算法是大多数学生通常在幼儿园学习的“波纹携带”类型,除了稍作修改。当你添加两个数字时,你会逐位数字:首先是数字位置,然后是数十位,然后是数百位,等等。如果你不得不写下大于10的数字(例如7 + 8) = 15),然后你把它写下来减去10并将10“带”到下一个地方,你在那里添加它(它变为1);这可能会在许多地方“波动”(例如999 + 1 = 1000)。通过使用此算法重复添加一个,我们可以逐个计数。

重要的是澄清我们所追求的东西:对于不同的地方来说,具有不同的基础意味着什么。如果你允许地方有任意数字范围,并代表任意数字,那么可能会发生一些不好的事情:一个数字可以用多种方式写入,和/或一些十进制数字不能写入。因此,我们将自己局限于一个“理智”的方案,如果一个地方 i 有一个基础 b i ,这意味着有效数字为0 ,1,2,..., b i -1 (像往常一样,就像十进制一样),那个地方的数字代表 b i 乘以右边所有碱基的乘积( b i-1 x b i-2 < / sub> x ...)。例如,如果我们的基数为[10,10,10],则数字的值将为[1000,100,10,1];如果我们的基数为[5,10,5],则数字的值将为[250,50,5,1]

如何为数字添加1:

Increment the least-significant digit (LSD)
Perform ripple-carry as follows:
    Set the current place to the LSD
    Repeat as long as the current place exceeds its allowed max digit:
        Set the digit at the current place to 0
        Advance the current place one to the left
        Increment the number at the new place (now on the left)

重复上述算法,直到找到所需的所有数字。

的Python:

from itertools import *

def multibaseCount(baseFunction):
    currentDigits = [0]
    while True:
        yield currentDigits[::-1]

        # add 1
        currentDigits[0] += 1

        # ripple-carry:
        for place,digit in enumerate(currentDigits):
            if currentDigits[place]>=baseFunction(place):    # if exceeds max digit
                currentDigits[place] = 0         # mod current digit by 10
                if place==len(currentDigits)-1:  # add new digit if doesn't exist
                    currentDigits += [0]
                currentDigits[place+1] += 1      # add 1 to next digit
            else:    # doesn't exceed max digit; don't need to carry any more
                break

演示,其中地点n的基数为n + 1:

>>> for digits in islice(multibaseCount(lambda n:n+1),30):
...     print( ''.join(map(str,digits)).zfill(5) )
... 
00000
00010
00100
00110
00200
00210
01000
01010
01100
01110
01200
01210
02000
02010
02100
02110
02200
02210
03000
03010
03100
03110
03200
03210
10000
10010
10100
10110
10200
10210

答案 1 :(得分:0)

如果您真的只对这种格式的八位数“数字”感兴趣,这里有一些伪代码可以帮助您入门:

for (a=0; a<2: a++)
  for (b=0; b<5; b++)
    for (c=0; c<2; c++)
      for (d=0; d<2; d++)
        for (e=0; e<2; e++)
          for (f=0; f<2; f++)
            for (g=0; g<2; g++)
              for (h=0; h<2; h++)
                printf("%d%d%d%d%d%d%d%d\n", a, b, c, d, e, f, g, h);

在这种情况下,它将是基数2,5,2,2,2,2,2,2。根据需要更改索引。

相关问题