sorting of different color balls in minimum passes - algorithm

There are 10,000 balls and may be 500 different colors of ball
Example: There are:
4 - red balls
5900 - Blue balls
3700 - Green balls
396 - mintcream balls
Or there may be 10,000 red balls.
Or all balls are has same range, i.e. 500 red, 500 blue, etc.
We don’t know the range of any ball and number of color balls, but the minimum is 1 color and maximum is 500 different colors, and we have auxiliary array of size 500. how to arrange all same color ball together in minimum passes over balls and in minimum swap? is it possible to do in less than two passes ??

You need one pass (in pseudocode with OO syntax):
for (ball in balls) {
array[array.getIndexByName(ball.color)].add(ball);
}
where getIndexByName returns the slot assigned to a certain color.
If no slot has been assigned to the color in question, a new slot is assigned.
Assuming a naive implementation of getIndexByName the complexity is O(number of balls * number of colors).

First you go over all the balls and count per color the number of occurrences, you can do this using the auxiliary array you have.
Then you know how much space you must reserve per color. So when you go over all balls again you have a pointer to the location they should be going to in the output array since you know how many balls of every color you expect. Don't forget to update the counter of the color after you processed a ball.
By swapping the balls in the input array with the balls at the position they should go to you can get an algorithm of O(n) swaps.
An example:
The first part is simple, say you have 10 balls, 3 red, 4 blue, 2 green and 1 yellow ball.
The second part takes your input array: red,blue,green,yellow
For simplicity say we order them in the order:
You start with the first ball. If it has color blue we have to swap it with the ball at location 4 in the array (since all balls before that have to be red. The new location we have to swap a blue ball to has to be updated in the auxilary array and should be 5 now. Then if the ball we swapped with is green we swap it with the ball at location 7. Now if the ball is red after the swap we can continue with the next ball. You can of course skip the balls you have swapped before. It is important to note that you swap a ball at most two times using this technique and you swap them to a known location, hence you don't need an additional pass.

you could do it in less than two passes, but it would be more complicated.
Here is how i would do it-
pass #1- determine number of balls for each color and number of colors
pass #2- for every 3 colors, (example 1, 4, 5, balls respectively=put a marker in 10th spot) and use the dutch color flag problem here

Related

Three type of Balls from Bag

I have a problem which sounds like this:
We have a bag with balls in. There are R red balls, B blue balls and G green balls.
I need to find the minimum number of extractions from the bag such that i am sure that i will have at least K balls of same colour.
Anyone can help with any idea? Or tips, etc?
If K>max(R,G,B) then the problem has no solution. So let's assume K <= max(R,G,B).
If you don't have any control over which ball gets extracted, you'll need at most (i.e. this is a lower bound) min(R, (K-1))+min(G, (K-1))+min(B, (K-1))+1 extractions for obvious reasons: extract K-1 red balls (or all red balls if R<K), then extract K-1 green balls (or all green balls if G<K), and finally extract K-1 blue balls (or all blue balls if B<K). Now there is at least one ball remaining---because max(R,G,B)>=K by assumption---and when we extract it we have K balls of the same color. (This is clearly the worst case.)
You obviously need at least K extractions (this is the best case).
Since you tagged the question with probability, maybe you can only extract a ball chosen uniformly at random. In that case we can talk of the expected number of extractions needed before we end up with K balls of the same color. This is an interesting question.
You need to make sure the upper bond working... When I test the upper bond, it blows off the int range (I using java)

Algorithm to find a frontline between enemy and friendly bases?

Please look at this picture first:
As you can see, blue and red both have a line showing the frontline bases.
Let's assume two players start playing against eachother.
One placing a base at the far left, the other at the far right.
The players continue by expanding and gaining territory.
After a while, the two sides will meet and battle will start.
Question is, in a randomly ordered list of base positions how would one find the two lines that are drawn in the picture?
You could get the distance between enemy bases, where the distance is shorter is the frontline.
Example:
0 1 2 3 4 5 6
0 aa A B bbb
1 aA B bb
2 A B b
3 aA B b
4 aaaA Bb
5 aaaA B
6 aaaA B
If you substract the X positions of the enemy bases in the same row, the ones with the less distance between them are the front lines, B.x - A.x will give you a smaller number that b.x - a.x. Then you can check which ones were the ones that gave you the smaller distance for each row.
Unless I'm getting your question wrong.
area
many games do not draw territory border by polylines
instead they draw a disc with constant radius (or dependent on base strength) at every base position
if the radius is set big enough then these discs/circles will overlap
and create seamless area of single color representing controlled territory
it is easy but inaccurate
perimeter polyline
first cluster all bases and create lists of bases close together
this can be done by grouping bases with distance <= treshold
process each group
find the outer most bases of group
something like perimeter points
this may help with it
also it contains inverse problem of yours which can solve the whole thing more here
now find the perimeter closed loop of area
the algorithm for that is also in the link above
when done then use this list of points as BEZIER cubics poly-curve control points
if borderline too close to the bases then enlarge the points
first compute avg point ap of group
then any point p is computed p=((p-ap)*scale)+ap
it is not exact but for your purposes it is enough
if you want something better then
p=p-ap
l=|p|
p=ap+(p*(l+dl)/l)
where dl is the step at which your border is enlarged
and if you want the accurate thing then you have to compute polygon enlargement
which is not easy task
handle edge cases
for singular base groups draw circle around
this approach has problem in close proximity of bases
one solution is not to count bases too close to any enemy base
per pixel borders
you can process the map image by pixels
something like this: (beware this is not tested)
per each pixel
compute the min distance to any player bases
remember two closest distances of different players
distance0 is closest
distance1 is second closest (but base owns another player)
select territory ownership
the player which has closest base own this
if the distance0 > treshold then this area is uncontrolled
in that case stop processing this pixel
if ((distance0 >= d-w)&&(distance0 <= d+w)&&(distance1>d+w+s)) then set pixel color to border polyline color
d is border line distance from base
w is half-size of borderline thickness
s is min distance between close front lines
edge case
previous step ignore border points that are closer to bases (close enemy bases)
to add them just add
if ((distance0<d)&&(|distance0-distance1|<=s+w)&&(|distance0-distance1|>=s-w)) then set pixel color to player ownership
also this will fail if any two opposing bases are closer then s-w
[Notes]
I think the best way is the per pixel
it is most close to the solution you want
the render can be a bit slower but you need to change it only if any base is conquered

Maximization algorithm for ball preferences

I'm trying to devise the most efficient algorithm for a problem, but I'm having some difficulty. If someone could lend a hand, either by proposing an algorithm or classifying the problem so I can do some further research, I would be very appreciative.
The problem is as follows:
There are n (an integer) number of distinct red balls, each of which has its own number, and m number of distinct green balls, each of which has its own corresponding number as well. For example, if n = 3, then there are three red balls named Red Ball 1, Red Ball 2 and Red Ball 3.
There are also two boxes in which the balls can be placed.
Before the balls are placed in the boxes however, x number of people make predictions as to which balls will be placed in which box (either box 1 or box 2). Each person gets one prediction and for each prediction they can guess one ball to be in each box. The only condition is that the ball they guess in box 1 cannot be the same color as the ball they guess to be in box 2. An example prediction would be: "I think that Red Ball 2 will be in box 1 and Green Ball 3 will be in box 2"
After everyone has made their predictions, the balls will be placed in the boxes the maximize the number of predictions that are correct.
The code I must write will be prompted with n, m, and x as well as the predictions and then be asked to return the maximum number of predictions that are correct.
Once again, I am looking for either algorithmic help or help to identify the type of problem this is. I currently have a recursive algorithm running on (n^2), but I need something a little more efficient.
Thanks for your help! Cheers, Mates!

Hungarian Rings Puzzle

I'm having a hard time finding an admissible heuristic for the Hungarian Rings puzzle. I'm planing on using IDA* algorithm to solve and am writing the program in Visual Basic. All I am lacking is how to implement the actual solving of the puzzle. I've implemented both the left and right rings into their own arrays and have functions that rotate each ring clockwise and counterclockwise. I'm not asking for code, just somewhere to get started is all.
Here is the 2 ring arrays:
Dim leftRing(19) As Integer
' leftRing(16) is bottom intersection and leftRing(19) is top intersection
Dim rightRing(19) As Integer
' rightRing(4) is top intersection and rightRing(19) is bottom intersection
In the arrays, I store the following as the values for each color:
Red value = 1 Yellow = 2 Blue = 3 and Black = 4
I suggest counting "errors" in each ring separately - how many balls need to be replaced to make the ring solved (1 9-color, 1 10-color, one lone ball from a 9-color). At most two balls can be fixed using a rotation, then another rotation is needed to fix another two. Compute the distance of each ring individually = 2n-1 where n is half the amount of bad positions and take the larger of them. You can iterate over all twenty positions when looking for one that has the least amount of errors, but I suppose there's a better way to compute this metric (apart from simple pruning).
Update:
The discussion with Gareth Reed points to the following heuristic:
For each ring separately, count:
the number of color changes. The target amount is three color changes per ring, and at most four color changes may be eliminated at a time. Credits go to Gareth for this metric.
the count of different colors, neglecting their position. There should be: 10 balls of one 10-color, 9 balls of one 9-color and one ball of the other 9-color. At most 2 colors can be changed at a time.
The second heuristic can be split into three parts:
there should be 10 10-balls and 10 9-balls. Balls over ten need to be replaced.
there should be only one color of 10-balls. Balls of the minor color need to be replaced.
there should be only one ball of a 9-color. Other balls of the color need to be replaced. If all are the same color, and 9-color is not deficient, one additional ball need to be replaced.
Take the larger of both estimates. Note that you will need to alternate the rings, so 2n-1 moves are actually needed for n replacements. If both estimates are equal, or the larger one is for the latest moved ring, add an additional one. One of the rings will not be improved by the first move.
Prune all moves that rotate the same ring twice (assuming a move metric that allows large rotations). These have already been explored.
This should avoid all large local minima.

Is this problem NP-hard?

I'm trying to come up with a reasonable algorithm for this problem:
Let's say you have a bunch of balls. Each ball has at least one color, but can also be multicolored. Each ball also has a number on it. There are also a bunch of boxes which are each only one color. The goal is to maximize the sum of the numbers on the balls in the boxes, and the only rules are:
in order to place a ball in a box, it
has to at least have the box's color
on it
you can only put one ball in each
box.
For example, you can put a blue and green ball into a blue box or a green box, but not into a red box.
I've come up with a few optimizations that help a lot in terms of running time. For example, you can sort the balls in descending order of point value. Then as you go from highest number to lowest, if the ball only has one color, and there are no other higher-point balls that contain that color, you can put it in that box (and thus remove that box and that ball from the remaining combinations).
I'm just curious is there's some kind of dynamic algorithm for this type of problem, or if it's just the traveling salesman problem in disguise. Would it help if I knew there were at most X colors? Any help is greatly appreciated. Thanks!
Edit - here's a simple example:
Balls:
1 red ball - 5 points
1 blue ball - 3 points
1 green/red ball - 2 points
1 green/blue ball - 4 points
1 red/blue ball - 1 point
Boxes:
1 red
1 blue
1 green
Optimal Solution:
red ball in red box
blue ball in blue box
green/blue ball in green box
Total value: 12 points (5 + 3 + 4)
This is a special case of the maximum weight matching problem on a weighted bipartite graph. Construct a graph whose left vertices correspond to balls, whose right vertices correspond to boxes and with the edge joining a ball and a box having weight V where V is the number on the ball if the ball can be placed in the box, and 0 otherwise. Add extra boxes or balls joined to the other side with edges of weight zero until you have the same number of vertices on each side. The assignment you're looking for is determined by the set of edges of nonzero weight in the maximum (total) weight matching in the resulting graph.
The assignment algorithm can be solved in O(n^3) time, where n is here the maximum of the number of balls or boxes, using the Hungarian algorithm. (BTW, I should make the disclaimer that I only mention the Hungarian algorithm because it is the theoretical result I happen to be familiar with and it presumably answers the question in the title of whether the original problem is NP-hard. I have no idea whether it is the best algorithm to use in practice.)
Have you tried a greedy alg?
Sort by points/value and place in box if possible.
If there are any exceptions im missing id like to see them.

Resources