Be the First 1 (leave only the first Truthy)

47

2

Intro

Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic edition of this year's eighth problem.

I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.

Problem

Given a Boolean* list, "turn off" all the Truthies after the first Truthy.

No Truthies? No problem! Just return the list unmodified.

Examples

[falsy,truthy,falsy,truthy,falsy,falsy,truthy][falsy,truthy,falsy,falsy,falsy,falsy,falsy]

[][]

[falsy,falsy,falsy,falsy][falsy,falsy,falsy,falsy]


* All your truthies must be identical, and all your falsies must be identical. This includes output.

Adám

Posted 2017-05-07T20:28:45.733

Reputation: 37 779

2Can we use bit lists or other truthy/falsy list representations that are more natural in our language of choice? – Martin Ender – 2017-05-07T20:32:29.973

@MartinEnder Yes, of course, I thought that was covered by default rules. No?

– Adám – 2017-05-07T20:33:16.217

1Well yeah, if you talk about "truthy" and "falsy" in the challenge instead of "booleans", "true" and "false". ;) – Martin Ender – 2017-05-07T20:36:15.143

1I'm not clear on the booleans. Can we use 0/1 even if our language has True/False? – xnor – 2017-05-07T20:59:44.070

@MartinEnder Thanks. Fixed. – Adám – 2017-05-07T21:08:58.043

@xnor See edit. – Adám – 2017-05-07T21:09:08.980

@Adám Are we choosing which values to expect as Truthy value and Falsey value? Does the output have to use the same ones as the input? – xnor – 2017-05-07T21:10:45.833

1@xnor Ah, good point. I think it would be fair to allow choosing input, but output must match, don't you think so? – Adám – 2017-05-07T21:12:04.893

@Adám I think that's reasonable, though it needs limits to stop people form embedding code into their choice of values (is that a loophole?). Matching output feels right for the challenge. – xnor – 2017-05-07T21:14:07.343

@Adám Actually, I'm a bit sad a language like Haskell can't use an arithmetic solution just because 0's and 1's aren't truthy or falsey. But saying "any two distinct values" would let people use True as False and False as True, which is also silly. Not sure how to handle that. – xnor – 2017-05-07T21:16:00.483

1@xnor I hear you, but if Haskell cannot treat numbers as Booleans, or cannot do arithmetic on Booleans, then that is a real limitation in the golfing power of Haskell, and ought to be reflected in the byte count by necessitating conversions or other work-arounds. What do you think of the footnote formulation? – Adám – 2017-05-07T21:19:12.507

It doesn't matter for this challenge (because the language doesn't have a working interpreter yet), but I'm working on a language which has booleans but not the ability to store them in arrays (not even by printing them one at a time; outputting boolean false would exit the program). How would that work in this challenge? (Normally you'd just use if statements to make them into something else, but the challenge bans that.) – None – 2017-05-08T03:54:15.157

Just to be sure, the input Truthy/falsy values should also be equal to the output T/F? Or can you use 0/1 as input and get TRUE FALSE as output? – JAD – 2017-05-08T07:04:18.730

1@JarkoDubbeldam The first: All your truthies must be identical, and all your falsies must be identical. This includes output. – Adám – 2017-05-08T07:05:39.773

Are two trailing falsey values ok? – Christopher – 2017-05-15T22:38:25.177

@Christopher What do you mean? – Adám – 2017-05-16T00:09:04.237

@Adám Input of 0 1 0 output of 0 1 0 0. Two extra false values at the end – Christopher – 2017-05-16T00:10:49.797

@Christopher I'd say no. That just isn't the right result. – Adám – 2017-05-16T00:28:53.290

@Adám thought so – Christopher – 2017-05-16T01:29:10.760

If working a language with text input separated by newlines, is an empty line acceptable, or should the line be removed entirely? – Dom Hastings – 2017-10-27T07:36:13.953

@DomHastings An empty line is fine. – Adám – 2017-10-27T07:37:28.690

Answers

36

Python 2, 35 bytes

while 1:b=input();print b;True&=b<1

Try it online! Input and output are lines of True/False.

Based on Dennis's solution. Redefines the variable True to be False after a True input is encountered. That way, any further inputs of True will evaluate to False and be printed as such.

The redefinition is True&=b<1, i.e. True = True & (b<1). When the input b is True, then (b<1) is False (since True==1), so True becomes False.

xnor

Posted 2017-05-07T20:28:45.733

Reputation: 115 687

19You can redefine True??? This deserves a +1 just because hax >_> – HyperNeutrino – 2017-05-08T01:33:17.817

1@HyperNeutrino Yes, but not in Python 3. (Which is fine because the language here is Python 2.) – Brian McCutchon – 2017-05-08T02:40:28.100

@BrianMcCutchon Okay thanks. That is just weird though... – HyperNeutrino – 2017-05-08T02:57:09.397

@HyperNeutrino It's probably worth mentioning that you can do True, False = False, True. – Brian McCutchon – 2017-05-08T02:59:32.533

@BrianMcCutchon Okay, thanks! Also, if I do True, False = False, True, will bool(1) return false (like, real false) and bool(0) return real true? – HyperNeutrino – 2017-05-08T03:00:28.980

1@HyperNeutrino - nope. Builtins still return the 'real' value, it's just 'True' that you type that changes. (Or modules, in some cases...). So bool(1) return True, but bool(1) == True returns False. – TLW – 2017-05-08T03:12:29.353

