我正在研究一种有效的遗传计算器,但不是我想要的哈哈。
我使用以下代码:
<?php
function getGeneArray($geneString) {
// check the argument for fitting your needs!
if ( strlen($geneString) % 2 == 1 ) {
die('Supplied geneString is not made of pairs!'); // better not die - handle errors according to your application methodology
}
// add additional error-catching (there are only certain possible base-pairs, if something else is found you should reject the string
$genes = array();
$i = 0;
while ( $i < strlen($geneString) )
{
$genes[] = substr($geneString, $i, 2);
$i += 2; // Here is your mistake, you just $i++
}
return $genes;
}
function combinePairs($A, $B) {
// uppercase genes build the string first, which means B must be uppercase to come first and A cant be uppercase -- no longer important
if ($A !== $A && $B === $B) {
return $B.$A;
}
return $A.$B;
}
$gene1 = 'bbEe';
$gene2 = 'bbEe';
$geneA = getGeneArray($gene1);
$geneB = getGeneArray($gene2);
$possibilities = array();
foreach ($geneA as $A) {
foreach ($geneB as $B) {
$possibilities[] = combinePairs($A, $B);
}
}
运行上述代码的输出是:
Array ( [0] => bbbb [1] => bbEe [2] => Eebb [3] => EeEe )
实际上,我希望它是这样的:
Array ( [0] => bbee [1] => bbEe [2] => bbEE )
我能做些什么/改变以获得正确的结果?
答案 0 :(得分:0)
使用str_split
function getGeneArray( $str ) {
if ( strlen( $str ) % 2 == 1 ) die('Supplied gene string is not made of pairs!');
return str_split( $str, 2 );
}
对于combinePairs
函数,它似乎只会返回$A.$B
- 如果不知道计算是如何工作的,那么很难给出答案。
我不知道这是combinePairs
函数应该是怎样的
function combinePairs( $A, $B ) {
return strtolower( $A )!=$A && $B===$B ? $B.$A : $A.$B;
}
关于计算序列的可能兴趣(根据您对"uppercase genes build the string first"
的评论,ctype_*
系列函数可能会有用。
`ctype_lower( $str )` ~ tests if ALL characters in $str are lowercase.
`ctype_upper( $str )` ~ tests if ALL characters in $str are uppercase.
`ctype_alpha( $str )` ~ tests that all characters in $str are Alphabetic.
要测试字符串是否包含大写字符,您可以执行以下操作:
if( strtolower( $str ) != $str ){/* contains an uppercase character */}