binary-trees Swift #8 program
source code
/* The Computer Language Benchmarks Game
https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
contributed by Isaac Gouy
*/
class Tree {
var left, right: Tree?
init (_ left: Tree?, _ right: Tree?) {
self.left = left
self.right = right
}
static func with (_ depth: Int) -> Tree {
return (depth == 0)
? Tree (nil, nil)
: Tree ( with(depth-1), with(depth-1))
}
func nodeCount () -> Int {
return (left == nil)
? 1
: 1 + left!.nodeCount() + right!.nodeCount()
}
func clear () {
if (left != nil) {
left?.clear()
self.left = nil
right?.clear()
self.right = nil
}
}
}
func main(_ n: Int) {
let minDepth = 4
let maxDepth = minDepth + 2 > n ? minDepth + 2 : n
let stretchDepth = maxDepth + 1
stretch(stretchDepth)
let longLivedTree = Tree.with(maxDepth)
for depth in stride(from: minDepth, to: stretchDepth, by: 2){
let iterations = 1 << (maxDepth - depth + minDepth)
var sum = 0
for _ in 1...iterations {
sum += count(depth)
}
print("\(iterations)\t trees of depth \(depth)\t check: \(sum)")
}
let count = longLivedTree.nodeCount()
longLivedTree.clear()
print("long lived tree of depth \(maxDepth)\t check: \(count)")
}
func stretch(_ depth: Int) {
print("stretch tree of depth \(depth)\t check: \(count(depth))")
}
func count(_ depth: Int) -> Int {
let t = Tree.with(depth)
let c = t.nodeCount()
t.clear()
return c
}
main(
(CommandLine.argc > 1)
? Int(CommandLine.arguments[1])!
: 10 )
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
Swift version 6.0
(swift-6.0-RELEASE)
Target: x86_64-unknown-linux-gnu
Mon, 14 Oct 2024 02:20:09 GMT
MAKE:
/opt/src/swift-6.0-RELEASE/usr/bin/swiftc binarytrees.swift-8.swift -Ounchecked -wmo -o binarytrees.swift-8.swift_run
13.89s to complete and log all make actions
COMMAND LINE:
./binarytrees.swift-8.swift_run 21
PROGRAM OUTPUT:
stretch tree of depth 22 check: 8388607
2097152 trees of depth 4 check: 65011712
524288 trees of depth 6 check: 66584576
131072 trees of depth 8 check: 66977792
32768 trees of depth 10 check: 67076096
8192 trees of depth 12 check: 67100672
2048 trees of depth 14 check: 67106816
512 trees of depth 16 check: 67108352
128 trees of depth 18 check: 67108736
32 trees of depth 20 check: 67108832
long lived tree of depth 21 check: 4194303