@TLW That's just... Weird... I won't be doing stuff like this anytime soon. :P – HyperNeutrino – 2017-05-08T03:28:54.237

@HyperNeutrino - That's probably for the best :-) It's up there with #define 42 43 for how much 'fun' you can have in a codebase with it. Oh, and with ctypes you can actually make, e.g. the internal Python object that represents int(2) actually have an integer value of 1. This breaks all the things. – TLW – 2017-05-08T04:05:43.837

@BrianMcCutchon Actually, you can. import builtins \n builtins.__dict__["True"] = False. :-) – wizzwizz4 – 2017-05-10T17:16:28.803

@wizzwizz4 That doesn't seem to change anything? – Brian McCutchon – 2017-05-10T17:48:24.947

@BrianMcCutchon It might be good in a Python 3 port. Plus, it'll make eval(input()) work the same as Python 2's input in this case, no matter the local variables. – wizzwizz4 – 2017-05-10T18:49:24.280

30

APL, 2 bytes

<\

Evaluates to the function "scan using less-than". Try it online!

Explanation

In APL, the operator \ (scan) reduces each nonempty prefix of an array from the right using the provided function. For example, given the array 0 1 0, it computes 0 (prefix of length 1), 0<1 (prefix of length 2) and 0<(1<0) (prefix of length 2) and puts the results into a new array; the parentheses associate to the right. Reducing by < from the right results in 1 exactly when the last element of the array is 1 and the rest are 0, so the prefix corresponding to the leftmost 1 is reduced to 1 and the others to 0.

Zgarb

Posted 2017-05-07T20:28:45.733

Reputation: 39 083

Finally! I have been wondering. – Adám – 2017-05-08T10:25:28.087

Now I suppose you can answer in J too, no? – Adám – 2017-05-08T10:31:49.097

@Adám Yes, in J it's 3 bytes: </\ Jelly probably has an analogous 2-byte solution too. – Zgarb – 2017-05-08T10:33:07.427

No, I don't think so, because Jelly is left-to-right. – Adám – 2017-05-08T10:38:27.307

You should post separate language answers as separate posts. – Adám – 2017-05-08T10:43:20.450

@Adám Oh right. Done. – Zgarb – 2017-05-08T10:45:55.793

@Adám While it's unlikely this will be beaten (and I'm sure you'd update the checkmark if it is beaten), I'd suggest waiting a few more days with accepting an answer because you're likely to get more answers if the challenge doesn't look "finished". – Martin Ender – 2017-05-08T13:35:44.087

@MartinEnder Good point. – Adám – 2017-05-08T13:37:10.673

@Zgarb My retraction of the checkmark is only due to MartinEnder's comment. – Adám – 2017-05-08T13:37:39.493

What a strange version of scan APL has. It's neither a left nor a right scan (rather, a mix between them) and doesn't allow the interpreter to reuse previous results in calculating the next. But, as we can see, it does things that can't easily be done with a normal (cumulative) scan operation. (Compare this to the Haskell answer)

– Hjulle – 2017-05-08T18:59:19.400

@Hjulle Indeed, my answer implements precisely this scan "by hand" - although that wasn't how I thought of it originally. Haskell has both left and right scans, but both are aimed at reusing results, so neither works for this. – Ørjan Johansen – 2017-05-08T23:29:18.220

There are couple other two byters for this - ⊤\ and |. – Uriel – 2017-07-24T13:11:31.983

22

Aceto, 19 17 bytes non-competing

New version (17 bytes):

This new version takes the characters one at a time and is best executed with the -F option. It works similar, but not identical to the previous solution:

 >,
Op0
p|1u
,ip^

Old answer (19 bytes):

(Non-competing because I had to fix two bugs in the interpreter)

|p1u
iOp<
|!`X
rd!r

This is the first Aceto answer that highlights what it can do relatively well, I would say. The "lists" are input streams, with one input per line, "1" for true, and "0" for false, with an empty string signifying the end of the list.

code flow illustration

Aceto programs run on a Hilbert curve, starting on the bottom left, and ending on the bottom right. First, we read a string, duplicate, and negate (!) it, turning empty strings into True, everything else into False. Then there's a conditional horizontal mirror (|): If the top element on the stack is truthy, mirror horizontally. This happens when the string was empty. If we do the mirroring, we land on the X, which kills the interpreter.

Otherwise, we convert the remaining copy on the stack to an integer and do another conditional horizontal mirror: This time, because 1 is truthy and 0 is falsy, we mirror if we see the (first) true value. If we don't mirror (so we saw a 0) we print what's on the stack (since the stack is empty, a zero) and jump to the Origin of the curve, where we started, starting the whole process again.

Otherwise, when we saw a 1, we mirror and land on the u, which reverses the direction we move on the Hilbert curve. 1p prints a 1, and now we go on the same O we would have gone if we had seen a 0, but since we're in "reversed mode", our origin is at the bottom right, so we jump there.

Now we read another string, and negate it. If the string was empty, and therefore the top stack element is truthy, ` will not escape the next command (X), making us quit.

