我有很多不同基因类型的组合。每个组合都有其价值。我想通过组合找到价值。
注意:
切换的字母是相同的。例如:"CT"="TC","AG"="GA"等。
我现在通过将字母转换为数字并比较其总和来解决这个问题。请看我的代码。
这是一个好方法吗?我应该更改数据结构吗?($map)
<?php
function toNum($string)
{
$map = [
'A' => 1,
'C' => 2,
'G' => 3,
'T' => 4,
];
$arr = str_split($string);
$r = 0;
foreach ($arr as $value) {
if (!isset($map[$value])) {
continue;
}
$r += $map[$value];
}
return $r;
}
function getValue($map, $input)
{
foreach ($map as $row => $key) {
$current_row = $row;
$row = explode(',', $row);
$attempt = 0;
foreach ($row as $key => $value) {
if (toNum($row[$key]) === toNum($input[$key])) {
$attempt++;
}
}
if ($attempt === count($row)) {
return $map[$current_row];
}
}
}
$map = [
'CC,GG,AA,CC' => 'high',
'TT,AG,TT,CG' => 'medium',
'CT,AG,TT,GG' => 'low',
];
echo getValue($map, ['CC', 'GG', 'AA', 'CC']) . "n"; // high
echo getValue($map, ['TT', 'AG', 'TT', 'CG']) . "n"; // medium
echo getValue($map, ['TT', 'GA', 'TT', 'GC']) . "n"; // medium
echo getValue($map, ['CT', 'AG', 'TT', 'GG']) . "n"; // low
?>
您可以通过计算给定输入的正确映射键来简化它,而无需更改结构。
function sortString($string)
{
$type_chars = str_split($string);
sort($type_chars);
return implode($type_chars);
}
function getValue($map, $input)
{
$key = implode(',', array_map('sortString', $input));
return $map[$key] ?? null;
}
请注意,最后一行只是 PHP7。如果不运行它,可以将其替换为:
return isset($map[$key]) ? $map[$key] : null;
然后,使用相同的回调对地图的键进行排序:
function sortMap($map)
{
return array_reduce(array_keys($map), function ($sorted_map, $types) use ($map) {
$sorted_types = preg_replace_callback('/[A-Z]{2}/', function ($matches) {
return sortString($matches[0]);
}, $types);
$sorted_map[$sorted_types] = $map[$types];
return $sorted_map;
}, []);
}
演示:https://3v4l.org/4HhsV