Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: random setPosition generater, using rand()  (Read 3731 times)

0 Members and 1 Guest are viewing this topic.

mapPhil

  • Newbie
  • *
  • Posts: 11
    • View Profile
random setPosition generater, using rand()
« on: June 06, 2011, 03:42:24 pm »
hi,

I was wondering how would you generate random positions between -100 to 0 as well as 800 to 900

for example this is the code I have
(*currentIter).SetPosition(rand()% -100+0, rand()% 600);

and it sets the sprites position between 100 and 0
and the code below sets the sprite position between 800 and 900

(*currentIter).SetPosition(rand()%800 + 900, rand()% 600);

The question is how can I randomly choose between the both of these lines of code?

i tried:

(*currentIter).SetPosition(rand()%(-100 + 0)||(800 + 900), rand()% 600);

but that didn't work.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
random setPosition generater, using rand()
« Reply #1 on: June 06, 2011, 03:50:51 pm »
Code: [Select]
if (rand() % 2)
    line 1
else
    line 2


By the way, your second line is wrong, it will generate numbers between 900 and 1700. The correct code would be:
Code: [Select]
rand() % 100 + 800

The general formula is
Code: [Select]
rand() % range + minimum

Therefore your first line should be
Code: [Select]
rand() % 100 - 100
Even if yours is correct in C++, it is incorrect mathematically (modulo can't give negative results) and thus could be confusing.
Laurent Gomila - SFML developer

mapPhil

  • Newbie
  • *
  • Posts: 11
    • View Profile
random setPosition generater, using rand()
« Reply #2 on: June 06, 2011, 03:58:18 pm »
That's great, didn't though that rand() % range + minimum was the formula I thought it was rand() % minimum + maximum.

Thanks for the quick reply