[英]Haskell permutations with the length of the output list
I have such code for creating permutations:我有这样的代码来创建排列:
--unique permutation
perm :: [t] -> [[t]]
perm [] = [[]]
perm (x:xs) = [(y:zs) | (y,ys) <- views (x:xs), zs <- perm ys]
--create all possible views
views :: [t] -> [(t,[t])]
views [] = []
views (x:xs) = ((x,xs) : [ (y,(x:ys)) | (y,ys) <- views xs ])
However I want to limit the output to a certain length.但是我想将输出限制为一定长度。 For example, it should take a parameter specifying the number of elements in the ouput of the permutation.
例如,它应该采用一个参数来指定排列输出中的元素数量。 I want to create k distinct permutations drawn from a list [0..9].
我想从列表 [0..9] 中创建 k 个不同的排列。 So, for example, if k will be equal to 3, then the output should be something like this:[1,2,3], [9,8,7], [0,6,8] etc..
因此,例如,如果 k 将等于 3,那么输出应该是这样的:[1,2,3]、[9,8,7]、[0,6,8] 等等。
Right now if i pass [0..9] to the function it will generate a list with permutations of length 10. I am struggling to come up with a solution.现在,如果我将 [0..9] 传递给该函数,它将生成一个长度为 10 的排列列表。我正在努力想出一个解决方案。 In the end, the function should look like
perm k list
Thank you!最后,
perm k list
的功能应该是这样的 谢谢!
It is connected with this question: Verbal Arithmetics in Haskell (SEND + MORE = MONEY)它与这个问题有关: Haskell 中的 Verbal Arithmetics (SEND + MORE = MONEY)
Do you mean something like this?你的意思是这样的吗?
import Data.List (permutations)
choose n list = concatMap permutations $ choose' list [] where
choose' [] r = if length r == n then [r] else []
choose' (x:xs) r | length r == n = [r]
| otherwise = choose' xs (x:r)
++ choose' xs r
Output:输出:
*Main> choose 2 [0..5]
[[1,0],[0,1],[2,0],[0,2],[3,0],[0,3],[4,0],[0,4],[5,0],[0,5],[2,1]
,[1,2],[3,1],[1,3],[4,1],[1,4],[5,1],[1,5],[3,2],[2,3],[4,2],[2,4]
,[5,2],[2,5],[4,3],[3,4],[5,3],[3,5],[5,4],[4,5]]
Will replicateM
do what you need?威尔
replicateM
你需要什么?
Prelude Control.Monad> take 10 $ replicateM 3 [0..9]
[[0,0,0],[0,0,1],[0,0,2],[0,0,3],[0,0,4],[0,0,5],[0,0,6],[0,0,7],[0,0,8],[0,0,9]]
Prelude Control.Monad> take 10 $ replicateM 4 [1,3,3,7]
[[1,1,1,1],[1,1,1,3],[1,1,1,3],[1,1,1,7],[1,1,3,1],[1,1,3,3],[1,1,3,3],[1,1,3,7],[1,1,3,1],[1,1,3,3]]
Prelude Control.Monad> take 10 $ replicateM 2 [4,2]
[[4,4],[4,2],[2,4],[2,2]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.