Skip to content

Commit dbcbb25

Browse files
committed
Add 2.swift for binarytrees
1 parent ad18b20 commit dbcbb25

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import Foundation
2+
3+
let minDepth = 4
4+
let maxDepth: Int = {
5+
if CommandLine.argc <= 1 { return 10 }
6+
return max(minDepth + 2, Int(CommandLine.arguments[1]) ?? 10)
7+
}()
8+
9+
let stretchDepth = maxDepth + 1
10+
print("stretch tree of depth \(stretchDepth)\t check: \(Tree(depth: stretchDepth).check())")
11+
12+
let longLivedTree = Tree(depth: maxDepth)
13+
let nResults = (maxDepth - minDepth) / 2 + 1
14+
15+
for i in 0..<nResults {
16+
let depth = i * 2 + minDepth
17+
let n = 1 << (maxDepth - depth + minDepth)
18+
19+
var chk = 0
20+
for _ in 0..<n {
21+
chk += Tree(depth: depth).check()
22+
}
23+
print("\(n)\t trees of depth \(depth)\t check: \(chk)")
24+
}
25+
26+
print("long lived tree of depth \(maxDepth)\t check: \(longLivedTree.check())")
27+
28+
struct Tree {
29+
struct Node {
30+
var left: Int
31+
var right: Int
32+
}
33+
34+
private static let none: Int = -1
35+
private var nodes: [Node] = []
36+
private var root: Int = none
37+
38+
init(depth: Int) {
39+
let total = (1 << (depth + 1)) - 1
40+
guard total > 0 else { return }
41+
42+
nodes = Array(repeating: Node(left: Self.none, right: Self.none), count: total)
43+
root = 0
44+
45+
for i in 0..<total {
46+
let l = 2 * i + 1
47+
let r = l + 1
48+
if l < total { nodes[i].left = l }
49+
if r < total { nodes[i].right = r }
50+
}
51+
}
52+
53+
func check() -> Int {
54+
let span = nodes.span
55+
return _check(index: root, span: span)
56+
}
57+
58+
private func _check(index: Int, span: Span<Node>) -> Int {
59+
if index == Self.none { return 0 }
60+
let node = span[Int(index)]
61+
return 1 + _check(index: node.left, span: span)
62+
+ _check(index: node.right, span: span)
63+
}
64+
}

bench/bench_swift.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ problems:
66
- name: binarytrees
77
source:
88
- 1.swift
9+
- 2.swift
910
- name: nbody
1011
source:
1112
- 7.swift

0 commit comments

Comments
 (0)