我的意思是所有数字 _ _ _ _ _ _ _ 都是不同的,只能输入 2 到 9 的值。我尝试过使用数组和循环,但我只是想不出显示所有数字的解决方案。示例 2 到 9 中的 7 位数字是:234567 234568 234569
324567 324568 324569
请注意,这些值中的数字都没有重复。我真的不知道发生了什么。请帮我!
我的意思是所有数字 _ _ _ _ _ _ _ 都是不同的,只能输入 2 到 9 的值。我尝试过使用数组和循环,但我只是想不出显示所有数字的解决方案。示例 2 到 9 中的 7 位数字是:234567 234568 234569
324567 324568 324569
请注意,这些值中的数字都没有重复。我真的不知道发生了什么。请帮我!
由于您没有指定语言,因此这是 Haskell 的答案。
import Control.Monad
selectPerms :: MonadPlus m => [a] -> Int -> m [a]
selectPerms _ 0 = return []
selectPerms universe n = do
(digit, remain) <- selectDigit universe
xs <- selectPerms remain (n - 1)
return (digit:xs)
selectDigit :: MonadPlus m => [a] -> m (a, [a])
selectDigit [] = mzero
selectDigit (x:xs) = capture `mplus` next
where
capture = return (x, xs)
next = do
(digit, remain) <- selectDigit xs
return (digit, x:remain)
yourAnswer :: [[Int]]
yourAnswer = selectPerms [2..9] 7
由于这听起来有点像家庭作业,所以这里的教育将是一个渐进的过程。首先,尝试蛮力。这是一个可以做到的算法(好吧,真的是Python):
for n1 in range(2,10):
for n2 in range(2,10):
if n2 != n1:
for n3 in range(2,10):
if n3 != n2 and n3 != n1:
for n4 in range(2,10):
if n4 != n3 and n4 != n2 and n4 != n1:
for n5 in range(2,10):
if n5 != n4 and n5 != n3 and n5 != n2 and n5 != n1:
for n6 in range(2,10):
if n6 != n5 and n6 != n4 and n6 != n3 and n6 != n2 and n6 != n1:
for n7 in range(2,10):
if n7 != n6 and n7 != n5 and n7 != n4 and n7 != n3 and n7 != n2 and n7 != n1:
print "%d%d%d%d%d%d%d"%(n1,n2,n3,n4,n5,n6,n7)
它基本上是七个嵌套循环,每个数字位置一个,检查任何时候都没有重复。请注意,这不是一个可以很好地扩展到许多数字位置的解决方案,但它对其中的七个位置表现得很好。如果您想要更多,那么使用较少蛮力的解决方案会更好。
有 7!=5040 种置换 abcdefg 的方法。
从 123456789 中选择 7 个数字有9 C 7 =36 种方法。
给定一个排列“bfgdeac”和一组{1,3,4,5,6,8,9},有一种自然的方法可以使用排列来为该集合提供顺序,即[3,8,9 ,5,6,1,4]。
借自 Python 的itertools 文档。
def permutations(iterable, r=None):
# http://docs.python.org/library/itertools.html#itertools.permutations
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
for number in permutations('23456789',6): # you said 7, but your examples were 6
print number
编辑:或者如果你有 Python 无论如何......
import itertools
for number in itertools.permutations('23456789',6): print number