I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
The following is part of the List
interface (which ArrayList implements):
E e = list.get(list.size() - 1);
E
is the element type. If the list is empty, get
throws an IndexOutOfBoundsException
. You can find the whole API documentation here.
You can use array_multisort
to order the array values by a second array of mt_rand
values:
$arr = array(1,2,3,4,5,6);
mt_srand('123');
$order = array_map(create_function('$val', 'return mt_rand();'), range(1, count($arr)));
array_multisort($order, $arr);
var_dump($arr);
Here $order
is an array of mt_rand
values of the same length as $arr
. array_multisort
sorts the values of $order
and orders the elements of $arr
according to the order of the values of $order
.
I think something like this will do what you want:
$fruits = array('apple' => '20', 'orange' => '40', 'pear' => '40');
$newFruits = array();
foreach ($fruits as $fruit=>$value)
{
$newFruits = array_merge($newFruits, array_fill(0, $value, $fruit));
}
$myFruit = $newFruits[array_rand($newFruits)];
This creates an array ($newFruits
), which is a numerically-indexed array with 100 elements. 20 of those elements are 'apple', 40 are 'orange', and 40 are 'pear'. Then we select a random index from that array. 20 times out of 100 you will get 'apple', 40 times out of 100 you will get 'orange', and 40 times out of 100 you will get 'pear'.
arc4random
can return negative numbers which would cause you problems since negative % positive = negative
A better approach would be to use arc4random_uniform
let randomIndex = arc4random_uniform(UInt32(cardArray.count))
EXC_BAD_INSTRUCTION seems like a bad exception to throw on a bounds error, but that does seem to be what you get.
You can also do just:
This is the way to do it when you have an associative array.