2012-05-02 38 views
0

如果你想數超過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; 

但你怎麼能作出這樣的計算的算法 - 每個位 - 根據不同的基礎,例如: 如果最低顯著位是根據基地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

嵌套'for'循環大概是最簡單的,但非常緊密聯繫在一起的兩個數數字和涉及的基地。另一種只使用單個'for'-樣式循環的方法將依賴於爲特定數字設計的輸出例程。你試圖解決什麼問題? – sarnold

+0

我試圖獲得所有可能的8位組合,但是每一位都遵守特定的基礎(例如:位數1屬於基數2;位數2屬於基數5 ......) – user1312014

+0

我認爲你的意思是把所有這些0放在左邊的大小,所以它是00 01 02 03 04 10 11 12 13 14 ... – ninjagecko

回答

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。2.根據需要更改索引。對於這個問題

+0

非常感謝@sarnold – user1312014

3

一種算法是一種「波進」另外的大多數學生通常學習在幼兒園,只是略作修改。當您添加兩個數字,你這樣做位數按位數:首先是個位,那麼十位,那麼百位等,如果你曾經寫下的數字大於10(例如7 + 8大= 15),則寫下來減去-10和過「攜帶」在10到下一個地方,在這裏將其添加(它變成1);這可能在許多地方「漣漪」(例如999 + 1 = 1000)。通過使用這種算法重複添加一個,我們可以一個接一個地計算。這是什麼意思了不同的地方有不同的基地:

重要的是要澄清一下我們以後是很重要的。如果你允許地方有任意的數字範圍,並且代表任意數字,那麼可能會發生一些不好的事情:一個數字可以以多種方式寫入,並且/或者一些十進制數字不能被寫入。因此,我們將自己侷限於一種「理智」方案,即如果一個地方具有基礎b ,這意味着有效的數字是0,1,2,...,b - 1(像往常一樣,就像在十進制),並且在那個地方的數字表示所有鹼基的右側(b 倍產物b I-1 X b I-2 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 

10000 
10010 
10100 
10110 
10200 
10210