我正在尝试编写一种算法,该算法返回长度为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)
}
非常感谢您的帮助!
答案 0 :(得分:3)
这只是计数(以 k 为基数)。您可以执行此操作-将连续的整数转换为以 k 为基数-但这有很多除法和余数,因此您最好使用更简单的方法。
如果有助于理解,可以尝试使用 k = 10(这是普通的十进制计数)进行尝试。例如:
答案 1 :(得分:0)
这是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...))
}
}
答案 2 :(得分:0)
尝试此代码!
代码:
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']