-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeParser.rb
57 lines (46 loc) · 913 Bytes
/
TreeParser.rb
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
require 'json'
class TreeParser
attr_accessor :depth
public
def sum
sum = 0
@layers.each{|layer| layer.each{|item| sum += item} }
sum
end
def initialize(text)
@text = text
@array = JSON.parse(text)
end
def get_layers
get_array
@layers
end
private
def get_array
@depth = array_depth(@array) - 1
@layers = Array.new(@depth) { Array.new()}
parse(@array[1], 0)
@layers[0].push(@array[0])
@layers.delete_if{ |layer| layer.count == 0}
end
def parse(tree, level)
if tree[0].is_a? (Array)
parse(tree[0], level + 1)
else
@layers[level].push(tree[0])
end
if tree[1].is_a? (Array)
parse(tree[1], level + 1)
else
@layers[level].push(tree[1])
end
end
def array_depth(array)
b, depth = array, 1
until b==b.flatten
depth+=1
b=b.flatten(1)
end
depth
end
end