我需要创建一个没有近亲繁殖的逻辑关系。。。(动物杂交)
A B C D E
每个字母都在一个系列之下,可以从2到N不等(用户输入)
阵列:
a b c d e f
步骤1(打印:)
ab bc cd de ef fa
步骤2(打印:)
abcd bcde cdef defa efab fabc
到此为止,因为例如,如果你试图穿越abcd,其他人都至少有一个字母
一些规则-元素在任何阶段都不能重复,例如:AA或BB..CC..DD-组的元素可能不会出现在下一个。。。第三阶段示例:
字符串:AB BC CD DE EA
错误->AB BC
正确->AB CD
- 第一阶段,只需打印数组的每个元素
- 第二阶段,用下一个打印每个元素,用第一个打印最后一个
- 三个阶段,打印每个家庭的4个元素
知道吗?
更新
在我的数据库中,我有一个数组:
例如:["Fish1"、"FishEx3"、"FishExample"、"菲什规范"、"费什其他规范"]
我需要使用这个函数来解析它。
这不是一个不错的解决方案,但它确实有效。PHP
Fiddle
function Crossbreed($species = array())
{
if (empty($species)) {
return array();
}
$half_way = array();
$output = array();
$species_length = count($species) - 1;
foreach ($species as $index => $specie) {
$next = $index + 1;
if ($index >= $species_length) {
$next = $index - $species_length;
}
$half_way[] = $specie . $species[$next];
}
foreach ($half_way as $index => $specie) {
$next = $index + 2;
if ($next >= $species_length + 1) {
$next = $next - $species_length - 1;
}
$output[] = $specie . $half_way[$next];
}
return $output;
}
$species = array("Fish1","FishEx3","FishExample","FishSpecie","FishOtherSpecie");
$crossbred = Crossbreed($species);
$half_way
变量的输出(数组中有数字,便于读取)
Array (
[0] => 12
[1] => 23
[2] => 34
[3] => 45
[4] => 56
[5] => 67
[6] => 78
[7] => 89
[8] => 91
)
函数的输出(数组中有数字,所以很容易读取)
Array (
[0] => 1234
[1] => 2345
[2] => 3456
[3] => 4567
[4] => 5678
[5] => 6789
[6] => 7891
[7] => 8912
[8] => 9123
)
使用以下函数:
$arr = ['a', 'b', 'c', 'd', 'e', 'f'];
print_stage1($arr);
print_stage2($arr);
print_stage3($arr);
function increment($total, $pos, $inc){
if($pos + $inc < $total)
return $pos + $inc;
else
return ($pos + $inc) - $total;
}
function print_stage1($arr){
foreach($arr as $key => $family){
print $arr[$key]. " ";
}
}
function print_stage2($arr){
$total = count($arr);
foreach($arr as $key => $family){
$next_key = increment($total, $key, 1);
print $arr[$key] . $arr[$next_key]. " ";
}
}
function print_stage3($arr){
$total = count($arr);
foreach($arr as $key => $family){
$next1 = increment($total, $key, 1);
$next2 = increment($total, $key, 2);
$next3 = increment($total, $key, 3);
print $arr[$key] . $arr[$next1]. $arr[$next2]. $arr[$next3]. " ";
}
}
您要解释的是一个非常简单的独特组合数学问题,它可以用堆栈来解决。通过一次从数组/堆栈中移动/弹出一个元素,并将其与另一个元素连接,您最终会耗尽数组。对于进一步的组合数学,可以多次重复这个过程。
下面是一个例子。
function combine(Array $stack)
{
$newStack = [];
$lastElement = array_shift($stack);
while($nextElement = array_shift($stack)) { // shift
$newStack[] = $lastElement . $nextElement; // push
$lastElement = $nextElement;
}
return $newStack;
}
var_dump($level1 = combine(['a','b','c','d','e','f']), $level2 = combine($level1));
结果是。。。
array(5) {
[0]=>
string(2) "ab"
[1]=>
string(2) "bc"
[2]=>
string(2) "cd"
[3]=>
string(2) "de"
[4]=>
string(2) "ef"
}
array(4) {
[0]=>
string(4) "abbc"
[1]=>
string(4) "bccd"
[2]=>
string(4) "cdde"
[3]=>
string(4) "deef"
}