how can I simplify this code?

조회 수: 40 (최근 30일)
Cesar Cardenas
Cesar Cardenas 2025년 9월 13일 23:45
답변: Chuguang Pan 2025년 9월 14일 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>

채택된 답변

Chuguang Pan
Chuguang Pan 2025년 9월 14일 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>

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Constants and Test Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by