Heim  >  Artikel  >  Backend-Entwicklung  >  4个数随意运算得到结果是24_PHP教程

4个数随意运算得到结果是24_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:33:481278Durchsuche

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

<?php
set_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; 
}
?>

程序运行结果为:

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752414.htmlTechArticle算24点游戏大家都玩过吧,那么怎么用程序来计算4个数的随意运算组合得到的结果是24呢?比如,5,5,5,1这四个数,如何凑才能得到结果为...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn