Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the minimum distance in a table

I have a table of dimension m * n as given below

2    6    9    13
1    4    12   21
10   14   16   -1

Few constraints about this table:

  1. Elements in each row is sorted in increasing order (natural ordering).
  2. A -1 means the cell is of no significance for the purpose of calculatio, i.e. no element exists there.
  3. No element can appear in a row after a -1.
  4. All the cells can have either a positive number between 0 and N or a -1.
  5. No two cells have the same positive numbe, i.e. a -1 can appear multiple times but no other number can.

Question: I would like to find a set S of n numbers from the table where the set must contain only one number from each row and the max(S) - min(S) is as small as possible.

For e.g. the above table gives me S = 12,13,14.

I would really appreciate if this can be solved. My solution is complicated and it takes O(m^n) and this is too much. I want an optimal solution.

like image 705
dharam Avatar asked Jun 07 '12 11:06

dharam


People also ask

What is the formula for minimum distance?

The shortest distance between two points is a straight line. This distance can be calculated by using the distance formula. The distance between two points ( x 1 , y 1 ) and ( x 2 , y 2 ) can be defined as d = ( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 .

How do you find the minimum distance of an array?

Suppose we have one unsorted array A, and two numbers x and y. We have to find the minimum distance between x and y in A. The array can also contain duplicate elements. So if the array is A = [2, 5, 3, 5, 4, 4, 2, 3], x = 3 and y = 2, then the minimum distance between 3 and 2 is just 1.

What is the minimum distance?

Minimum distance estimation, a statistical method for fitting a model to data. Closest pair of points problem, the algorithmic problem of finding two points that have the minimum distance among a larger set of points. Euclidean distance, the minimum length of any curve between two points in the plane.


1 Answers

Here is a brute force O((m*n)^2 * nlog(m)) algorithm that I can prove works:

min <- INFINITY
For each 2 numbers in different rows, let them be a,b
   for each other row: 
        check if there is a number between a and b
    if there is a matching number in every other row:
        min <- min{min,|a-b|}

Explanation:
Checking if there is a number between a and b can be done using binary search, and is O(logm)
There are O((n*m)^2) different possibilities for a,b.

The idea is to exhaustively check the pair which creates the maximal difference, and check if it gives a "feasible" solution(all other elements in this solution are in range [a,b]), and get the pair that minimizes the difference between all "feasible" solutions .


EDIT: removed the 2nd solution I proposed, which was greedy and wrong.

like image 69
amit Avatar answered Oct 08 '22 22:10

amit