我编写了这段代码:
$a = array('X', 'X', 'X', 'O', 'O', 'O');
$rk = array_rand($a, 3);
$l = $a[$rk[0]].$a[$rk[1]].$a[$rk[2]];
if($l == 'OOO' || $l == 'XXX'){
echo $l . 'Winner';
} else {
echo = $l . 'Loser';
}
在数组中你会注意到相同值的倍数,因为三个是随机选择的,如果匹配你就赢了(它是一个基本游戏)。
我的问题是如何编码而不必在数组中添加相同值的倍数?
更新 回答Yanick Rochon问题
因为它的阵列是:
$a = array('X', 'X', 'X', 'O', 'O', 'O');
有可能以某种方式将其作为
$a = array('X', 'O');
仍然有3个值返回?
答案 0 :(得分:1)
使用基本兰特:
<?php
$a = array('X', 'O', 'R');
$size = count($a)-1;
$l = $a[rand(0,$size)].$a[rand(0,$size)].$a[rand(0,$size)];
if($l == 'OOO' || $l == 'XXX'){
echo $l . ' Winner';
} else {
echo $l . ' Loser';
}
?>
XXX或OOO或RRR获胜的版本:
<?php
$a = array('X', 'O', 'R');
$size = count($a)-1;
$l = $a[rand(0,$size)].$a[rand(0,$size)].$a[rand(0,$size)];
if($l === 'OOO' || $l === 'XXX' || $l === 'RRR'){
echo $l . ' Winner';
} else {
echo $l . ' Loser';
}
?>
答案 1 :(得分:1)
为了在程序上创建整个程序,这里是一个代码片段。您可以对其进行测试here。
function randomArray($multiple, $length = 4) {
if ($length <= $multiple) {
throw new Exception('Length must be greater than multiple');
}
// define possible characters
$possible = 'ABCEFGHIJKLMNPQRSTUVWXYZ';
$value = str_repeat(substr($possible, mt_rand(0, strlen($possible)-1), 1), $multiple);
$i = strlen($value);
// add random characters to $value until $length is reached
while ($i < $length) {
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
// we don't want this character if it's already in the string
if (!strstr($value, $char)) {
$value .= $char;
$i++;
}
}
// done!
$value = str_split($value);
shuffle($value);
return $value;
}
// return a random selection from the given array
// if $allowRepick is true, then the same array value may be picked multiple times
function arrayPick($arr, $count, $allowRepick = false) {
$value = array();
if ($allowRepick) {
for ($i = 0; $i < $count; ++$i) {
array_push($value, $arr[mt_rand(0, count($arr) - 1)]);
}
} else {
shuffle($arr);
$value = array_slice($arr, 0, $count);
}
return $value;
}
// generate an array with 4 values, from which 3 are the same
$values = randomArray(3, 4);
// pick any 3 distinct values from the array
$choices = arrayPick($values, 3, false);
// convert to strings
$valuesStr = implode('', $values);
$choicesStr = implode('', $choices);
echo 'Value : ' . $valuesStr . "\n";
//echo 'Choice : ' . $choicesStr . "\n";
if (preg_match('/^(.)\1*$/', $choicesStr)) {
echo $choicesStr . ' : Winner!';
} else {
echo $choicesStr . ' : Loser!';
}
注意:如果randomArray
,函数$length - $multiple > count($possible)
将失败。例如,此调用randomArray(1, 27)
将失败,脚本将无限期运行。你知道吗:)
答案 2 :(得分:0)
你的意思是这样的吗?
$letter = false;
$winner = true;
foreach($rk as $key)
{
if($letter === false) $letter = $a[$key];
elseif($a[$key] != $letter) $winner = false;
}
if($winner) echo 'Winner';
else echo 'Loser';
答案 3 :(得分:0)
$num = 3;
$unique_vals = array('X','O');
$a = array();
foreach ($unique_vals as $val)
{
for ($i = 0; $i < $num; $i++)
{
$a[] = $val;
}
}