gpt4 book ai didi

检查四叉树水平对称性的算法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:19:14 26 4
gpt4 key购买 nike

data (Eq a, Show a) => QT a = C a | Q (QT a) (QT a) (QT a) (QT a)
deriving (Eq, Show)

Giving the definition as above, write a predicate to check if a given image (coded as a quadtree) is symmetric in respect of vertical axis (horizontal symmetric). Use anonymous function where possible.

问题:如何为给定的四叉树实现水平对称检查?

嗯,我在想这样的事情:当四叉树只是一个叶子时,在这种情况下我们有水平对称性。基本情况是四叉树只有一级(四片叶子)对称性只是检查颜色的问题(c1 == c2 && c3 == c4) .

在任何其他情况下,我可能会检查是否满足递归条件:nw equals (fliphorizontal(ne)) && sw equals (fliphorizontal(se)) , 其中fliphorizontal水平翻转四叉树和equals检查两个四叉树是否相等。但是我想尽可能避免使用外部函数,尽可能避免使用匿名函数。

ishsymmetric :: (Eq a, Show a) => QT a -> Bool
ishsymmetric (C _) = True
ishsymmetric (Q (C c1) (C c2) (C c3) (C c4)) = c1 == c2 && c3 == c4
ishsymmetric (Q nw ne sw se) =

编辑:翻转示例:

fliph :: (Eq a, Show a) => QT a -> QT a
fliph (C a) = C a
fliph (Q nw ne sw se) = Q (fliph ne) (fliph nw) (fliph se) (fliph sw)

编辑:最终的单函数解决方案(使用四叉树的广义折叠函数):

ishsymmetric :: (Eq a, Show a) => QT a -> Bool
ishsymmetric (C _) = True
ishsymmetric (Q a b c d) = and $ zipWith equals [a,c] [fliph b,fliph d]
where
fold f g (C c) = g c
fold f g (Q a b c d) = f (fold f g a) (fold f g b)
(fold f g c) (fold f g d)
fliph q = fold (\a b c d -> Q b a d c) (\c -> C c) q
equals (C c1) (C c2) = c1 == c2
equals (Q a b c d) (Q e f g h) = and $ zipWith equals [a,b,c,d] [e,f,g,h]

最佳答案

类似于:

ishsymmetric :: (Eq a, Show a) => QT a -> Bool
ishsymmetric (C _) = True
ishsymmetric (Q (C c1) (C c2) (C c3) (C c4)) = c1 == c2 && c3 == c4
ishsymmetric (Q nw ne sw se) = equals nw (fliph ne) && equals sw (fliph se)
where equals (C a) (C b) = a == b
equals (Q a b c d) (Q e f g h) = equals a e && equals b f && equals c g && equals d h
fliph (C a) = C a
fliph (Q nw ne sw se) = Q (fliph ne) (fliph nw) (fliph se) (fliph sw)

但是句法优化是可能的。 :-/

关于检查四叉树水平对称性的算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4907802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com