Haskell:在线性时间内转换排列,仅使用列表 [英] Haskell : invert a permutation in linear time, using only lists

查看:166
本文介绍了Haskell:在线性时间内转换排列,仅使用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个函数

  invert :: [Int]  - > [Int] 

假设其输入是 [0。 。(n-1)] ,并返回它的逆。我们可以使用列表和元组(不包括数组)来定义它,以便它以线性时间运行吗?



这主要是出于学术兴趣;在实际的代码中,我可以使用 Array STArray 或类似的名称。

解决方案

所以,这不使用仅列表。但它似乎很适合。

 将限定的Data.Vector导入为V 

翻译:: [Int] - > [Int]
invert list = V.toList $ vec V.// assocs
其中vec = V.fromList list - 更好的想法来初始化vec?
assocs = zip(map pred list)[1 ..]

请参阅 Vector package ,它声称 // O(n)。那么它说 O(n + m),但在这种情况下, n = m



我将它加载到ghci中,并得到与德米特里相同的答案。 :)

I want to define a function

invert :: [Int] -> [Int]

that assumes that its input is a permutation of [0..(n-1)], and returns its inverse. Can one define it using only lists and tuples (without arrays) so that it runs in linear time?

This is primarily out of academic interest; in real code I might use Array or STArray or similar.

解决方案

So, this doesn't use "only lists". But it seemed to fit so well.

import qualified Data.Vector as V

invert :: [Int] -> [Int]
invert list = V.toList $ vec V.// assocs
  where vec = V.fromList list -- better ideas for initializing vec?
        assocs = zip (map pred list) [1..]

See the Vector package, which claims that // is O(n). Well, it says O(n+m), but in this case, n = m.

I loaded it up into ghci and got the same answer as dmitry. :)

这篇关于Haskell:在线性时间内转换排列,仅使用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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