生成列表的所有排列,包括不同的大小和重复的元素 [英] Generate all permutations of a list including diferent sizes and repeated elements

查看:61
本文介绍了生成列表的所有排列,包括不同的大小和重复的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建函数genAllSize ::[a] -> [[a]],该函数接收列表l并生成按大小排序的所有列表,这些列表可以用列表l的元素构建;即

I wanted to create the function genAllSize ::[a] -> [[a]], that receives a list l and generates all the lists sorted by size that can be built with the elements of the list l; i.e.

> genAllSize [2,4,8] 
[[],[2],[4],[8],[2,2],[4,2],[8,2],[2,4],[4,4],[8,4],[2,8],[4,8],[8,8],[2,2,2],[4,2,2],[8,2,2], ...

您将如何做?我想出了一个使用Data.List排列的解决方案,但我不想使用它.

How would you do it? I came up with a solution using permutations from Data.List but I do not want to use it.

推荐答案

  • 给出输入列表xs,以不确定的方式选择其前缀
  • 对于前缀中的每个元素,以不确定的方式将其替换为xs的任何元素
    • Given an input list xs, select a prefix of that in a non deterministic way
    • For each element in the prefix, replace it with any element of xs, in a non deterministic way
    • 结果:

      > xs = [2,4,8]
      > inits xs >>= mapM (const xs)
      [[],[2],[4],[8],[2,2],[2,4],[2,8],[4,2],[4,4],[4,8],[8,2],[8,4],
      [8,8],[2,2,2],[2,2,4],[2,2,8],[2,4,2],[2,4,4],[2,4,8],[2,8,2],
      [2,8,4],[2,8,8],[4,2,2],[4,2,4],[4,2,8],[4,4,2],[4,4,4],[4,4,8],
      [4,8,2],[4,8,4],[4,8,8],[8,2,2],[8,2,4],[8,2,8],[8,4,2],[8,4,4],
      [8,4,8],[8,8,2],[8,8,4],[8,8,8]]
      

      这篇关于生成列表的所有排列,包括不同的大小和重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