I have a NSMutableArray that has 5 values initially set to zero. It contains the x-coordinate of elements on the screen and is updated every 1/60th of a second. The position of each item is constantly changing. There is a maximum of 5 items on the screen and a minimum of 1 at any time.
Each item in the array will be in the range 0 – 480 (height of iphone screen). An example array at a given time would be:
{123,450,0,0,0}
Which might then change to:
{150,320,90,0,0}
I need a quick way to find a position that is not near any position in the array. This can be a position that is not within a set range around each value (for example the value is not within 50 of any items in the array) or the position with the most distance either side of it.
Obviously if finding a position within a certain range is not possible, the best solution should be picked.
It needs to be quick as a new item is being added to the screen so any delay in picking a new position will slow down the game ticker – so a while loop is not preferable.
Hopefully theres a simple mathematical method in objective-c that can sort this. I really am stuck as to how I should achieve this. Any help is MUCH appreciated.
Let me rephrase this question a bit. You have points
p1,p2,p3,p4,p5such thatYou want to find a point
xsuch thatthat maximizes the function
If this is your aim (and it isn’t clear to me that it is or should be), then you can solve this problem by checking which of the following potential
xvalues maximizes the distance:this assumes
0 <= p1 <= p2 <= p3 <= p4 <= p5 <= 480. Whichever of the difference terms is larger is the answer you should select.For example, for
the answer is
123 + (450-123)/2.For
the answer is
150 + (320-150)/2To code this in Objective-C, you need to have a function that returns the index of the maximum entry of an array. Take the input to be the
p1,p2,...,p5. Sort these into increasing order, append0on the left and480on the right. Then make a new array of length one less that gives successive differences, e.g.{p1-p0, p2-p1, ..., p6-p5}wherep0 = 0andp6 = 480. Finally, get the index of the maximum of this new array, call iti, and return the optimal positionp_i + (p(i+1)-p_i)/2.Example:
input:
{150,320,90,0,0}rearrange to
{0 , 0 , 0 , 90 , 150 , 320 , 480}difference array
{0 , 0 , 90 , 60 , 170 , 160}maximum at index
4answer is
150 + (320-150)/2