-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathavg.rb
executable file
·83 lines (74 loc) · 1.33 KB
/
avg.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
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
#!/usr/bin/ruby
def print_line(name, line)
printf("%s\t", name)
line.each {|i|
printf("%10.3f ", i)
}
puts ""
end
def print_matrix(matrix)
if matrix.size == 0
return
end
cols = matrix[0].size
min = Array.new(cols, 2**31)
max = Array.new(cols, -2**31)
sum = Array.new(cols, 0)
std = Array.new(cols, 0)
avg = []
row = 0
matrix.each { |line|
col = 0
line.each { |i|
sum[col] += i
std[col] += i*i
if max[col] < i
max[col] = i
end
if min[col] > i
min[col] = i
end
col += 1
}
row += 1
# print_line(row, line)
}
sum.each {|i| avg << i/row}
std.each_index {|i|
std[i] = (std[i] / row) - avg[i] * avg[i];
std[i] = std[i] > 0 ? Math::sqrt(std[i]) : 0
}
# [[ $0 == "sum" ]] && print_line("sum", sum)
# [[ $0 == "avg" ]] && print_line("avg", avg)
print_line("sum", sum)
print_line("avg", avg)
print_line("stddev", std)
# print_line("min", min)
# print_line("max", max)
puts
end
prev_cols = 0
cols = 0
matrix = []
STDIN.each_line { |l|
line = []
l = ' ' + l
l.scan(/\s-?\d*\.?\d+/) { |wd|
d = wd[1..-1].to_f
line << d
}
if line.size == cols and cols > 0
matrix << line
else
print_matrix matrix if matrix.size > 1
if line.size > 0
matrix = [line]
cols = line.size
else
matrix = []
cols = 0
end
end
prev_cols = line.size
}
print_matrix matrix if matrix.size > 0