Search Algo

Hi all,

I am sure this question may turn out to be a trivial one for some, but not to me :). I will try to represent the problem in the following example:

There are a group of 'marbles', distributed over a line of length 100cm. The total number of the marbles, their distribution, distance from each other, ...are all unknown. Each marble occupies a 2cm space on the line. Marbles do not overlap, but can be next to each other.

1) I need to select a segment of that line, of constant length x (e.g. 30 cm), that covers as many as possible of the total number of marbles on that line. A marble is counted 'in' when all of it is in.

2) Another flavor to the problem: The center of the new segment should be at the center of one of the marbles on the line. Its also better for the marbles to be centrally located on the new segment. (For example, if there are three marbles, and all are covered by the new segment, its better for the center of the new segment to match the center of the middle marble. )

But just for the first question, I would appreciate if someone can point me to an algorithm, some pseudocode, or some freely available java implementation if any.

Thanks a lot.

[1227 byte] By [synapse68a] at [2007-10-2 9:51:12]
# 1

Hi,

What you do know is that you can have a maximum of 50 marbles (because they can't overlap).

Steps that I would take are:

1. Sort marbles based on position (simple bubble sort would do).

2. Scan the list for the largest count:

int[] marblelist; // sorted list of positions along the line

int marbles = marblelist.length;

int maxCount = 0, maxStart = 0;

for ( int start = 0; start < 70; start++ ) // 70 = 100 - 30cm

{

int tmpCount = 0;

for ( int count = 0; count < marbles; count++ )

{

int position = marblelist[count];

if ( position >= start && position < start + 30 ) tmpCount++;

else if ( position >= start + 30 ) break;

}

if ( tmpCount > maxCount )

{

maxCount = tmpCount;

maxStart = start;

}

}

// maxStart now has the start position on the line that contains the maximum mable count

// maxCount is the number within the 30cm range.

As for question number 2.

Instead of moving along the line, move through the marbles list - checking for -15cm and +15cm to each side of the current marble you're looking at.

HTH.

munyula at 2007-7-16 23:56:17 > top of Java-index,Other Topics,Algorithms...