gpt4 book ai didi

swift - 打印带有缩进的树。 swift

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:28 24 4
gpt4 key购买 nike

使用 swift 实现树数据结构:

class Node {

var value: String
var children: [Node] = []
weak var parent: Node?

init(_ value: String) {
self.value = value
}

func add(_ child: Node){
children.append(child)
child.parent = self
}

func printTree() {
var text = self.value
if !self.children.isEmpty {
text += "\n " + self.children.map{$0.printTree()}.joined(separator: ", ")
}
print(text)
}

}

我的目标是看到这样的东西:

A1
B2
C3
G6
K0
H7
L8
L9

我知道应该有一些聪明的方法来插入缩进,但我也在与“ map ”作斗争。编译器给我“对成​​员‘map’的模糊引用”。

最佳答案

如果你想让它漂亮,你可以这样做:

extension Node
{
func treeLines(_ nodeIndent:String="", _ childIndent:String="") -> [String]
{
return [ nodeIndent + value ]
+ children.enumerated().map{ ($0 < children.count-1, $1) }
.flatMap{ $0 ? $1.treeLines("┣╸","┃ ") : $1.treeLines("┗╸"," ") }
.map{ childIndent + $0 }
}

func printTree()
{ print(treeLines().joined(separator:"\n")) }
}

a1.printTree()

// A1
// ┣╸B2
// ┣╸C3
// ┃ ┗╸G6
// ┗╸K0
// ┣╸H7
// ┃ ┗╸L8
// ┗╸L9

您还可以将其概括为任何树结构的打印函数,让您选择为每个节点打印什么:

func printTree<T>(_ node:T, _ nodeInfo:@escaping (T)->(String,[T]) ) 
{
func lines(_ aNode:T, _ nodeIndent:String="", _ childIndent:String="") -> [String]
{
let (label,children) = nodeInfo(aNode)
return [ nodeIndent + label]
+ children.enumerated().map{ ($0 < children.count-1, $1) }
.flatMap{ $0 ? lines($1,"┣╸","┃ ") :lines($1,"┗╸"," ") }
.map{ childIndent + $0 }
}
print( lines(node).joined(separator:"\n") )
}

// print a root node providing a capture to obtain the node's label
// and its array of children

printTree(a1){ ($0.value,$0.children) }

// works for any tree structure. for example, views :

printTree(view){( "\(type(of:$0)) \($0.frame)", $0.subviews )}

关于swift - 打印带有缩进的树。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371513/

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