We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi everyone!
I'm new to processing and coding in general for that matter. I assume this will be a fairly straight forward question for you coding pros.
I have a piece of code with a variable for the x direction of an object. Each time I start the program I would like for that number to be randomly selected to be either 1 or -1, nothing in between. Any idea on how I would do this?
Thanks in advance!
Answers
final int dir = random(1) > .5? 1 : -1;
@Infinitiive -- the example from @GoToLoop is what the Processing reference calls it the "conditional operator": https://processing.org/reference/conditional.html (in Java it is called the ternary operator).
It is written like this
So GoToLoop's example says:
@Chrisir's example writes out the same logic longhand (although note he used 0, not -1):
@jeremydouglass you put in a lot of effort to properly explain answers. GoToLoop prefers to give straight, unexplained answers which are more useful to advanced/intermediate programmers.
There are tradeoffs. If you answer briefly you can answer many questions instead of just a few -- and brief answers may also teach people to teach themselves. On the other hand, long / complete answers are often useful to both beginners and to future readers of the forum who have a similar problem -- that is, assuming that they find the old answer at all!
I provided good code where gotoloop provided code unreadable for a beginner....
I kind of didn't see you there, @Chrisir. Your answers are good too.
@GoToLoop, you, on the other hand, just don't answer questions for beginners. You're better off with really complex questions, which if explained properly will be way too long.
I can't agree -- @GoToLoop has contributed almost 10,000 responses on the forum so far, and isn't being paid to do this. I think pointing people in the right direction is better than not answering, and sometimes better than spelling it all out. Every approach is valuable. But let's not discuss this any more on Infinitiive's thread about a specific random number issue.
Of course, he has way more continuations that anyone else.
And we've been doing this many times before - discussing unrelated topics, so sorry all those who are concerned.
jeremydouglas has done a good job in explaining GoToLoop's minimalist answer and it has been accepted by the OP so this discussion is finished.
All the other posts have hijacked the discussion onto another subject altogether (not an uncommon occurence ;) ). kfrajer has stated a new discussion to cover this area.
This discussion is now closed.