Who is the tallest?
JavaScript (ES6), 78 76 72 bytes
Thanks to @edc65 for -4 bytes
f=a=>a.map((c,i)=>(p>c|c<a[i+1]?q:r).push(p=c),p=q=[],r=[])&&r[1]?f(q):r
Takes in an array of integers and outputs an array containing only the winner.
Test snippet
f=a=>a.map((c,i)=>(p>c|c<a[i+1]?q:r).push(p=c),p=q=[],r=[])&&r[1]?f(q):r
g=a=>a?console.log("Input:",`[${a}]`,"Output:",f(a.map(Number))+""):console.error("Invalid input")
g([5,3,9,8,7])
g([1,2,9,4])
g([9,3,8,7,4,12,5])
<input id=I value="9 1 8 2 7 3 6 4 5"><button onclick="g(I.value.match(/\d+/g))">Run</button>
Here are a few other attempts, using .filter
and array comprhensions:
f=a=>(q=a.filter((c,i)=>p>(p=c)|c<a[i+1]||0*r.push(c),p=r=[]))&&r[1]?f(q):r
f=a=>(r=a.filter((c,i)=>p<(p=c)&c>~~a[i+1]||0*r.push(c),p=q=[]))[1]?f(q):r
f=a=>[for(c of(i=p=q=[],r=[],a))(p>c|c<a[++i]?q:r).push(p=c)]&&r[1]?f(q):r
f=a=>(q=[for(c of(i=p=r=[],a))if(p>(p=c)|c<a[++i]||0*r.push(c))c])&&r[1]?f(q):r
Or a double for-loop, horribly long:
a=>eval("for(r=[,1];r[1]&&(p=i=q=[],r=[]);a=q)for(c of a)(p>c|c<a[++i]?q:r).push(p=c));r")
Explanation
The way this works is pretty simple: it builds an array of those who are relatively taller (r
) and an array of those that aren't (q
), then returns r
if it only has one item; if not, it runs itself on q
and returns the result of that.
MATL, 20 bytes
`tTYadZSd0<~&)nq}x2M
Input is a column vector, using ;
as separator.
Try it online! Or verify all test cases.
Explanation
This is a direct implementation of the procedure described in the challenge. A do
...while
loop keeps removing elements until only one has been removed; and that one is the output.
The elements to be removed are detected by taking differences, signum, then differences again. Those that give a negative value are the ones to be removed.
` % Do...while
t % Duplicate. Takes input (implicit) the first time
TYa % Append and prepend a zero
d % Consecutive differences
ZS % Signum
d % Consecutive differences
0<~ % Logical mask of non-negative values: these should be kept
&) % Split array into two: those that should kept, then those removed
nq % Size minus 1. This is used as loop condition. The loop will exit
% if this is 0, that is, if only one element was removed
} % Finally (i.e. execute at the end of the loop)
x % Delete array of remaining elements
2M % Push last element that was removed
% End (implicit)
% Display (implicit)
Python3, 265 260 248 243 203 121 117 112 111 bytes
def T(I):
b=[0];q=[];J=b+I+b
for i,x in enumerate(I):[q,b][J[i]<x>J[i+2]]+=x,
return len(b)<3and b[1]or T(q)
Thank you @ZacharyT, @orion, and @mathmandan for saving 5 45 a lot of bytes!