一種算法是一種「波進」另外的大多數學生通常學習在幼兒園,只是略作修改。當您添加兩個數字,你這樣做位數按位數:首先是個位,那麼十位,那麼百位等,如果你曾經寫下的數字大於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
嵌套'for'循環大概是最簡單的,但非常緊密聯繫在一起的兩個數數字和涉及的基地。另一種只使用單個'for'-樣式循環的方法將依賴於爲特定數字設計的輸出例程。你試圖解決什麼問題? – sarnold
我試圖獲得所有可能的8位組合,但是每一位都遵守特定的基礎(例如:位數1屬於基數2;位數2屬於基數5 ......) – user1312014
我認爲你的意思是把所有這些0放在左邊的大小,所以它是00 01 02 03 04 10 11 12 13 14 ... – ninjagecko