Greeting, I'm trying to solve the following puzzle:
I have a list of linear ranges which represent one big range.
X'
100 200 300 400 500 600 700 | 900 (X)
|----------|----------|----------|--------+----------|
0 | 100 (Y)
Y'
X consists of the following ranges (even and round numbers are just examples for ease of comprehension, they could be anything, no proportions here at all):
- from 100 to 200
- from 300 to 400
- from 500 to 600
- from 700 to 900
On the flip side, Y has just one range:
- from 0 to 100
Both X and Y are of the same length, just different units. Lets say one is dollars and another is percents (or any other similarly unrelated units). So Y'0 == X'100 and Y'100 == X'900.
Question: Given any point in Y, what is equivalent point in X and vise-versa, given a point in X - what is it in Y?
Is this a typical math problem? Does it have a name? Anything that would set me in the right direction would help.
Thank you.
Here's solution based on Igor Krivokon's answer. I had to remove multiplication by two to make it work.
input_range = [
[100, 200],
[300, 400],
[500, 600],
[700, 800]
]
range_sum = 0
lookup_list = []
input_range.each do |range_start, range_end|
lookup_list.push [ range_start, range_sum ]
range_sum += range_end - range_start
end
def get_percent(value, lookup_list, range_sum)
result = 0
lookup_list.reverse.each do |range_start, cummulative_sum|
if value >= range_start
result = value + cummulative_sum - range_start
break
end
end
return result.to_f / range_sum.to_f
end
def get_value(percent, lookup_list, range_sum)
result = 0
value = range_sum * percent
lookup_list.reverse.each do |range_start, cummulative_sum|
if value >= cummulative_sum
result = value - cummulative_sum + range_start
break
end
end
return result.to_f
end
puts "Input range: #{input_range.inspect}"
puts "Continous range sum: #{range_sum}"
puts "Lookup list: #{lookup_list.inspect}"
input_range.each do |range|
range.each do |start_or_end|
puts "#{start_or_end} is at " + get_percent(start_or_end, lookup_list, range_sum).to_s
end
end
[ 0, 0.25, 0.5, 0.75, 1 ].each do |percent|
puts "#{percent} is at " + get_value(percent, lookup_list, range_sum).to_s
end
$> ruby ranges.rb
Input range: [[100, 200], [300, 400], [500, 600], [700, 800]]
Continous range sum: 400
Lookup list: [[100, 0], [300, 100], [500, 200], [700, 300]]
100 is at 0.0
200 is at 0.25
300 is at 0.25
400 is at 0.5
500 is at 0.5
600 is at 0.75
700 is at 0.75
800 is at 1.0
0 is at 100.0
0.25 is at 300.0
0.5 is at 500.0
0.75 is at 700.0
1 is at 800.0
$> ruby ranges.rb
Input range: [[100, 200], [300, 400], [500, 600], [700, 1000]]
Continous range sum: 600
Lookup list: [[100, 0], [300, 100], [500, 200], [700, 300]]
100 is at 0.0
200 is at 0.166666666666667
300 is at 0.166666666666667
400 is at 0.333333333333333
500 is at 0.333333333333333
600 is at 0.5
700 is at 0.5
1000 is at 1.0
0 is at 100.0
0.25 is at 350.0
0.5 is at 700.0
0.75 is at 850.0
1 is at 1000.0
It seems to work with any range I give it, back and forth.