我想根据下面的逻辑将简单的字符串转换成另一种格式
示例1:如果字符串是3,4-8-7,5,那么我需要设置为(3,8,7),(4,8,5)。示例2:如果字符串是"4-5,6-4“,那么所需的集合将是(4,5,4),(4,6,4)。
更明确的要求:
如果字符串是5-6,7,8-2,3-1。结果:(5,6,2, 1 ),(5,6,3,1),(5,7,2,1),(5,7,3,1),(5,7,3,1),(5,8,2,1),(5,8,3,1),(5,8,3,1)。
构建集合背后的逻辑是我们需要考虑的',‘as或条件和'-’as和条件。
我正在尽我最大的努力使用For循环,但无法找到解决方案。
$intermediate = array();
$arry_A = explode('-', '3,4-8-7,5');
for ($i = 0; $i < count($arry_A); $i++) {
$arry_B = explode(',', $arry_A[$i]);
for ($j = 0; $j < count($arry_B); $j++) {
if (count($intermediate) > 0) {
for ($k = 0; $k < count($intermediate); $k++) {
$intermediate[$k] = $intermediate[$k] . ',' . $arry_B[$j];
}
} elseif (count($intermediate) === 0) {
$intermediate[0] = $arry_B[$j];
}
}
}echo $intermediate,应该给出最终结果。
发布于 2015-08-10 14:33:04
很酷的小锻炼!
为了提高可读性,我将使用以下代码来完成该任务:
我使用数组作为输出,因为它比字符串更容易检查。
首先,我们初始化$string并创建输出数组$solutions。我们将从一开始计算可能组合的最大值($results),并用空数组填充$solutions数组,这些数组稍后将用实际的组合填充。
$string = '3,4-8-7,5';
$solutions = array();
$results = substr_count($string,',')*2;
for($i = 0; $i < $results; $i++) {
array_push($solutions,array());
}我们需要两个辅助函数:checkSolutions,它确保组合不存在超过$limit时间。numberOfORAfterwards,它将计算OR模式在$string中的位置,因此我们可以计算在演练的单个步骤中允许组合的频率。
function checkSolutions($array,$solutions,$limit) {
$count = 0;
foreach($solutions as $solution) {
if($solution === $array) $count++;
}
if($count < $limit) return true;
else return false;
}
function numberOfORAfterwards($part,$parts) {
foreach($parts as $currPart) {
if($currPart === $part) $count = 0;
if(isset($count)) if(!ctype_digit($currPart)) $count++;
}
return $count;
}现在,主要部分:我们将遍历$string的“部分”,其中一个部分是AND操作之间的数字。
如果您需要进一步解释这个循环,只需留下注释。
$length = 0;
// split by all AND operations
$parts = explode('-',$string);
foreach($parts as $part) {
if(ctype_digit($part)) {
// case AND x AND
foreach($solutions as &$solution) {
array_push($solution,$part);
}
} else {
// case x OR x ...
$digits = explode(',',$part);
foreach($digits as $digit) {
for($i = 0; $i < $results/count($digits); $i++) {
foreach($solutions as &$solution) {
if(count($solution) == $length) {
$test = $solution;
array_push($test,$digit);
$limit = numberOfORAfterwards($part,$parts);
echo $digit.' '.$limit.'<br>';
if(checkSolutions($test,$solutions,$limit)) {
array_push($solution,$digit);
break;
}
}
}
}
}
}
$length++;
}
print_r($solutions);一些测试:
String: 3,4-8-7,5
Combinations: (3,8,7)(3,8,5)(4,8,7)(4,8,7)
String: 5-6,7,8-2,3-1
Combinations: (5,6,2,1)(5,6,3,1)(5,7,2,1)(5,7,3,1)(5,8,2,1)(5,8,2,1)
String: 2,1-4-3,2-7,8-9
Combinations: (2,4,3,7,9)(2,4,3,8,9)(2,4,2,7,9)(1,4,3,7,9)(1,4,2,8,9)(1,4,2,8,9)
String: 1,5-3,2-1
Combinations: (1,3,1)(1,2,1)(5,3,1)(5,3,1)https://stackoverflow.com/questions/31912660
复制相似问题