The result of random operation on 4 numbers is 24_PHP tutorial

WBOY
Release: 2016-07-13 10:33:48
Original
1283 people have browsed it

Everyone has played the 24-point calculation game, so how do you use a program to calculate the random operation combination of 4 numbers to get the result of 24? For example, how can we combine the four numbers 5, 5, 5, and 1 to get the result 24? The following introduces a very powerful program that can list all combinations that meet the conditions.

<?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; 
}
?>
Copy after login

The result of running the program is:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752414.htmlTechArticleEveryone has played the 24-point game, so how do you use a program to calculate the random combination of 4 numbers? The result is 24? For example, how do you combine the four numbers 5, 5, 5, and 1 to get the result...
Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!