aboutsummaryrefslogtreecommitdiff
path: root/challenge-130/iangoodnight/javascript/ch-2.js
blob: a6e60f4acfe1b3a7b6a4f0f5fecfb372a906a3b0 (plain)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env node

/**
 * ch-2.js
 *
 * Task 2 > Binary Search Tree
 * ===========================
 *
 * You are given a tree.  Write a script to find out if the given tree is a
 * `Binary Seach Tree (BST)`.  According to wikipedia, the definition of BST:
 *
 * > A binary search tree is a rooted binary tree, whose internal nodes each
 * > store a key (and optionally, an associated value), and each had two
 * > distinguished sub-trees, commonly denoted left and right.  The tree
 * > additionally satisfies the binary seach property: the key in each node is
 * > greater than or equal to any key stored in the left sub-tree, and less than
 * > or equal to any key stored in the right sub-tree.  The leaves (final nodes)
 * > of the tree contain no key and have no structure to distinguish them from
 * > one another.
 *
 * Example 1
 * =========
 *
 * Input:
 *
 *     8
 *    / \
 *   5   9
 *  / \
 * 4   6
 *
 * Output: 1 as the given tree is a BST.
 *
 * Example 2
 * =========
 *
 * Input:
 *
 *     5
 *    / \
 *   4   7
 *  / \
 * 3   6
 *
 * Output: 0 as the given tree is not a BST.
 **/

'use strict';

/**
 * Node built-in dependencies
 **/

const fs = require('fs');

const path = require('path');

/**
 * Here, our BinarySearchTree validator (PWC solution)
 **/

function isBST(binaryTree = {}) {
  // Guard against obviously bad input
  if (typeof binaryTree !== 'object' || !binaryTree.root) return false;
  // This is our actual solution, `isBST` is just a wrapper for it
  const recurse = ((node, min = null, max = null) => {
    // if no node, we've reached the end of the tree without failing.  Pass.
    if (!node) return true;
    // if we've exceed our max, fail
    if (max !== null && node.data >= max) return false;
    // if we find a value less than our min, fail
    if (min !== null && node.data <= min) return false;
    // Recurse through the rest of the nodes.
    return (
      recurse(node.left, min, node.data) &&
      recurse(node.right, node.data, max)
    );
  });
  // Start recursion at the validated root
  return recurse(binaryTree.root);
}

/**
 * Followed by some utilities to test our solution
 **/

// BinaryNode and BinaryTree classes to build test cases
class BinaryNode {
  constructor(data) {
    this.data = data;
  }
  // addRight and addLeft methods to keep our nodes binary and our leaves clear
  addRight(data) {
    if (this.right) return false;
    this.right = new BinaryNode(data);
    return this;
  }

  addLeft(data) {
    if (this.left) return false;
    this.left = new BinaryNode(data);
    return this;
  }
}

class BinaryTree {
  constructor(data = null) {
    if (data !== null) {
      this.root = new BinaryNode(data);
    } else {
      this.root = data;
    }
  }
  // In the case where Binary tree is initialized without a root or when
  // over-writing an existing tree.
  addRoot(data) {
    if (!data) return false;
    this.root = new BinaryNode(data);
  }
  // Private crawl method
  #crawl(callback) {
    const recurse = (node) => {
      callback(node);
      if (node.left) recurse(node.left);
      if (node.right) recurse(node.right);
    }
    recurse(this.root);
  }
  // Find and return a node by data value to assist in building our tree
  findNode(data) {
    let found = false;
    this.#crawl((node) => {
      if (node.data === data) {
        found = node;
        return;
      }
    });
    return found;
  }
}
// Utility for turning strings into integers or floats if necessary to avoid
// awkward comparisons
function parseArg(stringArg = '') {
  const int = /^-?\d+$/;

  const float = /^-?\d*\.\d+$/;

  if (int.test(stringArg)) return parseInt(stringArg);
  if (float.test(stringArg)) return parseFloat(stringArg);

  return stringArg;
}
// Parses input strings into BinaryTrees
function buildTreeFromStringArr(stringArr = []) {
  const binaryTree = new BinaryTree();

  const root = parseArg([...stringArr].shift().trim());

  if (root === NaN || root === '') return binaryTree;
  const lines = [...stringArr];

  binaryTree.addRoot(root);

  while (lines.length > 0) {
    const valueString = lines.shift();

    const values = valueString.trim().split(/\s+/)
      .map((val) => {
        return { value: parseArg(val), idx: valueString.indexOf(val) };
      });

    const connections = lines.shift();

    const leaves = lines[0];

    if (connections) {
      for (let i = 0; i < values.length; i++) {
        const node = binaryTree.findNode(values[i].value);

        const leftBound = i === 0 ? 0: values[i - 1].idx + 1;

        const rightBound = i === values.length - 1 ?
          leaves.length :
          values[i + 1]?.idx + 1;
        const connectionRange = connections.slice(leftBound, rightBound);

        const leftIdx = connectionRange.indexOf('/');

        const rightIdx = connectionRange.indexOf('\\');

        const left = leftIdx !== -1 && leftIdx < values[i].idx;

        const right = rightIdx !== -1 && rightIdx > values[i].idx;

        if (left) {
          const range = leaves.slice(leftBound, values[i].idx);

          const leaf = parseArg(range.trim());

          node.addLeft(leaf);
        }

        if (right) {
          const range = leaves.slice(values[i].idx + 1, rightBound);

          const leaf = parseArg(range.trim());

          node.addRight(leaf);
        }
      }
    }
  }
  return binaryTree;
}
// Paritions inputs form expected outputs and return display, tree, and expected
// output for testing
function parseTestCase(filePath = '') {
  try {
    const data = fs.readFileSync(filePath, 'utf8');

    const lines = data.split('\n')
      .filter(line => {
        return line.trim().charAt(0) !== '#' && line.trim().length !== 0;
      }
    );
    const [treeData, outputs] = lines.reduce(([data, tests], line) => {
      if (tests.length > data.length) data.push([]);
      if (line.indexOf('Output') !== -1) {
        tests.push(parseInt(line.trim().slice(-1)));
        return [data, tests];
      }
      if (!data[tests.length]) data[tests.length] = [];
      data[tests.length].push(line);
      return [data, tests];
    },[[[]], []]);

    const trees = treeData.map(treeArr => buildTreeFromStringArr(treeArr));

    if (trees.length !== outputs.length) {
      throw new Error('Missing inputs or outputs');
    }

    const displays = treeData.map(treeArr => treeArr.join('\n'));

    return [ displays, trees, outputs ];
  } catch (error) {
    console.log('Problems parsing test cases: ', error);
  }
}

function assertMatch(tree, output) {
  console.log('Expected: ', output);
  const result = isBST(tree);

  if (result) {
    console.log('Result: 1 as the given tree is a BST.');
  } else {
    console.log('Result: 0 as the given tree is not a BST.')
  }
  if (!!output === result) {
    return console.log('\x1b[32m%s\x1b[0m', 'Passed \u2690');
  }
  console.log('\x1b[31m%s\x1b[0m', 'Failed \u2715');
}

const isFile = (filePath) => fs.lstatSync(filePath).isFile();

const isDirectory = (filePath) => fs.lstatSync(filePath).isDirectory();

/**
 * And our test runner
 **/

(function main() {
  const testPath = process