Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add an optional probability parameter to bool function #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Main
Random.int(1,3); // 1, 2, or 3
Random.float(0,5); // Any float between 0 and 5, inclusive
Random.bool(); // True or false
Random.bool(0.25); // True (with 25% of probability) or false
Random.string(5); // A 5 character string using letters A-Z, a-z and 0-9
Random.string(10, "aeiou"); // A 10 character string using only vowels
Random.date( Date.now, nextWeek ); // Generate a random date / time between now and next week
Expand All @@ -39,8 +40,8 @@ class Main

The methods it provides:

* `Random.bool()`
Will return a random `true` or `false` boolean value.
* `Random.bool(?probability:Float)`
Will return a random `true` or `false` boolean value. A optional probability can be set so that there's more or less chance to get `true`. Default probability is 0.5.
* `Random.int(from, to)`
Will generate a random integer between `from` and `to`, inclusive.
* `Random.float(from, to)`
Expand Down
8 changes: 5 additions & 3 deletions src/Random.hx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@

class Random
{
/** Return a random boolean value (true or false) */
public static inline function bool():Bool
/**
* Return a random boolean value (true or false) following a given probability (default: 0.5).
**/
public static inline function bool(probability:Float = 0.5):Bool
{
return Math.random() < 0.5;
return Math.random() < probability;
}

/** Return a random integer between 'from' and 'to', inclusive. */
Expand Down
11 changes: 11 additions & 0 deletions test/RandomTest.hx
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ class RandomTest
Assert.isTrue(r == true || r == false);
}
}

@Test
public function bool_probability():Void
{
for (i in 0...1000)
{
var r = Random.bool(0.25);
Assert.isTrue(Std.is(r, Bool));
Assert.isTrue(r == true || r == false);
}
}

@Test
public function string():Void
Expand Down