计算在F#的排列 [英] Calculating permutations in F#

查看:122
本文介绍了计算在F#的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本<一个启发href="http://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f">question和<一href="http://stackoverflow.com/questions/283561/extracting-leaf-paths-from-n-ary-tree-in-f#283638">answer,如何创建在F#泛型排列算法?谷歌并没有提供任何有用的答案了这一点。

Inspired by this question and answer, how do I create a generic permutations algorithm in F#? Google doesn't give any useful answers to this.

编辑:我为我的最好的答案在下面,但我怀疑托马斯的比较好

I provide my best answer below, but I suspect that Tomas's is better (certainly shorter!)

推荐答案

你也可以这样写:

let rec permutations list taken = 
  seq { if Set.count taken = List.length list then yield [] else
        for l in list do
          if not (Set.contains l taken) then 
            for perm in permutations list (Set.add l taken)  do
              yield l::perm }

在'名单'的说法包含了所有你想要重排和取是一组,其中包含已使用的号码的数字。该函数返回时,所有的数字都采取了空单。 否则,它遍历仍可用的所有号码,获取剩余的号码(递归使用'置换')的所有可能的排列,并返回(L ::烫发)之前追加当前号码给每个人。

The 'list' argument contains all the numbers that you want to permute and 'taken' is a set that contains numbers already used. The function returns empty list when all numbers all taken. Otherwise, it iterates over all numbers that are still available, gets all possible permutations of the remaining numbers (recursively using 'permutations') and appends the current number to each of them before returning (l::perm).

要运行这个,你给它一个空集,因为没有号用于开头:

To run this, you'll give it an empty set, because no numbers are used at the beginning:

permutations [1;2;3] Set.empty;;

这篇关于计算在F#的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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