#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# total beginner: comparing array to mouseposition

edited February 2017

absolute beginner here :) hope i'm at the right place.

i have an array of x-coordinates – something like: float[] pos = {10,50,100,200,400}

i'd like to figure out if/when my mouse is within the range of two of these coordinates and output the according index. so let's say my mouse is within 0px and 10px, i'd like to return the index 0.. if it's within 10px and 50px, i'd wish for an index 1...

any hints on how to do that or where to read up on it? i'd be gracious.

Tagged:

• edited February 2017

******EDITED

The keyword break will force the exit in the for loop when the conditional is satisfied.

Kf

``````int[] xpos = {10, 50, 100, 200, 400};

void setup() {
size(400, 600);
}

void draw() {

int i;
for (i=0; i<xpos.length; i++) {
if (mouseX<xpos[i]) {
break;
}
}

println("MouseX "+mouseX+" at index " + i +" aka. less than "+xpos[i]+" pixs" );
}
``````
• edited February 2017 Answer ✓

Easy peasy-

``````int arrayCompare(float[] ar, float p){//return -1 if value is bigger than last value in array
for(int i = 0; i < ar.length; i++){
if(i == 0){
if(p < ar[0])return 0;
}else{
if(p < ar[i])return i;
}
}
return -1;
}
``````
• (It assumes that the values in the array are arranged in ascending order, and all values are preferably positive)

• kfrajer's fails for 5, should return 0, returns nothing

lord's fails to compile. can't return true when it's defined to return an int.

did either of you test your code? 8)

• can't return true when it's defined to return an int.

should return i, then it's all ok.

• edited February 2017

(Oops, didn't notice the problem :\"> And no, I don't test 90% of my code bcz I'm on tablet :D )

• Thanks @koogs, fixed.

• thanks so much guys.. really appreciated, being such an novice i am.. i think i'm going lord's code (as my approach was similar to kfrajer and i wanna learn!)

how ever – what do i do if my array isn't sorted (which it actually wont be)?

• Simple, sort the array. Use the function - `sort()`

• thanks buddy! :) so ... would i create a new array that is sorted? because i need the original array the way it was created.

• Yes of course. If original shouldn't be modified, new one is required.

• edited February 2017

... I need the original array the way it was created.

https://Processing.org/reference/sort_.html

Sorts an array of numbers from smallest to largest, or puts an array of words in alphabetical order. The original array is not modified; a re-ordered array is returned.

• oh this is really great! a first approach in these forums and immediate satisfaction :) thanks lord & co – be warned: i shall return in no time!

• (@GoToLoop just to inform you, I did lik to the reference myself)

• edited February 2017

I did lik to the reference myself

I was pretty aware of that. Just posted an excerpt of its reference b/c @benniii hadn't still realized that Processing's sort() would clone the passed array before sorting it out. >-)

• edited February 2017

P.S.: For in place (in loco / in situ) sorting, w/o any cloning, go w/ java.util.Arrays.sort() instead: :-bd
http://docs.Oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-int:A-

• i'm back! :)

this:

```for(int i = 0; i < ar.length; i++){ if(i == 0){ if(p < ar[0])return 0; }else{ if(p < ar[i])return i; } }```

shouldn't it be:

```for(int i = 0; i < ar.length; i++){ if(i == 0){ if(p < ar[0]) {return 0}; }else{ if(p < ar[i]) {return i}; } }```

(with curlies around the return)?

or am i right in the assumption, i'm lacking absolute basics?

• (and how do i post code correctly??? :o )

• edited February 2017

If it's 1 statement only, curly braces `{}` are optional. :ar!

• edited February 2017

A more compact version of @Lord_of_the_Galaxy's: \$-)

``````/** return -1 if value is bigger than last value in array */
@ SafeVarargs static final int arrayCompare(final int p, final int... arr) {
if (p < arr[0])  return 0;
for (int i = 0; ++i < arr.length; )  if (p < arr[i])  return i;
return -1;
}
``````
• edited February 2017
``````/** return -1 if value is bigger than last value in array */
@ SafeVarargs static final int arrayCompare(final float p, final float... arr) {
if (p < arr[0])  return 0;
for (int i = 1; i < arr.length; i++)  if (p < arr[i])  return i;
return -1;
}
``````
• And this is even more optimised.

