Haskell:在线性时间内转换排列,仅使用列表 [英] Haskell : invert a permutation in linear time, using only lists
问题描述
我想定义一个函数
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屋!