Skip to main content
added an explanation
Source Link
Arnauld
  • 205.5k
  • 21
  • 187
  • 670

JavaScript (ES6), 49 bytes

f=a=>1/a.sort((a,b)=>a-b)?0:a.pop(a.pop())/2+f(a)

Try it online!

How?

Because sort() operates in lexicographical order by default, we unfortunately need the explicit callback function (a, b) => a - b, although all test cases would pass without it.

We can stop as soon as the array is empty or only one element remains. Hence the test 1 / a which evaluates to:

  • Infinity (truthy) if the array is empty
  • A positive float (truthy) if the array is a singleton
  • NaN (falsy) when at least 2 elements remain

Because the .pop() method ignores its argument(s), the expression a.pop(a.pop()) simply discards the last element and returns the penultimate one.

JavaScript (ES6), 49 bytes

f=a=>1/a.sort((a,b)=>a-b)?0:a.pop(a.pop())/2+f(a)

Try it online!

JavaScript (ES6), 49 bytes

f=a=>1/a.sort((a,b)=>a-b)?0:a.pop(a.pop())/2+f(a)

Try it online!

How?

Because sort() operates in lexicographical order by default, we unfortunately need the explicit callback function (a, b) => a - b, although all test cases would pass without it.

We can stop as soon as the array is empty or only one element remains. Hence the test 1 / a which evaluates to:

  • Infinity (truthy) if the array is empty
  • A positive float (truthy) if the array is a singleton
  • NaN (falsy) when at least 2 elements remain

Because the .pop() method ignores its argument(s), the expression a.pop(a.pop()) simply discards the last element and returns the penultimate one.

Source Link
Arnauld
  • 205.5k
  • 21
  • 187
  • 670

JavaScript (ES6), 49 bytes

f=a=>1/a.sort((a,b)=>a-b)?0:a.pop(a.pop())/2+f(a)

Try it online!