Random Values in Array Problem - HELP!
Posted: Fri Sep 15, 2006 11:28 am
I am trying to take the values in an array and randomly assign them to one another. An example of what I am talking about would be if you wanted to have a list of students who will be randomly paired as presenter and evaluator.
The array holds the names like:
0 = Bobby
1 = Tim
2 = Sally
3 = Fred
I want the array to randomly pair the students, something like this:
Bobby with Tim
Tim with Sally
Sally with Fred
Fred with Bobby
So that each student is, in one pairing the presenter, and in another pairing the evaluator. They do not necessarily have to be different for each match (ie. I could have Bobby with Tim and Tim with Bobby) but I do want to avoid Bobby with Bobby, and also need to avoid doubling up presenters or evaluators like: Bobby with Sally and Tim with Sally.
I wrote some code that assigns the values into two identical arrays. Then it uses the shuffle($array) function on one to randomize the order. Then I put those through a loop that tests to verify that array1[0] != array2[0] to prevent someone from being matched to themselves, if they are, it resets the loop, performs the shuffle function again, and starts testing again.
This works perfectly when working with 4 or 5 students, but times out with only 10. I know there has got to be some built in function or something I am missing. I need this to be able to work for large classes of 25 to 50.
Any ideas would be much appreciated.
Travis
The array holds the names like:
0 = Bobby
1 = Tim
2 = Sally
3 = Fred
I want the array to randomly pair the students, something like this:
Bobby with Tim
Tim with Sally
Sally with Fred
Fred with Bobby
So that each student is, in one pairing the presenter, and in another pairing the evaluator. They do not necessarily have to be different for each match (ie. I could have Bobby with Tim and Tim with Bobby) but I do want to avoid Bobby with Bobby, and also need to avoid doubling up presenters or evaluators like: Bobby with Sally and Tim with Sally.
I wrote some code that assigns the values into two identical arrays. Then it uses the shuffle($array) function on one to randomize the order. Then I put those through a loop that tests to verify that array1[0] != array2[0] to prevent someone from being matched to themselves, if they are, it resets the loop, performs the shuffle function again, and starts testing again.
This works perfectly when working with 4 or 5 students, but times out with only 10. I know there has got to be some built in function or something I am missing. I need this to be able to work for large classes of 25 to 50.
Any ideas would be much appreciated.
Travis