how can I simplify this code?

40 vues (au cours des 30 derniers jours)
Cesar Cardenas
Cesar Cardenas le 13 Sep 2025 à 23:45
Réponse apportée : Chuguang Pan le 14 Sep 2025 à 6:39
is there any way to simplify this code? any help would be appreciated thanks.
function [idx, pairs_checked, scan_indices] = two_ended_search_1(x, target)
% TWO_ENDED_SEARCH Bidirectional scan from array ends toward center (arrays-only).
n = length(x);
% --- Edge case: empty array ---
if n == 0
idx = -1;
pairs_checked = zeros(0,2);
scan_indices = zeros(1,0);
return;
end
% --- Preallocate with conservative sizes ---
maxIters = ceil(n/2);
pairs_checked = zeros(maxIters, 2);
scan_indices = zeros(1, 2*maxIters); % at most two comparisons per iter
L = 1; R = n;
idx = -1;
pairCount = 0;
scanCount = 0;
while L <= R
% Record pair at start of iteration
pairCount = pairCount + 1;
pairs_checked(pairCount, :) = [L, R];
% Compare left
scanCount = scanCount + 1;
scan_indices(scanCount) = L;
if x(L) == target
idx = L;
break;
end
% If middle element already checked, stop (avoid duplicate compare)
if L == R
break;
end
% Compare right
scanCount = scanCount + 1;
scan_indices(scanCount) = R;
if x(R) == target
idx = R;
break;
end
% Move pointers inward
L = L + 1;
R = R - 1;
end
% Trim prealloc arrays to actual sizes
pairs_checked = pairs_checked(1:pairCount, :);
scan_indices = scan_indices(1:scanCount);
end
x = [5, 2, 3, 1, 9, 7, 9, 4, 8];
target = 4;
[idx, pairs_checked, scan_indices] = two_ended_search_1(x, target)
idx = 8
pairs_checked = 2×2
1 9 2 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
scan_indices = 1×4
1 9 2 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Réponse acceptée

Chuguang Pan
Chuguang Pan le 14 Sep 2025 à 6:39
function [idx,pairs,scan] = Two_Ended_Search_2(x,target)
idx = find(x==target);
n = length(x);
LR = min(idx-1,n-idx);
pairsL = 1:(LR+1);
pairsR = n:-1:n-LR;
pairs = [pairsL.' pairsR.'];
scan = reshape(pairs.',1,[]);
end
X = [5, 2, 3, 1, 9, 7, 9, 4, 8];
target = 4;
[Idx,Paris,Scan] = Two_Ended_Search_2(X,target)
Idx = 8
Paris = 2×2
1 9 2 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Scan = 1×4
1 9 2 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Plus de réponses (0)

Catégories

En savoir plus sur Constants and Test Matrices dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by