[英]Number of k-combinations for all N
我正在嘗試編寫一個算法,它返回長度為n的值0,1和2的所有可能組合的數組。
例如,當n = 2時:
00
01
02
10
11
12
20
21
22
我已經開始但遠非正確或完成的代碼:
func main() {
var results []string
matches := rangeSlice(2)
for a := 0; a < len(matches); a++ {
for b := 0; b < 3; b++ {
matches[(len(matches) - a) - 1] = b
results = append(results, strings.Join(convertValuesToString(matches), ""))
}
}
printResults(results)
}
非常感謝您的幫助!
這只是計數(在基數k )。 你可以這樣做 - 將連續的整數轉換為基數k - 但這是很多除法和余數,所以你不妨使用更簡單的方法。
如果它有助於理解,你可以嘗試使用k = 10,這是普通的十進制計數。 例如:
這是rici解決方案(計數)的實現。 (輸出采用2D切片的形式,每個切片組合。)
要生成示例輸出,請使用getCombinations(3, 2)
。
func getCombinations(base, length int) [][]int {
// list of combinations always includes the zero slice
combinations := [][]int{make([]int, length)}
current := make([]int, length)
for {
incrementIndex := length - 1
// zero trailing <base - 1>'s
for current[incrementIndex] == base-1 {
current[incrementIndex] = 0
incrementIndex--
// stop when the next digit to be incremented is "larger"
// than the specified (slice) length
if incrementIndex < 0 {
return combinations
}
}
// increment the least significant non-<base - 1> digit
current[incrementIndex]++
// copy current into list of all combinations
combinations = append(combinations, append([]int{}, current...))
}
}
試試這個代碼!
代碼:
n = int(input("Enter value of n :"))
result=[]
for num1 in range(0,n+1):
for num2 in range(0,n+1):
result.append(str(num1)+str(num2))
print(result)
輸出:
Enter value of n :3
['00', '01', '02', '03', '10', '11', '12', '13', '20', '21', '22', '23', '30', '31', '32', '33']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.