• (@GoToLoop Say, does using float cause any problems?)

• I was still tweaking my compact version... 8-|
My final version transfers `++i` to the conditional part of the loop: :P
`for (int i = 0; ++i < arr.length; )`

• @koogs post updated. It failed in the trivial case which is now corrected.

Kf

• Perhaps this may work- `for(int i = 0; ++i < arr.length; if(p < arr[i])return i));`. @GoToLoop will it? If so, it's as compact as possible.

• We can only have expressions inside the `for ( ; ; )` loop.
`if ()` isn't an expression. I guess the name is a command or something like that. ^#(^

• thanks guys, really incredible.. i'll do some testing. thanks for all the help!

• edited February 2017

damn, i'm back... grr... i feel really stupid. for starters, i'm trying lord's first function as i can retrace it a little bit.

``````int arrayCompare(float[] ar, float p){
for(int i = 0; i < ar.length; i++){
if(i == 0){
if(p < ar[0])return 0;
}else{
if(p < ar[i])return i;
}
}
return -1;
}
``````

i've placed it in a void, but voids apparently cant return values. how or where do i utilise it, assuming i will pass it the arguments describing my array with positions and my current mouseposition.

i'm aware that this is due to a lack of very basic understanding. sorry, you just really got me going now with this particular problem.

• edited February 2017

"I've placed it in a void"

This doesn't make sense, it's like saying "I've placed my Starbucks in a coffee." A Starbucks may return a coffee; a function may return things such as an int, or a float, or void (nothing). A function that returns nothing... returns nothing.

If a function begins "int" then it must have a return statement that returns an int.

• ahh i got it to work!

anyways, i wasn't even aware that int is a function.. i placed all things that should "do something" in voids (void somename()) and called them in the void draw() function.

ah, there's loads of stuff to learn.

• `int` isn't a function, it's a primitive datatype. It's also a Java keyword:

• edited February 2017

@benjii -- sorry, I think my metaphor was unclear. A function returns a thing -- like an int. A shop gives you a product -- like a cup of coffee. If you say "coffee shop" you mean a shop that gives a cup of coffee. If you say "int myFunction()" you mean a function that gives (returns) an int. That doesn't mean an int is a function -- and it doesn't mean a cup of coffee is a shop!

Again, "I placed thing in voids" does not make sense. That's like saying "I put shops inside cups of coffee."

• If your original array is unsorted then I don't think there is always a unique solution. Suppose your array is [10, 100, 50] with mouseX = 70. 70 is between 10 and 100. It's also between 100 and 50 so no unique solution

• @andygray That's why I suggested using the sort() function to sort the array. Then there will be a unique solution - unless two values are equal. The problems will occur.

• @GoToLoop collision detection? How's that related?

• More like the distance from an x coordinate within the coords array. ^#(^

• Okaaay..... I still don't get it.

• @Lord_of_the_Galaxy Beniii will end up with the index of his sorted array, not the original. It might help if Beniii could describe what this index is needed for

• not perfect, but a small idea for @benniii

we don't sort the initial array. We just leave it as it is.

Additionally we make a 2nd array `xposMouse` of same length that holds the normal screen position to match the mouse.

Now, we can just use the mouse pos to figure out in which slot of xposMouse we are and look up the number in the same slot in the unsorted array xpos

I am not sure what your goal is, but that's my idea

Best, Chrisir ;-)

``````int[] xpos = { 200, 50, 100, 200, 10, 400};

int[] xposMouse = new int[xpos.length];

void setup() {
size(400, 600);
}

void draw() {

int dist = width/xpos.length;

for (int i=0; i<xpos.length; i++) {
line(i*dist, 0, i*dist, 10);
xposMouse[i]=i*dist;
text(xpos[i], i*dist, 18);
}

int i;
for (i=0; i<xposMouse.length; i++) {
if (mouseX<xposMouse[i]) {
break;
}
}

if (i>=xpos.length)
i=xpos.length-1;

println("MouseX "+mouseX+" at index " + i +" giving you "+xpos[i]+" VALUE " );
}
``````
• @andygray An index in an unsorted array doesn't even make sense. See this array:
`100, 10, 50, 30, 70`. What index would you want for a value of, say, 40?
I think now I understand what @GoToLoop was trying to say- return the index of the value closest to the mouseX.