Home > Backend Development > PHP Tutorial > 一个强悍的算24点游戏的PHP程序

一个强悍的算24点游戏的PHP程序

WBOY
Release: 2016-06-23 13:59:28
Original
1142 people have browsed it

算24点游戏大家都玩过吧,那么怎么用程序来计算4个数的随意运算组合得到的结果是24呢?比如,5,5,5,1这四个数,如何凑才能得到结果为24?下面介绍一个很强悍的程序,可以将符合条件的所有组合列出来。

<?phpset_time_limit(0); $values = array(5, 5, 5, 1); $result = 24;$list = array();echo "<pre class="brush:php;toolbar:false">"; makeValue($values); print_r($list);function makeValue($values, $set=array()) { 	$words = array("+", "-", "*", "/"); 	if(sizeof($values)==1) 	{ 		$set[] = array_shift($values); 		return makeSpecial($set); 	} 		foreach($values as $key=>$value) 	{ 		$tmpValues = $values; 		unset($tmpValues[$key]); 		foreach($words as $word) 		{ 			makeValue($tmpValues, array_merge($set, array($value, $word))); 		} 	} } function makeSpecial($set) { 	$size = sizeof($set);	if($size<=3 || !in_array("/", $set) && !in_array("*", $set)) 	{ 		return makeResult($set); 	}	for($len=3; $len<$size-1; $len+=2) 	{ 		for($start=0; $start<$size-1; $start+=2) 		{ 			if(!($set[$start-1]=="*" || $set[$start-1]=="/" || $set[$start+$len]=="*" || $set[$start+$len]=="/")) 				continue; 			$subSet = array_slice($set, $start, $len); 			if(!in_array("+", $subSet) && !in_array("-", $subSet)) 				continue; 			$tmpSet = $set; 			array_splice($tmpSet, $start, $len-1); 			$tmpSet[$start] = "(".implode("", $subSet).")"; 			makeSpecial($tmpSet); 		} 	} }function makeResult($set) { 	global $result, $list; 	$str = implode("", $set); 	@eval("\$num=$str;"); 	if($num==$result && !in_array($str, $list)) 	$list[] = $str; }?>
Copy after login


程序运行结果为:

Array(    [0] => (5-1/5)*5    [1] => 5*(5-1/5))
Copy after login


 

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