PHP implementation Math problem: combination

Source: Internet
Author: User

Demand:

There is an array [' A ', ' B ', ' C ', ' CD ']

You need to remove any m non-repeating elements from the array, listing all the possibilities (and not requiring duplicates such as [' A ', ' B ', ' C ') and [' A ', ' C ', ' B ']).

You can use the recursive return to complete:

<?phpfunction getcombinationtostring ($arr, $m) {if ($m = = 1) {   return $arr;} $result = []; $tmpArr = $arr; unset ($tmpArr [0]); for ($i = 0; $i < count ($arr); $i + +) {$s = $arr [$i]; $ret = Getcombinationt Ostring (Array_values ($TMPARR), ($m-1), $result), foreach ($ret as $row) {$val = $s. ‘,‘ . $row, $val = Explode (', ', $val), sort ($val), $val = Implode (', ', $val), if (! In_array ($s, explode (', ', $row)) && In_ Array ($val, $result)) {$result [] = $val;}}}     return $result;} $arr = [' A ', ' B ', ' C ', ' CD ']; $t = getcombinationtostring ($arr, 3); Echo ' <pre> ';p rint_r ($t);

If you allow repeating combinations, you can annotate the conditions of the line:17.

Output:

Array (    [0] = A,b,c    [1] = A,B,CD    [2] = = A,C,CD    [3] = = B,C,CD)

  

PHP implementation Math problem: combination

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.