jeudi 5 février 2015

How to fetch a not so random value from an array?

The idea


At work, we've got a task no one wants to do. So I tried making a script that randomly selects a person from an array and displays their name. However, when we have an intern, we want him/her to turn up more often than the others.


Keep in mind this is just some fooling around with code.


Code



<?php
if (!isset($_COOKIE['names'])) {
// Prepare initial array
$names = array(
'John Doe' => 10,
'Jane Doe' => 10,
'Mike Doe' => 10,
'Gina Doe' => 10,
'Anne Doe' => 10,
'George Doe' => 10,
'Jack Doe' => 10,
);

// Create cookie
setcookie('names', serialize($names), time()+28800);
}

$names = unserialize($_COOKIE['names']);

$randomArray = array();
foreach ($names as $name => $probability) {
if ($probability > 1) {
foreach (range(1, $probability) as $v) {
$randomArray[] = $name;
}
} else {
$names[$name] = 10;
}
}

$selected = $randomArray[array_rand($randomArray)];
if (array_key_exists($selected, $names)) {
if ($names[$selected] > 1) {
$names[$selected]--;
}
setcookie('names', serialize($names), time()+28800);
echo $selected;
}


By looking at this code, I guess you'll get the general idea. By making the probability higher, people's name will come up more often.


The problem


When the probability comes to 1, I set it back to 10. But somehow this feels wrong. I am not a calculus miracle but my head can figure out that this just isn't right. Also, the piece of code I wrote doesn't feel efficient at all. In my opinion there are too many loops.


What I wold like to ask is for you to take a look at my code and tell me what it is I'm doing wrong and what I can do to improve it. Suggestions etc. are also welcome.





Aucun commentaire:

Enregistrer un commentaire