A powerful PHP program for computing 24-point games

Source: Internet
Author: User
The PHP program of a powerful 24-point game has been used for 24-point games. how can we use a program to calculate the random combination of 4 numbers to get the result of 24? For example, for the numbers 5, 5, 5, and 1, how can we get the result 24? The following describes a very powerful program that can list all the combinations that meet the conditions.

 "; 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; }?>


The program running result is:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.