I wrote a matlab code inorder to find the last man standing for the problem given here.
Problem: n people are standing in a circle with gun in their hands. 1 kills 2, 3 kills 4, 5 kills 6 and so on (circularly) till we are left with only one person. Who will be the last person alive.
function N = lastManStanding(n)
while length(n) ~= 1
if mod(length(n),2) == 0
for ii = 1:length(n)/2
a(ii) = [ii*2];
end
n(a) = [];
a = [];
end
if mod(length(n),2) == 1
for jj = 1:floor(length(n)/2)
b(jj) = [jj*2];
end
n(b) = [];
n = circshift(n,[0,1]);
b = [];
end
end
N = n;
What this code basically does is it takes a range array (1,....,n) as input and returns the last remaining index. I was wondering if there exists a closed form equation to solve this or if the above code can be simplified further.
UPDATE Find the updated code below
function N = lastManStanding(n)
while length(n) ~= 1
if mod(length(n),2) == 0
n(2:2:end) = [];
else mod(length(n),2) == 1
n(2:2:end) = [];
n = circshift(n,[0,1]);
end
end
N = n;

narray. For examplen(2:2:end) = [];will remove things without the nestedforloop. Also you don't need the secondifstatement. Just add anelsebranch. - Mattendbeforeelse(in updated code) - Mad Physicist