我试图生成一个随机数组(如果我使用的话),其中包含可能的重复项,但不是相邻的,并且是从给定的数组中生成的。
例如:狮子,老虎,熊,猴子,大象
我想说出一句话,但有可能:“狮子和老虎、熊”、“熊和狮子、猴子和大象”、“猴子和大象”或“大象、狮子、大象和老虎”。
因此,它需要随机数量的可能性(不少于2,所以“熊和老虎”和任何其他产品的两个选项将是最小的,但也不超过7)。再说一次,我希望这些变量能够被复制,但不是在彼此旁边,这样就可以像“猴子和狮子、老虎和猴子”这样的东西。
由于我对PHP不太了解,这只是我尝试过的选项之一:
<?php
$input_array = array("lions", "tigers", "bears", "monkeys", "elephants");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>但是,由于它只生成两个元素的静态数量,并且不会重复,所以它不完全产生我想要做的事情。
任何帮助都会很感激,特别是如果它包含了在每个变量之间放置单词" and“的代码,并且还打印它们(而不是生成算法)-- PHP对我来说是非常新的,我不知道如何做到这一点而不搞砸。
发布于 2017-05-22 02:11:35
输入:
$input_array=["lions","tigers","bears","monkeys","elephants"];方法:
$count=mt_rand(2,7); // declare number of elements to extract
echo "Count = $count\n"; // display expected element count
$result=[];
while(sizeof($result)<$count){ // iterate until count is fulfilled
if(($new_val=$input_array[array_rand($input_array)])!=end($result)){
$result[]=$new_val; // add new value if different from previous value
}
}
echo implode(' and ',$result); // display values (joined by ' and ')一些潜在的产出:
Count = 6
monkeys and tigers and bears and tigers and monkeys and bears
Count = 2
elephants and lions
Count = 7
lions and bears and lions and elephants and monkeys and elephants and lions发布于 2017-05-21 23:19:36
所以你想做的是:
首先,您需要设置应该有多少个混叠元素。
$num = rand(2,7); // get random number between 2 and 7然后,您会多次迭代您的$input_array。还检查它中的最后一个条目是否等于新添加的项,在这种情况下,跳过迭代并再次滚动骰子。
$rand_keys = array();
while($num>0){ // repeat as long as $num is not zero
$rand_key = $input_array[rand(0,count($input_array)-1)]; // select random key from input_array
if(count($rand_keys)==0 || $rand_keys[count($rand_keys)-1]!=$rand_key){ // check if either this is the first element to add, or if the last element added is not equal to the new one
$rand_keys[] = $rand_key; // push new key into rand_keys
$num--;
}
}现在,您的$rand_keys数组应该包含所需的洗牌键。
PS:要将这个数组转换成字符串,如您的示例中所示,请使用implode(' and ',$rand_keys);
https://stackoverflow.com/questions/44102494
复制相似问题