Finding the median of the largest gap of a sequence of numbers in a set/vector

1k Views Asked by At

Im working on a programming function, but I cant seem to get this equation right. Im hoping someone can help point me in the right direction here.

Say you have a set of numbers:

1, 10, 15, 25

All numbers are in the range 1-30, so 31 would be 1, 0 would be 30.

I am trying to find the best spot to insert a unique number (1-30) in the best location to keep the numbers spaced best. For example, if the set of numbers is 15, 18. Id like the next number to be rounded down and inserted in the middle position of the biggest space. So in this case it would be 7. The set would be 7, 15, 18

The sets of numbers can be really random, meaning different sizes, and different numbers, but they are always 1-30. Always positive integers.

Examples: 1,2,5,10,28 3,4,8,9,12

Any help would be appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

So you mean you're looking for a way to identify the biggest gap in between the numbers and insert the median of the two so that the gap is "bridged"? Anyways, here's what I came up with:

Let's take your last example set, $\{1,2,5,10,28,3,4,8,9,12\}$. Should the numbers be in that order or does order not matter?

If order does matter
Simply take the absolute value of each difference between each two adjacent numbers, like this:

$|1 - 2| = |-1| = 1$
$|2 - 5| = |-3| = 3$ ... and so on.

Find the largest of such differences (in this case, it's $|28 - 3| = 25$.) This difference is the largest and thus has the largest gap between them. Then take the two numbers which have this difference, 28 and 3, and compute their average, rounded down. In code, just use the floor() function to round down: $\left \lfloor{\frac{(28 + 3)}{2}} \right \rfloor = 15$ (the $\left \lfloor{x} \right \rfloor$ notation means round down.)
So your number will be 15.

If order doesn't matter (the numbers should be sorted increasingly)
Sort the numbers from smallest to largest, as shown:

$\{1,2,3,4,5,8,9,10,12,28\}$
... and continue with the algorithm presented if order did matter. (The differences, then the average of the numbers with the largest difference.)
In this case the number you need to bridge the largest gap between 12 and 28 is $\left \lfloor{\frac{(28 + 12)}{2}} \right \rfloor = 20$.

Why are the numbers different? The gap size depends on the difference between the two numbers adjacent to each other. Whether we sort or not changes the number placements, thus changing the gaps between terms.

A final thing worth mentioning. Sometimes you'll get two or more differences which are equally large, as in the case $\{1, 5, 9\}$. The gaps are equally large between the numbers, so it's up to you to decide whether you want to insert a number between each difference or leave it alone, or possibly only insert a number in one gap.