how can I simplify this code?
40 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Cesar Cardenas
am 13 Sep. 2025 um 23:45
Beantwortet: Chuguang Pan
am 14 Sep. 2025 um 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)
0 Kommentare
Akzeptierte Antwort
Chuguang Pan
am 14 Sep. 2025 um 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)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Constants and Test Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!