Inspired by, and in memory of, my dear friend and colleague,
Dan Baronet, 1956 – 2016. R.I.P.
He found the shortest possible APL solution to this task:
Task
Given a Boolean list, count the number of trailing truth values.
Example cases
{} → 0
{0} → 0
{1} → 1
{0, 1, 1, 0, 0} → 0
{1, 1, 1, 0, 1} → 1
{1, 1, 0, 1, 1} → 2
{0, 0, 1, 1, 1} → 3
{1, 1, 1, 1, 1, 1} → 6
64 Answers 64
Ruby (削除) 37 (削除ここまで) 32 bytes
->n{n.size-1-(n.rindex(!0)||-1)}
Creates an anonymous function that finds the right-most instance of a false value, and counts the size of the subarray starting at that value.
It uses !0 as false, as 0 are truthy values in Ruby. rindex finds the last index of a value in an array.
Usage:
boolean_list = [true, false, false, true]
->n{n.size-1-(n.rindex(!0)||-1)}[boolean_list]
Returns 1
If I was allowed to be passed a string of 0s and 1s as command line parameters (which is not how ruby represents lists of booleans), I could get it down to 24:
$*[0]=~/(1*)\z/;p1ドル.size
This uses regular expressions and prints the length of the string returned by the regular expression /(1*)\z/, where \z is the end of the string. $*[0] is the first argument passed and is a string of 0s and 1s.
Usage:
trailing_truths.rb 011101
Returns 1.
-
1\$\begingroup\$ Once you have the index of the last false value, why do you need to retrieve elements from the array again? \$\endgroup\$Lee W– Lee W2016年11月07日 16:14:22 +00:00Commented Nov 7, 2016 at 16:14
-
\$\begingroup\$ You're right, I don't. Thanks. 5 bytes off! \$\endgroup\$IMP1– IMP12016年11月08日 08:48:03 +00:00Commented Nov 8, 2016 at 8:48
Pip, 8 bytes
WDQg++ii
Takes input as command-line arguments of 0 and 1 (or any truthy value). Try it online!
Explanation
g is cmdline args, i is 0
DQg Dequeue item from end of g
W ++i While this is truthy, increment i
i Print i
(Dequeueing from an empty list gives nil, which is falsey.)
brainfuck, 99 bytes
Takes input like 11011. Output is a single byte/character value.
-[>+<-----]>---[>>,]<-[>+<-----]>---[-<+>>>+<<]<[->+<]>+>>+[<+[-<<+>>]<<<[-<+>>>-<<]<[->+<]>>>-]<-.
Try it online - Run with input, then click "view memory" to see the value under the pointer that was printed.
Explanation:
-[>+<-----]>--- put constant 48 (ASCII '0') at start of list
[>>,] receive all input, with an empty cell between each
<-[>+<-----]>--- constant 48 near end of list
[-<+>>>+<<]<[->+<]>+>> move to right and copy right, add one to make 49 (ASCII '1')
TAPE: 48 _ i0 _ i1 _ ... in _ 49 _ 48< (pointer)
+[<+[-<<+>>]<< LOOP. Put counter+=1 in empty cell. Move it left 2 cells.
<[-<+>>>-<<]<[->+<]> Subtract value from value 2 cells right.
>>-]<-. Subtract one more. If zero, print counter-1, Else loop again.
Close, but must contain a zero, and it doesn't handle trailing zeros or an empty list. (49 bytes)
,[>>,]>>+[<+[-<<+>>]<<<[-<+>>>-<<]<[->+<]>>>-]<-.
-
\$\begingroup\$
,[>,]-[>+<-----]>---[-<<[<]>[->]>]<<[>[-<+>]<<]>.\$\endgroup\$Jo King– Jo King2018年10月04日 09:30:33 +00:00Commented Oct 4, 2018 at 9:30 -
1\$\begingroup\$ @JoKing Go ahead and create your own answer. That doesn't resemble mine at all. \$\endgroup\$mbomb007– mbomb0072018年10月04日 16:28:11 +00:00Commented Oct 4, 2018 at 16:28
PHP, 38 bytes
a totally different approach
<?=strpos(strrev(join([0]+$argv)),48);
takes input from command line arguments. Save to file.
[0]+$argv sets the first element (script name) to 0.
Join that without a delimiter, reverse and find the first occurence of the 0 character.
While my first solution works with any truthy and falsy values, this one obviously depends on single characters: 0 is falsy, every other character (apart from maybe the 0 byte) truthy.
-
\$\begingroup\$ -4 Bytes for using
$_GET\$\endgroup\$Jörg Hülsermann– Jörg Hülsermann2017年05月03日 13:32:11 +00:00Commented May 3, 2017 at 13:32 -
\$\begingroup\$ @JörgHülsermann That would have empty output for any list full of
1s. \$\endgroup\$Titus– Titus2017年05月03日 14:50:51 +00:00Commented May 3, 2017 at 14:50 -
\$\begingroup\$ Okay now I have realize it \$\endgroup\$Jörg Hülsermann– Jörg Hülsermann2017年05月03日 16:48:50 +00:00Commented May 3, 2017 at 16:48
Pushy, 6 bytes
$v;FL#
Arguments given a list on command line: $ pushy truths.pshy 0,1,1,0,0. Like my binary conversion program, this takes advantage of the second stack in an interesting way. Here's how it works:
\ Implicit: Input on stack
$ \ While last item is not 0:
v; \ Move last item to auxiliary stack
FL# \ Output length of auxiliary stack.
Note that the loop will not run if the list is empty, so the output will be 0.
-
\$\begingroup\$ How many stacks does Pushy have? \$\endgroup\$user41805– user418052016年12月07日 17:09:58 +00:00Commented Dec 7, 2016 at 17:09
-
\$\begingroup\$ @KritixiLithos Two, input is automatically on stack 1 and that's where main operations take place. Stack 2 is just for storing counters / variables that need to be kept out of the way. \$\endgroup\$FlipTack– FlipTack2016年12月07日 17:15:52 +00:00Commented Dec 7, 2016 at 17:15
PHP, (削除) 40 (削除ここまで) 34 bytes
Along with $argv comes $argc ... and both are variable.
Either one of the arguments or +$argv[0]==+"-" is 0.
while(+$argv[--$argc])$i++;echo$i;
takes input from command line arguments. Empty output for 0.
Run with php -nr '<code>' <space separated values>
unary output, (削除) 35 (削除ここまで) 29 bytes
while(+$argv[--$argc])echo 1;
Brain-Flak, 30 bytes
(()){{}({}{{}}<><{}>)<>([])}<>
Explanation
(()) #{ Start Loop. Used instead of ([]) so that the loop will run at least once on empty input. }
{{} #{Remove the stack height. }
(
{}{{}} #{ Add the TOS with any 1s below it (until a zero). }
<><{}> #{ Remove a value on the other stack if there. }
) #{ Push the result (# of 1s just removed) to the other stack. }
<> #{ Switch stacks back. }
([]) #{ Push stack height for the loop. }
} #{ Once the loop is done (stack is empty)... }
<> #{ Switch stacks to the most recent # of 1s removed. }
Taxi, (削除) 1580 (削除ここまで) (削除) 1576 (削除ここまで) 1564 bytes
-4 bytes because of a less complex route to the Crime Lab (string equality checker). Also, you don't run out of gas for a sufficiently large number of truthy values anymore!
-12 bytes by getting rid of the quotes.
Go to the Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to Chop Suey.
Go to Chop Suey:n 1 r 1 l 4 r 1 l.
[B]
Switch to plan C if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l 3 l.
Pickup a passenger going to Narrow Path Park.
Pickup a passenger going to Joyless Park.
Go to Zoom Zoom:n.
Go to Narrow Path Park:w 1 l 1 l 1 r.
Go to Joyless Park:e 1 r 3 l.
Go to Chop Suey:w 1 r 1 r 1 l.
Switch to plan B.
[C]
0 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 3 l 3 l 2 r.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park:w 1 r.
Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.
[D]
Switch to plan F if no one is waiting.
Pickup a passenger going to Crime Lab.
1 is waiting at Writer's Depot.
Go to Writer's Depot:w 1 l 1 r 2 l.
Pickup a passenger going to Crime Lab.
Go to Zoom Zoom:n.
Go to Crime Lab:w 1 l 2 r.
Switch to plan E if no one is waiting.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s.
Pickup a passenger going to Addition Alley.
Go to Sunny Skies Park:n 1 l 1 l 1 r.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:n 1 r 1 r 1 r.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park:n 1 l 1 l 1 l.
Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.
Switch to plan D.
[E]
Go to Narrow Path Park:n 5 l.
[F]
Go to Sunny Skies Park:w 1 l 1 r 2 l 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r 1 r.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.
Go to Taxi Garage:n 1 r 1 l 1 r.
Input is in the form of a string of 0's and 1's (for example: 11101).
Taxi is an esolang in which all programming is done by picking up and dropping off passengers at various stops in the fictional town of Townsburg. Of course, your taxicab will sometimes run out of gas, so you also need to visit gas stations every so often, and pay using the credits you receive as fare.
I had to do some strange management of fuel in this program. Specifically, I have a loop at the beginning (between plans B and C) which pushes each character of the input to Narrow Path Park (which is a LIFO queue, or a stack) by going back and forth between Narrow Path Park and Chop Suey (which split the input string into characters in the first place). However, for sufficiently large inputs, this can cause me to run out of gas. Simply going to a gas station every iteration is insufficient, because I'm not earning enough money from actually bringing passengers to their destinations. The best way I've figured out to earn enough money to make going to a gas station every iteration "worth it" is bringing each new passenger to Cyclone (which clones them), and taking one of those clones to Narrow Path Park while leaving one forever trapped at Joyless Park (which is a FIFO queue, but for the purposes of this program is a dumping ground).
(Note: Bringing passengers to Riverview Bridge is a good way to get rid of them, but they don't pay you - because they always seem to fall off the bridge into the river before they can pay - so I couldn't do this either.)
-
\$\begingroup\$ 1531 bytes (STDERR ignored) \$\endgroup\$The Empty String Photographer– The Empty String Photographer2023年06月16日 11:59:04 +00:00Commented Jun 16, 2023 at 11:59
C++17, (削除) 82 (削除ここまで) 66 bytes
int f(){return 0;}int f(int H,auto... L){return(H*...*L)+f(L...);}
Uses the C++17 template parameter fold expression and essentially the same idea as Dennis. Saving 16 bytes by using Generic Variadic Lambda.
Explanation:
int f(){return 0;} //base case for empty list
int f(int H, auto... L) { //first element, variadic arguments
return (H*...*L) //a_0*a_1*a_2*...
+ f(L...); //+ f(a_1,a_2,...)
}
Usage:
f(1,1,0,1,1,0,1,1,1,1,1) -> 5
f() -> 0
f(1,0,1,0) -> 0
Non competing
Albeit longer, this also works with template constants:
template <int...L> int C=0;
template <int H, int...L> int C<H,L...> = (H*...*L)+C<L...>;
Usage:
std::cout << C<1,0,1,1> << std::endl;
std::cout << C<1,0,1,0,1> << std::endl;
std::cout << C<1,1,1,0,1,0,1,1> << std::endl;
std::cout << C<1,1,1,0,1,0,1,1,1,1,1,1> << std::endl;
std::cout << C<> << std::endl;
Pari/GP, 30 bytes
p->valuation(Pol(p)*(x-1)+1,x)
Converts the list to a polynomial, say \$p\$, then finds the valuation of \$(x-1)p+1\$ with respect to \$x\$, i.e., the minimal degree of its nonzero terms.
For example, if we take [1, 0, 1, 1, 1] as input, then the polynomial \$p\$ is \$x^4 + x^2 + x + 1\$, and \$(x-1)p+1\$ is \$x^5 - x^4 + x^3\$, whose valuation is \3ドル\$.
-
1\$\begingroup\$ Well, that is truly an original method. +1 \$\endgroup\$Adám– Adám2017年07月13日 05:47:28 +00:00Commented Jul 13, 2017 at 5:47
Raku, 17 bytes
{sum [\R*] 0,|@_}
0, |@_is the input list of boolean values with a zero prepended to the front.R*is theReversed multiplication operator. It's the same as the regular multiplication operator*, except that it's right-associative.[\R*]is the "triangular reduction" of the list to the right, using theR*operator. Given a list \$x_0, x_1, ... x_n\$, it produces \$x_n, x_n \cdot x_{n-1}, x_n \cdot x_{n-1} \cdot x_{n-2}, ..., x_n \cdot x_{n-1} \cdot x_{n-2} \cdot ... \cdot x_0\$. Raku's arithmetic operators treat boolean true values as 1 and false values as 0, so this produces a list that starts with as many ones as there are true values at the end of the list, followed by as many zeroes as there are remaining values in the list.sumadds up those values.
It's necessary to paste a leading zero onto the front of the input list, or else an empty list would produce the multiplicative identity element 1.
Python2, (削除) 42 (削除ここまで) 41 Byes
t=input()[::-1];print len(t[:t.index(0)])
takes input as [1, 1, 0, 1, 1]
-
\$\begingroup\$ No joy with the empty list test case. \$\endgroup\$Jonathan Allan– Jonathan Allan2016年11月06日 15:11:12 +00:00Commented Nov 6, 2016 at 15:11
ABCR, 14 bytes
c7iA)7a!xcx!Bp
Accepts the formatting [0,1,0,1,0, where any non-numeric character can be replaced with any other non-numeric character. Empty input is the empty list.
Explanation: Every 7 input number i is queued up A; every "0" input number (or rather, non-"1") )7 will pop from the queue until it's empty 7a!x; before another input number is queued, a delimiter character is grabbed cx to check for the end of queue. After all the integers are grabbed, !Bp prints the length of the queue of input numbers (which will be all the trailing "1" values.)
Swift 3, 49 bytes
func a(b:[Bool]){print(b.reduce(0,{1ドル ?0ドル+1:0}))}
Minkolang, 32 bytes
0$nI1-[1=?v0g1+1R]N.
.Ng0<
Explanation
0 pushes 0 (this is the number that will keep track of the number of 1s)
$n pushes all of input as numbers (pushes -1 if there is no input)
I1- pushes stack minus 1 (to exclude the 0)
[ ] for loop with the previous number as the number of iterations
1=? check equality with 1 (this is for the empty input testcase)
where -1 will be pushed by the interpreter
If number is not 1 (ie 0 or -1[-1 will be pushed if there is no input]):
< start going left
g0 gets the first element in stack
.N output it as number and stop program
If number is 1:
v gets jumped over by ? since true has been evaluated
0g1+ gets the first element and adds 1 to it
1R rotates stack once clockwise
N. outputs as number and stops program
PHP, (削除) 58 (削除ここまで) (削除) 54 (削除ここまで) 53 bytes
function f($a){while(array_pop($a))$i++;return+$i;}
Since PHP has no list I use an array instead
-4 bytes thanks to user59178
-
\$\begingroup\$ Assigning
$i=0;is unnecessary if you echo/return+$i. Having this as a command line program rather than a function is much shorter as well, though you need to account for the fact that $argv[0] is truthy. With both of these you could save 19 bytes. \$\endgroup\$user59178– user591782016年11月07日 16:50:34 +00:00Commented Nov 7, 2016 at 16:50 -
\$\begingroup\$
return+$i;needs no space. \$\endgroup\$Titus– Titus2016年12月07日 16:08:39 +00:00Commented Dec 7, 2016 at 16:08
Clojure, (削除) 39 (削除ここまで) 36 bytes
#(count(take-while{1 1}(reverse %)))
Input as integers [1 0 1 1 0 1 1 1], anything other than 1 is falsy. {1 1} is a hash-map with key 1 and value 1 which can also used as a function. For example ({1 999} 1) is 999 (truthy) whereas ({1 999} 0) is nil (falsy).
Original, based on booleans:
#(count(take-while(fn[i]i)(reverse %)))
Amazing how (fn[i]i) is shorter than identity and also doesn't force you to put a space after take-while. Must take a list or vector of booleans, integers can be converted like this: (map #(= 1 %) [1 0 1 1 0 1 1 1])
Mathematica, 36 bytes
Length[#/.({___,0,x___/;x==1}:>{x})]&
Not the shortest, but short enough where I was proud to submit it :)
brainfuck, 33 bytes
,[+++>-[<->-----],]<[>[-<+>]<<]>.
Takes input via a string like 101011, and then outputs via byte value. I've added some code in the footer to add 48 to the value to output a digit.
,[ Loop over input
+++>-[<->-----] Subtract 48 from each value to form a tape of 0s and 1s
,]
<[>[-<+>]<<] Add up all the trailing ones
>. And print the value
Rust, 44 bytes
|a|a.iter().rev().take_while(|&&i|i).count()
explanation:
|a|a.iter().rev().take_while(|&&i|i).count() //anonymous function
|a|a.iter() //iterate over the input
.rev() //reverse the iterator
.take_while(|&&i|i) //take while **self is true
.count() //Count the elements in the iterator
Fig, \5ドル\log_{256}(96)\approx\$ 4.116 bytes
Lt@x$
No "group consecutive," unlike most other golfing languages.
Lt@x$
$ # Reverse the list
t # Take while
@x # The identity function
L # Return the length
Nekomata + -1, 3 bytes
sP∑
s Find a suffix of the input
P that contains only positive integers
∑ and sum them.
-1 prints the first solution.
Thunno 2 tS, 1 byte
ġ
Or, if you want it flagless:
Thunno 2, 3 bytes
ġtS
Explanation
ġtS # Implicit input
ġ # Group consecutive
t # Last item
S # Sum
# Implicit output
Braingolf, 7 bytes
!?&gGL|
Explanation
!?&gGL| Implicit input from commandline args
!? If last item on stack is > 0..
&g ..Combine all items into single number (1, 1, 0, 1 becomes 1101)
G ..Split into digit runs (1101 becomes 11, 0, 1)
L ..Pop last item and push length of item (111 becomes 3)
| Endif
Implicit output of last item on stack, either number of trailing ones, or zero
-
\$\begingroup\$ You use 3 chars for the conditional. Could you maybe multiply by the parity instead? \$\endgroup\$Adám– Adám2017年07月13日 09:46:31 +00:00Commented Jul 13, 2017 at 9:46
-
\$\begingroup\$ @Adám that would still be 3 bytes, 2 bytes to get the parity (
2%) and one byte to multiply (*) \$\endgroup\$Mayube– Mayube2017年07月13日 09:49:42 +00:00Commented Jul 13, 2017 at 9:49
Backhand, 17 bytes
v I^: ]|{]1$|{O @
Explanation:
v I^: ]|{]1$|{O @
v Decrease step value to 2
I Get input as a number
: ]|{ Reflect if not EOF
^ Increase step value to 3
v Decrease to 2 and repeat the loop
] The leftover EOF (-1) is now our counter. Increment it to 0
$|{ Reflect if the top value is truthy
|{ 1 Reflect and repeat
] Increment the counter for every truthy value
O @ Output the final state of the counter
V, 7 bytes
Ó1*0
ø1
Try it online! Takes input as a string of 0 and 1.
Explanation
Ó1*0 Remove all occurences of any number of ones followed by a zero
ø1 Count the number of remaining ones
01100? \$\endgroup\$