Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of algorithm should i use?

Lets say I have four group

A [ 0, 4, 9]

B [ 2, 6, 11]

C [ 3, 8, 13]

D [ 7, 12 ]

Now I need one number from each group(i.e a new group) E [num of A,num of B, num of C, num of D], such that the difference between the maximum num in E and minimum num in E should be possible lowest.What type of problem is this ? which graph algorithm will be better to solve this kind of problem ? Thanks in advance.

P.S : I'm trying to solve this in java and sorry for the unspecified title.

Edit : Finally I've found what I'm actually looking for http://rcrezende.blogspot.in/2010/08/smallest-relevant-text-snippet-for.html

like image 699
user1624525 Avatar asked Aug 25 '12 17:08

user1624525


1 Answers

  1. Combine contents of every group into a single array. Each element of the array should be a pair of (number, group name).
  2. Sort this array by numbers.
  3. Advance two iterators, one after another. Move first iterator when elements of not every group are between these iterators. Move second iterator when there is an element of each group between these iterators. For details see this question.
  4. Minimum distance between iterators determine optimal resulting group (you only need to drop unneeded elements when there are several representatives of the same group there).

Other algorithm:

  1. Sort elements of each group (if not sorted already).
  2. Put a pair (number, group name) for smallest elements of each group into priority queue (min-heap, priority=number).
  3. Remove smallest element from the queue and replace it with the next element from the same group.
  4. Repeat step 3 until no more elements are left in some group. Calculate max(queue) - min(queue) for each iteration and if it is smaller than any previous value, update the best-so-far resulting group.
like image 59
Evgeny Kluev Avatar answered Oct 14 '22 20:10

Evgeny Kluev