Assume that there are 4 numbers & nbsp; 1, 2, 3, 4 & nbsp; three numbers must be arranged, but they cannot be repeated. & Nbsp; example: 123,124,134,234. & Nbsp; wherein & nbsp; 123 calculates the digital combination algorithm
Assume there are 4 numbers.
1, 2, 3, 4
Three numbers must be arranged, but they cannot be repeated.
For example, combination: 123,124,134,234.
The combination of 123 and 213,312,321,132,231 is the same.
How to implement it? Cainiao, online, etc. thank you!
------ Solution --------------------
Above error
For ($ I = 1; $ I <= 5-2; $ I ++ ){
For ($ j = $ I + 1; $ j <= 5-1; $ j ++ ){
For ($ k = $ j + 1; $ k <= 5; $ k ++ ){
Echo "$ I, $ j, $ k
";
}
}
}
------ Solution --------------------
/**
* Function combination
* Function m is a combination of n.
* Parameters
* $ Ar array, raw data
* $ Num value, number of elements in each combination
**/
If (! Function_exists ('combination ')):
Function combination ($ ar, $ num ){
$ Control = range (0, $ num-1 );
$ K = false;
$ Total = count ($ ar );
While ($ control [0] <$ total-($ num-1 )){
$ T = array ();
For ($ I = 0; $ I <$ num; $ I ++) $ t [] = $ ar [$ control [$ I];
$ R [] = $ t;
For ($ I = $ num-1; $ I >=0; $ I --){
$ Control [$ I] ++;
For ($ j = $ I; $ j <$ num-1; $ j ++) $ control [$ j + 1] = $ control [$ j] + 1;
If ($ control [$ I] <$ total-($ num-$ i-1) break;
}
}
Return $ r;
}
Endif;
/** Example **/
Print_r (combination (array (1, 2, 3, 4, 5), 3 ));