PHP: Have a 1/2 chance to add or subtract 1 ..?

Forum
Last Post
Threads / Messages
Status
Not open for further replies.

Quillink

Member
Member
Joined
Dec 18, 2008
Messages
93
Points
0
Mysidian Dollar
7,188
I'm trying to create a code that will take an existing number (from a table) and have a one-in-two chance of adding or subtracting one from it.
This is what I have at the moment:

Code:
// $numnew = new number
// $curnum = current number
// $max = upper limit (5 in this case)

if (rand(1,2) == 1) {
$numnew = ($curnum + rand(-1,1));
}

if ($numnew == 0) {
$numnew = $max;
}

if ($numnew > $max) {
$numnew = 1;
}

I've been trying to figure how to do this all day. This code works... kind of.
It tends to favor staying at either 1 or 5. I heard that the rand() function isn't truly random, so I guess this is what they meant. Is there any workaround?
Also, the number will occasionally and unexplainably jump to 5 no matter what $curnum was. :(

If anyone can help make this work (or better, show me how to write it better from scratch) I'd very much appreciate it. :D


EDIT: Should I be posting these random php questions in the Webmaster Bat Cave, Brandon? I just figured since they apply to my adoptable site they belonged here. :S
 
The rand() function isn't truly random. I don't know why it isn't working, but I'll think about it and let you know if I come up with any ideas.
 
I could be wrong but I think the issue is here:

Code:
// $numnew = new number
// $curnum = current number
// $max = upper limit (5 in this case)

[b]if (rand(1,2)[/b] == 1) {
$numnew = ($curnum + rand(-1,1));
}

if ($numnew == 0) {
$numnew = $max;
}

if ($numnew > $max) {
$numnew = 1;
}

I think maybe setting it like this:

Code:
[b]if (rand(0,4)[/b] == 1) {

That might rectify the issue.
 
this thread is over a year old, the post date is January 2010. I believe (like most forums) that you aren't suppose to bump old threads.
 
Status
Not open for further replies.

Similar threads

Users who are viewing this thread

  • Forum Contains New Posts
  • Forum Contains No New Posts

Forum statistics

Threads
4,280
Messages
33,130
Members
1,603
Latest member
Monako
BETA

Latest Threads

Latest Posts

Top