1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
"use strict";
const usedNumbers = []; function getRandomUniqueNumber() { let num; do { num = ~~(Math.random() * 90 + 1); } while(usedNumbers.indexOf(num) !== -1); usedNumbers.push(num); return num; }
const assert = require("assert"); const cp = require("child_process"); import Node from "./Node"; import RBNode from "./RBNode"; import BST from "./BST"; import AVL from "./AVL"; import RBT from "./RBT"; const fs = require("fs"); const path = require("path");
const startTime = Date.now();
const arr = Array.from(new Array(20), () => getRandomUniqueNumber()); const rbt = new RBT(arr); console.log(arr);
beautifyRBTree(rbt);
avl.insert(8); avl.remove(usedNumbers[0]); avl.remove(usedNumbers[8]); avl.remove(usedNumbers[3]);
console.log("Test finished in", Date.now() - startTime, "ms");
beautifyTree(avl);
function beautifyTree(bst) { let str = "graph {\n"; str += mapBSTNode(bst.root); str += "}"; fs.writeFileSync("result.txt", str); fs.writeFileSync("tree.png", cp.execSync("dot -Tpng result.txt")); return; const values = bst.preOrder(); fs.writeFileSync(path.join(__dirname, "output-tree-data.js"), `var values = [${values.join(",")}]`); }
function beautifyRBTree(rbt) { let str = "graph {\nnode[fontname=Courier];\n"; str += mapRBTNode(rbt.root); str += "}"; fs.writeFileSync("result.txt", str); fs.writeFileSync("tree.png", cp.execSync("dot -Tpng result.txt")); return; }
function mapBSTNode(node) { let str = ""; if(node.left) { str += ` ${node.val} -- ${node.left.val}\n`; str += mapBSTNode(node.left); } if(node.right) { str += ` ${node.val} -- ${node.right.val}\n`; str += mapBSTNode(node.right); } return str; }
function mapRBTNode(node) { let str = ""; const DEF = "fontcolor=gray, style=filled, height=.1, shape=point, color=gray"; if(node.left) { str += ` ${node.val}[fontcolor=white, color=${node.color}, style=filled];\n` + ` ${node.left.val}[fontcolor=white, color=${node.left.color}, style=filled];\n` + ` ${node.val} -- ${node.left.val};` str += mapRBTNode(node.left); } else { str += ` ${node.val}[fontcolor=white, color=${node.color}, style=filled];\n` + ` ${node.val-0.5}[${DEF}];\n` + ` ${node.val} -- ${node.val-0.5};` } if(node.right) { str += ` ${node.val}[fontcolor=white, color=${node.color}, style=filled];\n` + ` ${node.right.val}[fontcolor=white, color=${node.right.color}, style=filled];\n` + ` ${node.val} -- ${node.right.val};`; str += mapRBTNode(node.right); } else { str += ` ${node.val}[fontcolor=white, color=${node.color}, style=filled];\n` + ` ${node.val+0.5}[${DEF}];\n` + ` ${node.val} -- ${node.val+0.5};` } return str; }
|