Is there any way to find out how many intervals greater than x exist in a list of values?

70 Views Asked by At

I'm not a professional mathematics, but I have a problem of applied mathematics. Beforehand, I apologize for not using more technical terms. I hope I can be as clear as possible:

Given the following values: 8, 9, 10 and 20.

How many times I have an interval greater or equal then 6?

The answer is 1, because between 10 and 20 we have an interval of 10.

In this other list: 8, 9, 10, 11, 12 the answer is 0.

And, finally, in this list: 3, 10 and 20 the answer is 3.

Is there a function or way to figure this anwser using math?

Thank to all

2

There are 2 best solutions below

8
On

You have a set of $n$ numbers $A = \{ x_1, \ldots, x_n \}$, where we assume that those numbers are sorted: $x_1 < x_2 < \cdots < x_n$.

You can form intervals $[x_i, x_j]$ for $i < j$, with length $x_{ij} = x_j - x_i$.

If one arranges the $x_{ij}$ as a $n\times n$ matrix, these are the elements above the diagonal. There are $N = \frac{(n-1) n}{2}$ of such intervals.

You could formulate your query as $$ m = \sum_{\overset{i < j}{x_{ij} \ge 6}} 1 = \text{card}\{ x_{ij} \mid i<j \wedge x_{ij} \ge 6 \} $$

The question how to organize a large set of numbers such that certain queries can be performed efficiently is subject to computer science, in particular data structures.

Example:

Set of given numbers: $$ A = \{ 1, 3, 10, 22 \} $$ Matrix of differences $x_{ij}$: $$ \left( \begin{array}{rrr} 0 & \color{red} 2 & \color{green} 9 & \color{green}{21} \\ -2 & 0 & \color{green} 7 & \color{green}{19} \\ -9 & -7 & 0 & \color{green}{12} \\ -21 & -19 & -12 & 0 \end{array} \right) $$ You would need to traverse the $N = ((4-1)4/2 = 6$ elements above the diagonal to evaluate your query.

In a real program you would not construct the full matrix but would use two loops for the indices $i$, $j$ with proper parameters and act on the set $A$, to just calculate the $N$ positive differences and not more.

Update:

The related problem turns out to find a function, which takes a sequence (a tuple) of times $$ t = (t_1, t_2, \ldots, t_n) $$ where $t_i < t_j$ for $i < j$ and to split this sequence along gaps $t_{ij} = t_j - t_i \ge 6$.

Using a programming language expressing this would take more room than the description above, depending on the support of that language for organizing and processing data as tuples or lists, a Ruby program would be shorter than a C program.

A mathematical function would be recursive and probably need some helper functions to formulate operations on a tuple.

0
On

I think your problem is related to the MAX-GAP problem, see for example https://stackoverflow.com/questions/10262937/array-maximum-difference-algorithm-that-runs-in-on