Otherwise (if the string wasn't empty), we do escape the X and ignore it. In that case, we go to the left (<), print 0 (because the stack is empty), and jump back to the Origin.

L3viathan

Posted 2017-05-07T20:28:45.733

Reputation: 3 151

2Congratulations on your first proper challenge solved in Aceto. – Adám – 2017-05-07T21:26:02.523

2Looks at diagram. Right… – Adám – 2017-05-07T21:58:01.967

1@Adám It probably won't help (if you don't know Aceto) on its own, but I thought it might be good to see alongside the text to be able to follow it better. – L3viathan – 2017-05-07T22:03:45.973

15

Java8, 24 19 Bytes

Long::highestOneBit

Hope this is legal; I got the impression the input / output doesn't have to evaluate as true/false in the language. Takes a long as input and gives one as output, with ones being true and zeroes being false in the binary representation. For example, binary 00101 is 5 and would return binary 00100 which is 4.

Five bytes thanks to @puhlen

JollyJoker

Posted 2017-05-07T20:28:45.733

Reputation: 381

4Nice approach. Java being competitive‽ – Adám – 2017-05-08T11:04:05.407

3Wow, JAVA as a competitive answer‽ – Zacharý – 2017-05-08T11:06:31.877

Not entirely sure if this is valid for codegolf rules, but this could be improved to 19 chars by using a method reference: Long::highestOneBit which produces the identical result with a shorter syntax – puhlen – 2017-05-08T15:58:35.517

@puhlen expressions evaluating to anonymous functions are allowed. – Cyoce – 2017-05-08T17:27:00.100

@puhlen Thanks, didn't realize that would work here, but since it's completely equivalent.. – JollyJoker – 2017-05-08T18:42:31.810

This isn't quite valid. You need to include the import to Long, as this doesn't compile by itself. That said, java.lang.Long::highestOneBit compiles just fine. – Nathan Merrill – 2017-05-08T19:20:51.363

2

@NathanMerrill The java.lang package is imported by default. From the language spec "A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang."

– JollyJoker – 2017-05-09T07:21:18.243

@JollyJoker you're right. I assumed that wasn't the case because my IDE auto-imports it. My bad :) – Nathan Merrill – 2017-05-09T13:08:49.693

@Adám, ZacharyT: +1 for exposing me to the Interrobang. – Grant Miller – 2017-05-16T00:21:19.723

12

Retina, 6 bytes

