Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 高分求一?算法,在线等待可?上??

高分求一?算法,在线等待可?上??

Jun 23, 2016 pm 02:18 PM

本帖最后由 sibang 于 2013-08-08 23:44:40 编辑

PHP 算法 函数 字符串 组合

请帮忙写一个函数,用来重新组合字符串,大概如下:
/**参数:	$arr:原始Array	$len:组合后的长度/**/Function getArray($arr,$len){	//请帮忙写}$arr=Array('A','B','C');print_r(getArray($arr,2));$arr=Array('A','B','C','D','E','F');print_r(getArray($arr,4));
Copy after login
Copy after login


要求如下:
第1种: A,B,C
期望能够得到的组合是: AB,AC,BC

第2种: A,B,C,D(可通过参数控制结果长度,如长度为2或3)
期望能够得到的组合是: AB,AC,AD,BC,BD,CD或ABC,BCD,ACD,ABD

第3种: A,B,C,D,E(可通过参数控制结果长度,如长度为2;3或4)
期望能够得到的组合是: AB,AC,AD,AE,BC,BD,BE,CD,CE,DE或ABC,BCD,CDE,ABD,ABE,ACD,ACE,BDE,BCE,ADE或ABCD,BCDE,ABCE,ACDE,ABDE

第四种:A,B,C,D,E,F(可通过参数控制结果长度,如长度为2;3;4或5)
期望能够得到的组合是: 可根据上边的组合推演出来,在此不再例举


回复讨论(解决方案)

排列组合中的 组合?

貌似很有意思的样子...虽然可能做不出来...试试吧

期待算法高手的光?

抱歉...实在弄不出来.... 想了下或许用 深度优先搜索 比较好 但是怎么写呢 还没想好....

做了一点点进展, 谈不上算法,效率很低! 只是希望能帮你打开思路...

思路:先算排列,然后去除排列中重复的地方,来达成组合.

P.S:半路出家,做了一年多PHP了,居然完全不知道数据结构、算法... 手头项目完成后一定好好补补课..

/*$arr = array("A","B","C");Function getArray($arr,$len=2){	$arr2 = array();    foreach ($arr as $y){		foreach($arr as $k){			if($y != $k){					$arr2[] = $y.$k;			}		}	}		$arr3 = array();		foreach($arr2 as $c){		$f = str_split($c);		if($arr3){			$i = 0;			foreach($arr3 as $d){				$e = str_split($d);				if(in_array($f[0],$e) && in_array($f[1],$e)){					$i++;				}			}			if(!$i){				$arr3[] = $c;			}		}else{			$arr3[] = $c;		}	}	return $arr3;}*/$arr = array("A","B","C","D");Function getArray($arr,$len=3){	$arr2 = array();    foreach ($arr as $y){   //$len是几,就循环几次,这里是一个变数		foreach($arr as $k){			foreach($arr as $v){				if($y != $k && $y != $v && $v != $k){   //$len个元素均不相同						$arr2[] = $y.$k.$v;				}			}		}	}		$arr3 = array();		foreach($arr2 as $c){		$f = str_split($c);		if($arr3){			$i = 0;			foreach($arr3 as $d){				$e = str_split($d);				if(in_array($f[0],$e) && in_array($f[1],$e) && in_array($f[2],$e)){    //$len个元素都在数组中的话,$i++ 如果$i大于0,这个记录就抛弃					$i++;				}			}			if(!$i){				$arr3[] = $c;			}		}else{			$arr3[] = $c;		}	}	return $arr3;}print_r(getArray($arr));
Copy after login


有三处会根据$len变化,而ABCD四个字符或者ABCDE五个字符均可正确得出结果

所以关键在$len这里如何判断和递归...

==============================
总觉得这个方法很山寨,求批评指正

A B C D E F G 七个字符的数组, 取三个排列

用上边的方法 结论是
Array ( [0] => ABC [1] => ABD [2] => ABE [3] => ABF [4] => ABG [5] => ACD [6] => ACE [7] => ACF [8] => ACG [9] => ADE [10] => ADF [11] => ADG [12] => AEF [13] => AEG [14] => AFG [15] => BCD [16] => BCE [17] => BCF [18] => BCG [19] => BDE [20] => BDF [21] => BDG [22] => BEF [23] => BEG [24] => BFG [25] => CDE [26] => CDF [27] => CDG [28] => CEF [29] => CEG [30] => CFG [31] => DEF [32] => DEG [33] => DFG [34] => EFG )
35个 应该是正确的.....

你这是求“组合”方法有很多种
我先给你一种“高效率的10移动法”,函数命名选用组合的英文单词combination

function combination( $arr, $num=0) {  $len = count($arr);  if($num == 0) $num = $len;  $res = array();  for($i=1,$n=pow(2, $len);$i<$n;++$i) {    $tmp = str_pad(base_convert($i, 10, 2), $len, '0', STR_PAD_LEFT);    $t = array();    for($j=0;$j<$len;++$j) {      if($tmp{$j} == '1') {        $t[] = $arr[$j];      }    }    if(count($t) == $num) $res[] = join('', $t);  }  return $res;}
Copy after login

调用:
$arr = array('A', 'B', 'C');print_r(combination($arr, 2));
Copy after login
Array
(
[0] => BC
[1] => AC
[2] => AB
)

请帮忙写一个函数,用来重新组合字符串,大概如下:

/**参数:	$arr:原始Array	$len:组合后的长度/**/Function getArray($arr,$len){	//请帮忙写}$arr=Array('A','B','C');print_r(getArray($arr,2));$arr=Array('A','B','C','D','E','F');print_r(getArray($arr,4));
Copy after login
Copy after login


要求如下:
第1种: A,B,C
期望能够得到的组合是: AB,AC,BC

第2种: A,B,C,D(可通过参数控制结果长度,如长度为2或3)
期望能够得到的组合是: AB,AC,AD,BC,BD,CD或ABC,BCD,ACD,ABD

第3种: A,B,C,D,E(可通过参数控制结果长度,如长度为2;3或4)
期望能够得到的组合是: AB,AC,AD,AE,BC,BD,BE,CD,CE,DE或ABC,BCD,CDE,ABD,ABE,ACD,ACE,BDE,BCE,ADE或ABCD,BCDE,ABCE,ACDE,ABDE

第四种:A,B,C,D,E,F(可通过参数控制结果长度,如长度为2;3;4或5)
期望能够得到的组合是: 可根据上边的组合推演出来,在此不再例举

是否有重复字母?
还有AB,BA算不算不同的?
总得要具体说明一下吧

递归的写法

function combination($ar, $k, $m=0, $a=array()) {        static $ret = array();        if($m == 0) {                $m = count($ar);                $ret = array();        }        for($i=$m; $i>=$k; $i--) {                $a[$k-1] = $ar[$i-1];                if($k > 1) {                        combination(&$ar, $k-1, $i-1, $a);                }else {                        array_unshift ($ret, array_reverse($a));                }        }        return $ret;}
Copy after login
利用堆栈的写法
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;}
Copy after login
Copy after login

版大犀利

求问6#为甚么使用pow(2,$len)来做循环次数, 而为什么可以通过转化为2进制数来解决问题? 这一块应该是数学问题了吧.... 但是没想明白, 求点拨...

版大犀利

求问6#为甚么使用pow(2,$len)来做循环次数, 而为什么可以通过转化为2进制数来解决问题? 这一块应该是数学问题了吧.... 但是没想明白, 求点拨...

2进制那个简单的,你首先要明白的是$tmp = str_pad(base_convert($i, 10, 2), $len, '0', STR_PAD_LEFT);这个得到的,他这个是根据取的长度在前面增加几个0,然后可以循环才能有
if($tmp{$j} == '1') {
$t[] = $arr[$j];
}
这个数组,这个数组的长度才能与$len相同,相同的话就组成字符串


版大犀利

求问6#为甚么使用pow(2,$len)来做循环次数, 而为什么可以通过转化为2进制数来解决问题? 这一块应该是数学问题了吧.... 但是没想明白, 求点拨...

2进制那个简单的,你首先要明白的是$tmp = str_pad(base_convert($i, 10, 2), $len, '0', STR_PAD_LEFT);这个得到的,他这个是根据取的长度在前面增加几个0,然后可以循环才能有
if($tmp{$j} == '1') {
$t[] = $arr[$j];
}
这个数组,这个数组的长度才能与$len相同,相同的话就组成字符串

大概略微有点头绪了

是不是二进制数010101之类的 恰好可以代表每个位置选中/未选中

pow(2,$len)可以大于等于所有的排列情况的数量,而小于它的数,每个数的2进制形式也都是不同的,所以恰好可以用这种方式来进行筛选?

还没想透,不知道如何证明或者反证这种巧妙的方法 .... 再纠结下

可参阅 http://blog.sina.com.cn/s/blog_605f5b4f0100vcwz.html

版大犀利

求问6#为甚么使用pow(2,$len)来做循环次数, 而为什么可以通过转化为2进制数来解决问题? 这一块应该是数学问题了吧.... 但是没想明白, 求点拨...

做了10?次循???,??下???效率最高,??了,感?xuzuning老大的?忙

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles