Random variable

Would this produce a 1/10 chance that action A is played?

float ran = random(10);
if (ran == 2)
{
  //action A
}
else if (ran != 2)
{
  //action B
}

random() returns a float datatype value: Processing.org/reference/random_.html

You need an int instead: :nerd_face:

final int choice = (int) random(10); // range 0 to 9

if (choice == 2) {
}
else {
}
1 Like

@GoToLoop

Would this also work?

int ran = (int)random(10);

Then I would be able to keep my previous code

if (ran == 2)
{
  //action A
}
else if (ran != 2)
{
  //action B
}

Yes, it would. You don’t need the if(ran != 2) bit though–just the else will do. This is because the else bit only runs if the if stuff before hasn’t run.

2 Likes

Yes, it would alright! :wink:

That Would work too, since it means the Same. But the second if (ran != 2) is obsolete. If it is 2, then the if (ran == 2) is true, Else the other one is. What you are doing is just adding a redundant condition. You can do it, But it’s better to not, performance wise. (Doesnā€˜t matter much now, But it stacks if you do it this way some Million Times.

1 Like

Keep in mind that one of the most basic ways to inspect whether in code is doing what you want is to test it.

So, you can answer your question by like this:

float ran = random(10);
println(ran);

7.702701

Or try printing a sample of outputs:

for (int i=0; i<10; i++) {
  println(random(10));
}

8.375377 5.7671003 0.24511933 1.3771093 6.604124 3.733101 2.9731035 2.9664493 5.653407 4.418477

…and, if you are unsure (maybe 7.7 == 7, or 8?), try it!

if (7.702701 == 7) {
  println("true");
}

if (7.702701 == 8) {
  println("true");
}

You will notice that warnings pop up in the PDE error box ā€œdead codeā€ – those will never be true.

3 Likes