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
|
# File 'lib/naive_calculator/repl.rb', line 46
def plot(plot_data)
x_range = 90
y_range = 10
result = (y_range + 1).times.map { ' ' * (x_range + 1) }
samples = x_range.times.map do |x|
rx = (x.to_f / x_range) * (plot_data.max_x - plot_data.min_x) + plot_data.min_x
ry = plot_data.function.call(rx)
[x, rx, ry]
end
min_y, max_y = [
samples.min_by { |x, rx, ry| ry }.last.to_f,
samples.max_by { |x, rx, ry| ry }.last.to_f,
]
range = max_y - min_y
samples.each do |x, rx, ry|
scaled_y = ((ry - min_y) / range * y_range).round
result[y_range - scaled_y][x] = 'O'
end
scaled_y_zero = (-min_y / range * y_range).round
if (0...y_range).include? scaled_y_zero
(x_range + 1).times do |x|
result[y_range - scaled_y_zero][x] = '.' unless result[y_range - scaled_y_zero][x] == 'O'
end
end
scaled_x_zero = (-plot_data.min_x.to_f / (plot_data.max_x - plot_data.min_x) * x_range).round
if (0...x_range).include? scaled_x_zero
(y_range + 1).times do |y|
result[y_range - y][scaled_x_zero] = '.' unless result[y_range - y][scaled_x_zero] == 'O'
end
end
result.join("\n")
end
|