1>`1
0

Try it online!

Input is a list of 0s (for False) and 1s (for True).

Matches all 1 and replaces each except the first one (1>) with a 0.

Martin Ender

Posted 2017-05-07T20:28:45.733

Reputation: 184 808

I can see it now. You working in an office on some OS. A manager comes over and yells at you for writing an entire OS with regex. – Christopher – 2017-05-15T21:04:18.840

10

V, 7 bytes

f1òf1r0

Try it online!

My first V submission! \o/

How it works

f1òf1r0
f1       "go to the next occurence of 1
  ò      "repeat the following until end:
   f1    "    go to the next occurence of 1
     r0  "    replace with 0

Leaky Nun

Posted 2017-05-07T20:28:45.733

Reputation: 45 011

How does this work? – Brian McCutchon – 2017-05-08T02:43:55.163

@BrianMcCutchon Explanation added. – Leaky Nun – 2017-05-08T02:45:27.720

This fails for a 1 in the first position :( – nmjcman101 – 2017-05-09T02:17:52.373

@nmjcman101 fixed. – Leaky Nun – 2017-05-09T03:08:27.097

Since you changed the input format, you can swap r0 with <C-x> to decrement the ones and save a byte. – nmjcman101 – 2017-05-09T13:54:47.330

9

Haskell, 25 bytes

Anonymous function taking and returning a list of Bools.

Use as (foldr(\x l->x:map(x<)l)[])[False,True,False,False].

foldr(\x l->x:map(x<)l)[]

Try it online!

How it works

  • Folds over a list from the right, prepending new elements and possibly modifying those following.
  • x is the element to be prepended to the sublist l.
  • Uses that False compares less than True, so map(x<)l will turn any Trues in l into False if x is True.

Ørjan Johansen

Posted 2017-05-07T20:28:45.733

Reputation: 6 914

9

Jelly, 4 bytes

+\=a

Try it online!

Here's a rather different algorithm to most of the other golfing language solutions (although after I posted it, I noticed that the R solution also uses this algorithm), and tying with the current Jelly record holder.

Explanation

+\=a
+\    Cumulative sum of the input list
  =   Compare corresponding elements with the input
   a  Logical AND corresponding elements with the input

As long as all elements to the left of an element are 0, the cumulative sum up to an element will equal the element itself. To the right of the first 1, the two are different (because we're now adding the nonzero total of the elements to the left). Thus, +\= gives us a list containing 1 (i.e. true) up to and including the first truthy element. Finally, logical AND with the original list will give us a 1 for only the first truthy element.

user62131

Posted 2017-05-07T20:28:45.733

Reputation:

8

JavaScript (ES6), 33 26 bytes

a=>a.map(e=>e&!(i-=e),i=1)

I/O is in arrays of 0s and 1s.

Neil

Posted 2017-05-07T20:28:45.733

Reputation: 95 035

8

05AB1E, 6 bytes

Code:

ā<s1kQ

Explanation:

ā         # External enumeration, get a and push [1 .. len(a)]
 <        # Decrement each
  s       # Swap to get the input
   1k     # Get the first index of 1
     Q    # Check for equality with the enumeration array

Uses the 05AB1E encoding. Try it online!

Adnan

Posted 2017-05-07T20:28:45.733

Reputation: 41 965

1k>sƶ-_ is another, worse though. The lift idea may have potential though. – Magic Octopus Urn – 2017-10-27T14:31:04.033

6

Turing machine simulator, 39 bytes

0 0 0 r 0
0 1 1 r 1
1 0 0 r 1
1 1 0 r 1

Try it online!

Leaky Nun

Posted 2017-05-07T20:28:45.733

Reputation: 45 011

Essentially the same thing I'm doing in my answer. – L3viathan – 2017-05-08T07:36:08.640

5

brainfuck, 55 bytes

+>,[[->+>[->-<]>+[-<+>]<<<]>>[-<-<<[->>+<<]>>>]<.[-]<,]

Try it online!

Leaky Nun

Posted 2017-05-07T20:28:45.733

Reputation: 45 011

4

Jelly, 4 bytes

A port of my 05AB1E answer.

i1=J

Explanation (argument α):

i1        # Index of 1 (1-indexed) in α
  =       # Check for equality with the array:
   J      # [1 .. len(α)]

Try it online!

Adnan

Posted 2017-05-07T20:28:45.733

Reputation: 41 965

4

R, 24 bytes

cumsum(T<-scan(,F))==T&T

Try it online!

Example:

For input FALSE TRUE TRUE FALSE
cumsum(T<-scan(,F))==T returns TRUE TRUE FALSE FALSE. The F in the scan ensures logical input.
FALSE TRUE TRUE FALSE and TRUE TRUE FALSE FALSE is FALSE TRUE FALSE FALSE. A single & does an elementwise comparison.

MickyT

Posted 2017-05-07T20:28:45.733

Reputation: 11 735

@rturnbull unfortunately the input format has to be the same as the output. – MickyT – 2017-05-10T17:17:38.113

4

Octave, 23 bytes

@(a)diff([0 cummax(a)])

Try it online!

First difference of cumulative max of the list.

rahnema1

Posted 2017-05-07T20:28:45.733

Reputation: 5 435

4

J, 3 bytes

</\

Defines a monadic verb. This is a trivial port of my APL answer. Try it online!

Zgarb

Posted 2017-05-07T20:28:45.733

Reputation: 39 083

3

Python, 58 bytes

lambda x:[x[i]and x.index(x[i])==i for i in range(len(x))]

If x[i] is false, the output is false; otherwise, it gives whether or not the element is the first occurence in the array of itself.

HyperNeutrino

Posted 2017-05-07T20:28:45.733

Reputation: 26 575

3

Perl 5, 20 bytes

sub{map$_&&!$x++,@_}

Truthy is 1 and falsey is '' (an empty string).

Explanation:

map loops over elements of the list it @_, the arguments passed to the subroutine, setting each element to $_ locally and returning an array of the return values it computes from each element. $_&&!$x++ outputs $_ if $_ is falsey and !$x++ if it is truthy. (Note that && is short-circuiting, so !$x++ is not executed until the first truthy value is reached). $x++ returns 0 (which is falsey) the first time it is run and then increments every time (and so remains truthy). The ! negates $x++, and so it returns truthy the first time it is encountered and falsey thereafter.

Chris

Posted 2017-05-07T20:28:45.733

Reputation: 1 313

Your doubts were justified: you need to submit a full function (or a full program); and this is a only a snippet (therefor, invalid without the sub{...}). – Dada – 2017-05-09T13:28:06.950

3

PHP, 37 bytes

foreach($_GET as$v)echo$v*!$$v++,' ';

user63956

Posted 2017-05-07T20:28:45.733

Reputation: 1 571

2

Pyth - 9 bytes

.e&b!s<Qk

Try it here

.e&b!s<Qk
.e          # Python's 'enumerate' (i.e., for each index k and each element b at that index)
      <Qk   # The first k elements of the input
     s      # 'Sum' these first k elements (with booleans, this is a logical 'or')
  &b!       # The value of the output at index k is [value of input @ index k]&&[the negation of the 'sum']

Maria

Posted 2017-05-07T20:28:45.733

Reputation: 644

1It seems to be more efficient to use a variable and just map over it normally: m&!~|Z. – FryAmTheEggman – 2017-05-08T00:28:13.183

2

Python 2, 45 36 bytes

r=0
while 1:n=input();print n>r;r+=n

Input and output are one Boolean (True or False) per line.

Try it online!

Dennis

Posted 2017-05-07T20:28:45.733

Reputation: 196 637

2

Python 3, 69 66 64 60 54 53 bytes

lambda i:[k==i.index(j)and j for k,j in enumerate(i)]

Takes an array of falses and trues. This is a list comprehension of falses except if the current iteration's value is true and it is the first true in the input.

This seems a little long (and it's my first lambda), so if you can find a way to golf it, it would be greatly appreciated!

OldBunny2800

Posted 2017-05-07T20:28:45.733

Reputation: 1 379

Can you explain? – Adám – 2017-05-07T23:23:56.357

Oh, oops, misinterpreted the question. – OldBunny2800 – 2017-05-07T23:27:01.723

Undeleted and fixed the answer – OldBunny2800 – 2017-05-08T00:03:41.017

You can save one byte by making 0 for 0for. – Zacharý – 2017-05-08T11:03:30.700

It works for 1if and 1else, right? Thanks! – OldBunny2800 – 2017-05-08T11:08:56.723

1if i.index(j)==k and j==1else 0 -> i.index(j)==k and j would work the same if the input is a Boolean vector – Felipe Nardi Batista – 2017-05-08T12:47:03.993

Doesn't even have to be a boolean because python is awesome. Thanks! – OldBunny2800 – 2017-05-08T14:15:22.927

I think @FelipeNardiBatista meant the whole thing, not just the ==1. – Ørjan Johansen – 2017-05-08T16:52:41.697

@OldBunny2800 what i meant is that it it a lot shorter – Felipe Nardi Batista – 2017-05-08T18:34:20.493

i.index(j)==k and => k==i.index(j)and. – Zacharý – 2017-07-13T19:52:31.617

2

C#, 77 bytes

a=>{var b=1<0;for(int i=0;i<a.Length;){a[i]=b?1<0:a[i];b|=a[i++];}return a;};

Compiles to a Func<bool[], bool[]>. Nothing clever really, just a straight forward solution.

TheLethalCoder

Posted 2017-05-07T20:28:45.733

Reputation: 6 930

2

Batch, 85 73 bytes

:a
@(if %1.==. exit)&set/ar=(1-f)*%1
@echo %r%&set/af^|=%1&shift&goto a

Takes input as command line arguments. For eample: 1.bat 0 1 0 1 0 0 1

Previous version

@set f=1
:a
@(if %1.==. exit)&set/ar=f*%1
@echo %r%&(if %1==1 set f=)&shift&goto a

Andrei Odegov

Posted 2017-05-07T20:28:45.733

Reputation: 939

2

sed, 16 19 bytes

15 18 bytes sourcecode + 1 byte for -r flag (or -E flag for BSD sed).

:
s/1(0*)1/1\10/
t

Try it online!

Edit: Thanks Riley for pointing out a mistake.

Maxim Mikhaylov

Posted 2017-05-07T20:28:45.733

Reputation: 571

@Riley Thanks for pointing that out! It looks like TIO has a version of sed that is different from mine (BSD). I can't leave the labels empty. Good to know this. – Maxim Mikhaylov – 2017-05-08T13:19:17.323

Yeah, sorry. TIO uses GNU sed. It's a bug turned feature. – Riley – 2017-05-08T13:20:18.313

2

Brain-Flak, 146 144 bytes

([]){{}({}<>)(())<>([])}{}<>((())){{}({}<>)<>}{}<>(()){{}((){[()](<{}>)}{})(<>)<>}<>(())<>([]){{}(<{}<>>)<>([])}{}<>{}{}([]){{}({}<>)<>([])}<>{}

Try it online!

# Reverse the stack and add a 1 between each to help with reversing later
([]){{}({}<>)(())<>([])}{}<>

# Add a 1 in case there aren't any truthy values (and another 1 like before)
((()))

# Reverse the stack back to it's original order using the 1s from earlier to know when to stop
{{}({}<>)<>}{}<>

# Push 1 to start the loop
(())

# Until we find the first 1
{

 # Pop the last value
 {}

 # Logical not
 ((){[()](<{}>)}{})

  # Put a 0 on the other stack
  (<>)<>

# end loop
}

# Put a 1 on the other stack
<>(())<>

# Push the stack height
([])

# While there are values on this stack
{

 # Move them to the other stack as a 0
 {}(<{}<>>)<>([])

# End while
}{}

# Pop an extra 0
{}

# Switch stacks
<>

# Copy everything back (to reverse it back to it's original)
([])
{
 {}({}<>)<>([])
}<>{}

Riley

Posted 2017-05-07T20:28:45.733

Reputation: 11 345

2

Jelly, 4 bytes

TḊṬ^

Try it online!

How?

This does what was asked in a pretty literal sense:

TḊṬ^ - Main link: list a   e.g. [0,1,0,1,0,0,1]  or  [0,1,0,1,0,1,0]
T    - get the truthy indexes   [  2,  4,    7]      [  2,  4,  6  ]
 Ḋ   - dequeue                  [      4,    7]      [      4,  6  ]
  T  - make a boolean array     [0,0,0,1,0,0,1]      [0,0,0,1,0,1  ]
   ^ - XOR that with a          [0,1,0,0,0,0,0]      [0,1,0,0,0,0,0]

Jonathan Allan

Posted 2017-05-07T20:28:45.733

Reputation: 67 804

2

c (with gcc builtins), 40

A slightly different approach:

f(n){return!n?0:1<<31-__builtin_clz(n);}

This may be ruled invalid - in which case I will happily mark this as non-competing.

Input and output "arrays" are 32-bit unsigned integers - this limits the input list size to be exactly 32 - this may be a disqualifier. If the input is less than 32 bits long, then it may be padded with zero bits at the end.

Try it online.

Digital Trauma

Posted 2017-05-07T20:28:45.733

Reputation: 64 644

2

Brain-Flak, 230 bytes

([]){{}({}[()]<>)<>([])}{}<>([]){{}({}<>)<>([])}{}<>({<({}<>)<>>()}<(())>){({}[()]<<>({}<>)>)}{}(([])<{{}(({})())({<{}>{}((<()>))}<{}{}>)({}<>)<>([])}<>>){({}[()]<({}<>)<>>)}{}<>([]){{}({}<>)<>([])}{}<>{}{}([]){{}({}<>)<>([])}{}<>

I will explain soon but my mom cooked me some fried potatoes

([]){{}({}[()]<>)<>([])}{}<>([]){{}({}<>)<>([])}{}<> Subtracts one from every item

({<({}<>)<>>()}<(())>){({}[()]<<>({}<>)>)}{} Loops down stack until current item is zero and adds one

(([])<{{} (({})())({<{}>{}((<()>))}<{}{}>) ({}<>)<>([])}<>>){({}[()]<({}<>)<>>)}{}<> On every item of stack if it is 0 do nothing and if it is -1 add one

([]){{}({}<>)<>([])}{}<> Flip stack

{}{} Remove the two zeros at top of stack

([]){{}({}<>)<>([])}{}<> Flip stack back

Try it online!

Special thanks

Special thanks to Wheat Wizard and Riley for helping me a ton with code!

Christopher

Posted 2017-05-07T20:28:45.733

Reputation: 3 428

2

Perl 5, 12 bytes

10 bytes code + 2 for -pl.

$_&&=!$-++

Try it online!

Dom Hastings

Posted 2017-05-07T20:28:45.733

Reputation: 16 415

1

Cubix, 14 bytes

W;@.1I?>O;w..W

Try it online

Cubix doesn't have proper lists or booleans, so we take the input as a sequence of space-separated 1s and 0s terminated with a -1.

Unfolded

    W ;
    @ .
1 I ? > O ; w .
. W . . . . . .
    . .
    . .

Explanation

The instruction pointer starts at the top of the left face of the cube, moving to the right.

Initially, we push a 1 onto the stack. We then take one input at a time, with I and branch with ?.

If the input is 0, we see O;, which outputs 0 and pops it from the stack.
If the input is 1, we see ;O;, which pops the 1 from the stack, outputs the top of the stack (which will be 1 the first time around), then pops it from the stack.
If the input is -1, we see @, which ends the program.

user48543

Posted 2017-05-07T20:28:45.733

Reputation:

1

Ruby, 32 bytes

->a{i=1;a.map{|x|x&&[i,i=p][0]}}

Uses 1 for truthy and nil for falsy.

Explanation

->a{           # take an array a
    i=1;       # use i to keep track of if we've gotten a truthy value yet
    a.map{|x|  # for each element x in a:

        x&&[     # if x is truthy:
              i,     # remember the old i,
              i=p    # then set i to false
           ][0]      # and replace x with the old i
    }
}

Cyoce

Posted 2017-05-07T20:28:45.733

Reputation: 2 690

1

x86 assembly instructions, 12 bytes

31 c0 0f bd cf 74 04 ff c0 d3 e0 c3

Or in gcc assembly:

    .globl  f
f:
    xor     %eax, %eax
    bsrl    %edi, %ecx
    je  .L2        
    inc     %eax
    sall    %cl, %eax
.L2:
    ret

This is a translation of my c answer and has the same I/O specs.

Try it online.

Digital Trauma

Posted 2017-05-07T20:28:45.733

Reputation: 64 644

1

vim, 19 keystrokes

2/1<ENTER>i<ENTER><ESC>:s/1/0/g<ENTER>kJx

2/1<ENTER>i<ENTER><ESC> puts everything after the first 1 to the second line and moves the cursor to that line. :s/1/0/g<ENTER> replaces the 1s with 0s. kJx then merges the lines.

Ray

Posted 2017-05-07T20:28:45.733

Reputation: 1 488

1

Perl 6, 19 bytes

{@_ «&&»[\^^] @_}

This is an anonymous function that takes its arguments in @_. ^^ is the exclusive-or operator, and [\^^] does a scan using that operator, returning a copy of the input list where the first truthy value is replicated until the second truthy value, whereupon it and all remaining values become Nil (which is falsy). To falsify the replicated copies of the first truthy value, if any, the list is combined with the original using &&, the boolean and operator.

Sean

Posted 2017-05-07T20:28:45.733

Reputation: 4 136

1

Javascript, 25 bytes

x=>x.map(c=>c&&x&&!(x=0))
  • x holds the original array.
  • Once the first truthy has been found, x is overwritten with a false value.
  • This makes c && x return false for all values except the first truthy.

efdee

Posted 2017-05-07T20:28:45.733

Reputation: 111

1

Scala, 44 bytes

s=>{var b=1>2;s.map{x=>if(b)!b else{b=x;x}}}

corvus_192

Posted 2017-05-07T20:28:45.733

Reputation: 1 889

1

PowerShell, 29 bytes

$args|%{$_-and!$b;$b=$b-or$_}

Try it online!

briantist

Posted 2017-05-07T20:28:45.733

Reputation: 3 110

1

OCaml, 85 60 bytes

let rec f?(b=true)=function h::t->(h&&b)::(f~b:(h<b)t)|_->[]

Ungolfed

let rec f ?(b=true) = function
    | head :: tail -> (head && b) :: (f ~b:(head<b) tail)
    | _            -> []

Explanation

f is defined as a recursive function taking an optional (?) boolean b and an unnamed list (function) and return according to the cases:

  • if the first element of the list is false, returns it unchanged,
  • if the first element if the list is true, sets it to b and flip b to false (id est, only let unchanged the first true since b is true by default and then set to false),
  • if the list is empty (end of recursive call), returns the empty list.

Usage

Try it online (you'll need to copy/paste the function definition) !

# f [];;
- : bool list = []
# f [false];;
- : bool list = [false]
# f [true];;
- : bool list = [true]
# f [false;true;true;false;true;true;false;true;false;false];;
- : bool list =
[false; true; false; false; false; false; false; false; false; false]

History

25 (yes, twenty-five) bytes golfed off by Ørjan Johansen, suggesting to merge the first two cases (see explanation).

YSC

Posted 2017-05-07T20:28:45.733

Reputation: 732

1You can merge the first two cases: let rec f?(b=true)=function c::t->(c&&b)::(f~b:(c<b)t)|_->[]. – Ørjan Johansen – 2017-05-10T17:03:31.440

@ØrjanJohansen Thanks, that's 25 bytes golfed! – YSC – 2017-05-11T15:40:15.857

1

F#, 79 76 72 bytes

let rec f o=function|[],_->o|x::y,1->f(o@[0])(y,1)|x::y,_->f(o@[x])(y,x)

Try it online!

Usage

let input = [0;0;0;0;1;1;0;0;1]
printfn "%A" f [] (input, 0)

Explanation

This is a very straightforward implementation.

f is a function with two arguments, first being the result list and the second a tuple of input and a value indicating if a truthy value has been found.

Note: only 1 is considered truthy, every other number is falsy. Which sounds weird now that I think about it. This however, can easily be changed so that any value <> 0 is truthy. But I think it should be ok the way it is, as expected input is only 0 or 1

// int list -> int list * int -> int list
let rec f output = function
| [], _ -> output                      // return result
| x::xs, 1 -> f (output@[0]) (xs,1)    // if truthy was encountered before, append 0 to result, process rest of input
| x::xs, _ -> f (output@[x]) (xs,x)    // if not, append 0 or 1 to result, process rest of input

Brunner

Posted 2017-05-07T20:28:45.733

Reputation: 331

1

PHP, 34 bytes

foreach($_GET as$g)echo$f?0:$f=$g;

Try it online!

inarilo

Posted 2017-05-07T20:28:45.733

Reputation: 111

0

PHP, 61 Bytes

$n=[];foreach($_GET as$v)$n[]=$n&&max($n)?0:$v;print_r($n);

Try it online!

Jörg Hülsermann

Posted 2017-05-07T20:28:45.733

Reputation: 13 026

0

Japt, 7 bytes

®?!T°:Z

Try it online!

Luke

Posted 2017-05-07T20:28:45.733

Reputation: 4 675

0

ReRegex, 18 bytes

1(0*)1/1$10/#input

Fairly simple solution, ReRegex takes all pairings of 1(0*)1, which is two 1s with any amount of 0s in between, and just leaves the first 1, replacing the second with a 0. As ReRegex keeps running the regex until no more change happens, which satisfies the challenge.

Try it online!

ATaco

Posted 2017-05-07T20:28:45.733

Reputation: 7 898

This solution removes ones from the input, but I believe the challenge asks to turn them into zeros. This can be fixed by adding a final 0 to the substitution pattern – Leo – 2017-05-08T09:40:57.800

0

Idris, 98 bytes

The code is a bit longer, but on the plus side you get the compile time guarantee that the output has the same size as the input!

import Data.Vect
f:Vect n Bool->Vect n Bool
f[]=[]
f(x::y)=x::if x then replicate _ False else f y

I'm going to give an extensive explanation to have you understand the basic workings of Idris.

Explanation

import Data.Vect

The type Vect : Nat -> Type -> Type is not imported by default

f : Vect n Bool -> Vect n Bool

Contrary to Haskell, Idris uses a single colon : to specify types and also requires you to specify the type, as the dependent type checker can't possibly infer it in all cases. Since Vect takes a Nat (natural number) and a Type, we provide just that, n being a natural number and Bool being the type. Even though we didn't specify the type of n explicitly, Idris can infer it to be Nat. Since n occurs both in the argument and the resulting type, they need to be the same.

f [] = []

As the base case, the empty list returns the empty list. This is the only possible implementation, anything else such as f[]=[True] would give a compiler error, since the type of [] is Vect 0 Bool but the type of [True] is Vect 1 Bool.

f (x :: y) = x :: if x then

:: is used as the cons operator in Idris, similar to : in Haskell. We put the first element in the resulting list, unchanged.

  replicate _ False else

If the first element is true, we want the rest of the list to be false in any case, so we just replicate the value False. Since Idris knows that the rest of the list has to have the same size as y, it can infer the value of _ (namely length y).

  f y

If the first element is false, we just move on by recursively calling the function on the rest.

Silvan Mosberger

Posted 2017-05-07T20:28:45.733

Reputation: 131

0

77 Bytes, Javascript

var s=0;[0,0,0,1,0,0].forEach(function(c,i,a){if(c||s)s=c=1;console.log(c)});

I/O are zeros and ones.

WasteD

Posted 2017-05-07T20:28:45.733

Reputation: 101

0

F#, 88 bytes

let c2 u=
 let n=ref(1<0)
 [for i in u do if !n||not i then yield 1<0 else n:=i;yield i]

Use as follows:

let mutated = c2 [true; true; false; false; true]

or

printfn "%A" (c2 [true; false; true; false; true])

Vojtěch Štěpančík

Posted 2017-05-07T20:28:45.733

Reputation: 1

0

AWK, 31 bytes

BEGIN{ORS=RS=" "}$1{$1=t-->-1}1

Try it online!

Assumes input is space-separated 1 and 0. Most of the code is just splitting the records on for input and output. The variables could be assigned via command-line options, but it only saves a couple bytes and TIO doesn't count them. :(

BTW

BEGIN{ORS=RS=" "}$1&&t++{$1=0}1

also works, but I find it a bit harder to read and has the same byte-count, anyway.

Robert Benson

Posted 2017-05-07T20:28:45.733

Reputation: 1 339

0

Chip, 10 bytes

,.
`z.
a\A

