Count trailing truths
Dyalog APL, 6 2 bytes
⊥⍨
Test it on TryAPL.
How it works
⊥ (uptack, dyadic: decode) performs base conversion. If the left operand is a vector, it performs mixed base conversion, which is perfect for this task.
For a base vector b = bn, ⋯, b0 and a digit vector a = an, ⋯, a0, b ⊥ a converts a to the mixed base b, i.e., it computes b0⋯bn-1an + ⋯ + b0b1a2 + b0a1 + a0.
Now, ⍨ (tilde dieresis, commute) modifies the operator to the left as follows. In a monadic context, it calls the operator with equal left and right arguments.
For example, ⊥⍨ a is defined as a ⊥ a, which computes a0⋯an + ⋯ + a0a1a2 + a0a1 + a0, the sum of all cumulative products from the right to the left.
For k trailing ones, the k rightmost products are 1 and all others are 0, so their sum is equal to k.
JavaScript (ES6), 21 bytes
f=l=>l.pop()?f(l)+1:0
Test cases
f=l=>l.pop()?f(l)+1:0
console.log(f([])); // → 0
console.log(f([0])); // → 0
console.log(f([1])); // → 1
console.log(f([0, 1, 1, 0, 0])); // → 0
console.log(f([1, 1, 1, 0, 1])); // → 1
console.log(f([1, 1, 0, 1, 1])); // → 2
console.log(f([0, 0, 1, 1, 1])); // → 3
console.log(f([1, 1, 1, 1, 1, 1])); // → 6
Jelly, 4 bytes
ŒrṪP
Try it online! or Verify all test cases.
For the case where the list is empty, there are some curious observations. First, run-length encoding the empty list []
returns another empty list []
. Then retreiving the last element from that using tail Ṫ
returns 0
instead of a pair [value, count]
which are the regular elements of a run-length encoded array. Then product P
returns 0
when called on 0
which is the expected result.
Explanation
ŒrṪP Main link. Input: list M
Œr Run-length encode
Ṫ Tail, get the last value
P Product, multiply the values together