Home > Backend Development > PHP Tutorial > 求教数字随机排列不重复的有关问题

求教数字随机排列不重复的有关问题

WBOY
Release: 2016-06-13 12:05:40
Original
1109 people have browsed it

求教数字随机排列不重复的问题
用1、2、3、4这四个数字随机排列,比如这样的:
2,1,3,2,4,3,1,3,4,1,3,4,2,3,4,1,3,4,2,4
共20位,相邻两个数不要重复,如3,3
该怎么写函数啊?
------解决方案--------------------
这个意思?

$a = array(1,2,3,4);<br />$b = array_merge($a, $a, $a, $a, $a);<br /><br />for($i=0; $i<1000; $i++) {<br />  shuffle($b);<br />  if(! preg_match('/(.)\1/', join('', $b))) printf("%d %s\n", $i, join('', $b));<br />}
Copy after login

------解决方案--------------------
<?php <br />	$a=array();<br />	function check(){<br />		global $a;<br />		$count=count($a)-1;<br />		if ($count >= 1 && $a[$count] == $a[$count-1]) {<br />			$a[$count]=mt_rand(1,4);<br />			check();<br />		}<br />	}<br />	for ($i=0; $i < 20; $i++) { <br />		$a[$i]=mt_rand(1,4);<br />		check();<br />		echo $a[$i]."<br />";<br />	}<br />?>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template