Try it online!

How?

The elements a\A will copy the lowest bit of input (A) to the lowest bit of output (a) so long as the switch is inactive (\).

When A is powered, due to a truthy input, it activates the delay element (z) via a wire (.). This delay element will wait one cycle -- that is, until the next input byte -- at which point it will send the signal onward. This activates the switch, cutting off the input from the output, and via some more wires (` , .) activates itself for the next cycle.

If you change the normally-closed switch \ for a normally-open switch /, you'd get a circuit that filters out only the first truthy value.

Phlarx

Posted 2017-05-07T20:28:45.733

Reputation: 1 366

0

Retina, 16 bytes

+T`1`0`(?<=1)0*1

Try it online! My first Retina submission ever.

Steven H.

Posted 2017-05-07T20:28:45.733

Reputation: 2 841

0*1 can be replaced with .* – eush77 – 2017-05-20T22:38:20.777

0

C++, 77 75 bytes

Yay pointers and memset!

void f(bool*a,int b){bool*c=&a[b];while(a<c)if(*a++)break;memset(a,0,c-a);}

Function takes in a pointer to a bool array, and the length of that array as parameters. It loops through the array until it finds the first true, increments one more cell, and memsets the remainder of the memory from that pointer until the end. 0 length arrays work too since the loop is skipped entirely and the memset gets 0 bytes as the length, however passing in null instead of an empty array will break things.

Ungolfed + tests

#include <iostream>
#include <cstdlib>
#include <cassert>

//void f(bool*a,int b){bool*c=&a[b];while(a<c)if(*a++)break;memset(a,0,c-a);}

void f(bool* a, int b)
{
    bool* c = &a[b];
    while (a < c)
        if (*a++)
            break;
    memset(a, 0, c - a);
}

void print(bool* a, int b)
{
    for (int i = 0; i < b; i++)
    {
        std::cout << a[i] << '\t';
    }
    std::cout << std::endl;
}

int main()
{
    size_t s = sizeof(bool);
    assert(s == 1);
    bool* t1 = new bool[5] { false, false, false, false, false };
    bool* t2 = new bool[0];
    bool* t3 = new bool[6] { false, false, true, false, true, true };
    bool* t4 = new bool[10] { true, true, true, true, true, true, true, true, true, true };
    f(t1, 5);
    f(t2, 0);
    f(t3, 6);
    f(t4, 10);
    print(t1, 5);
    print(t2, 0);
    print(t3, 6);
    print(t4, 10);
    delete[] t1;
    delete[] t2;
    delete[] t3;
    delete[] t4;
}

Cody

Posted 2017-05-07T20:28:45.733

Reputation: 447

0

Befunge-98, 19 bytes

&:1`#@_1*:.70g\-70p

Try it online!

Input: stream of numbers, 0 (false), 1 (true), or 2 (EOF).

Output: stream of numbers, 0/1.

Explanation

The program works by reading the next number in a loop, multiplying it by a constant, and printing the result to stdout. The operation described in the problem statement is performed by modifying that constant:

&:1`#@_1*:.70g\-70p
       ^          v
       [ P[7]-= x ]

eush77

Posted 2017-05-07T20:28:45.733

Reputation: 1 280

0

CJam, 10

{_1#\,,f=}

Try it online!

Explanation:

This is a function that takes an array of 0 and 1 from the stack, and pushes the resulting array on the stack.

_      duplicate the array
1#     find the index of the first 1 (it is -1 if not found)
\      swap with the other copy of the array
,      get the array length, let's call it n
,      make an array [0 1 … n-1]
f=     compare each element with the index we got earlier

aditsu quit because SE is EVIL

Posted 2017-05-07T20:28:45.733

Reputation: 22 326

-1

PowerShell, 25 bytes

$args|%{$_-and!$f;$f+=$_}

Previous "non legal" version

{$_*!$f;if($_){$f=1}}

Try it online!

The one more version with the same length of 25 bytes

$args|%{!!$f-lt$_;$f+=$_}

Try it online!

Andrei Odegov

Posted 2017-05-07T20:28:45.733

Reputation: 939

Is this a legal answer? I am honestly not sure. You cannot run this on its own as a function or program. It is a process scriptblock for the foreach-object cmdlet. I would have expected you to use $args – Matt – 2017-05-08T18:34:41.703

@Matt I would say no, it's not legal. – briantist – 2017-05-09T20:05:06.597

@briantist Well that is good then. I don't feel the need to go back to my old answers now. – Matt – 2017-05-09T20:06:23.363

1

@Matt here's the relevant clarification for PowerShell specifically.

– briantist – 2017-05-09T20:08:22.040