我正在尝试对三个字符组成的组(如LMH,MMH,HHL等)进行排序,这些组仅包含字符L,M和H,但我需要按照LMH的顺序对其进行排序。这就是我所拥有的,但不确定如何进行比较。重复字符时$ val数组不起作用。这是一个字符串,该字符串被函数分解为数组。
function sortit($str) {
$val = ['L' => 0, 'M' => 1, 'H' => 2];
$parts = str_split($str);
foreach ($parts as $value) {
$order[$val[$value]] = $value;
}
ksort($order);
return implode('',$parts);
}
输入:
MLH
HLL
MHM
LHM
MLH
LHM
MHL
所需的输出:
LMH
LLH
MMH
LMH
LMH
LMH
LMH
答案 0 :(得分:3)
使用B = imread('peppers.png');
% make superpixels
[L,N] = superpixels(B,200);
% find neighbors for all superpixels
glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[],'Symmetric',true);
% find superpixels k neighboring superpixel number 50
supNum = 50;
k=find(glcms(:,supNum));
k(k == supNum) = [];
% find pixels that are in superpixel 50
maskPix = L == supNum;
% find pixels that are in neighbor superpixels k
maskNeighb = ismember(L,k);
% plot
maskPix3 = repmat(maskPix,1,1,3);
maskNeighb3 = repmat(maskNeighb,1,1,3);
Bneigbors = B;
Bneigbors(maskPix3) = 0;
Bneigbors(maskNeighb3) = 255;
figure;
imshow(Bneigbors)
doc:
usort
用作:
function sortit($str) {
$val = ['L' => 0, 'M' => 1, 'H' => 2];
$parts = str_split($str);
usort($parts, function ($a, $b) use ($val) {return $val[$a] - $val[$b];});
return implode("", $parts);
}
答案 1 :(得分:1)
$val = ['L' => 0, 'M' => 1, 'H' => 2];
$strings = ['HML', 'MHM', 'LHL'];
foreach ($strings as $str) {
$arr = str_split($str);
usort($arr, function($val1, $val2) use ($val) {
return $val[$val1] <=> $val[$val2];
});
var_dump(implode('', $arr));
}
您可以使用usort和自定义比较功能对其进行排序。在这里,我使用了val数组,这是一个好主意。