# Question
Title: Separate a list into even-indexed and odd-indexed parts
Inspired by this question:

Make a function (or a full program) that receives a list of numbers and outputs the list rearranged, so that even-indexed numbers appear first, and odd-indexed numbers follow. The values of the numbers themselves don't affect ordering - only their indices do. All indices are zero-based.

For example:

Input: `[0, 1, 2, 3, 4]`

Output: `[0, 2, 4, 1, 3]`

Another example:

Input: `[110, 22, 3330, 4444, 55555, 6]`

Output: `[110, 3330, 55555, 22, 4444, 6]`

Use most natural representation for lists that your language has. There are no limitations on complexity (e.g. allocating a temporary list is OK - no need to do it in-place).

P.S. It should work for the empty list (empty input =\> empty output).

# Answer
# Japt, 1 byte

```
ó

```

Try it online!
> 3 votes

# Answer
## Python, 23 bytes

```
lambda x:x[::2]+x[1::2]

```

Try it online
> 23 votes

# Answer
# Pyth, 5

```
o~!ZQ

```

Try it online, or run a Test Suite

### Explanation

```
o~!ZQ    ## implicit: Z = 0; Q = eval(input)
o   Q    ## sort Q using a supplied function
 ~!Z     ## Use the old value of Z, then set Z to be not Z
         ## This assigns a weight to each number in the list, for example given [0,1,2,3,4]
         ## This will give (value, weight) = [(0,0), (1,1), (2,0), (3,1), (4,0)]
         ## The values are sorted by weight and then by index
         ## This happens because Pyth is written in Python, which performs stable sorts

```
> 16 votes

# Answer
## CJam, 7 bytes

```
{2/ze_}

```

Pushes a block (the closest thing to an unnamed function) which transforms the top stack element as required.

Test it here.

### Explanation

The explanation assumes that the top of the stack is the array `[0 1 2 3 4]`. The actual values don't affect the computation.

```
2/  e# Split the array into chunks of two: [[0 1] [2 3] [4]]
z   e# Zip/transpose, which works on ragged arrays: [[0 2 4] [1 3]]
e_  e# Flatten the result: [0 2 4 1 3]

```
> 12 votes

# Answer
## Labyrinth, ~~28~~ ~~25~~ ~~24~~ ~~23~~ 22 bytes

```
" >
?!?:|}\{@
@\?"":)!

```

This was mad fun! :) That is by far the most densely compressed Labyrinth program I've written so far. I had so many versions at 20 and 21 bytes which *almost* worked that I'm still doubting this is optimal...

This takes input as a list of *positive* integers (with an arbitrary delimiter), and prints the result to STDOUT as linefeed-delimited integers.

**The hunt for 20/21 bytes:** I've checked all programs of the form

```
" XX
?!?X}\{@
@\?XX)!

```

where `X` is any reasonable character by brute force, but didn't find any valid solutions. Of course that doesn't mean that a shorter solution doesn't exist, but it's not possible to force 20-byte programs without a decent amount of assumptions on its structure.

### Explanation

*(The explanation is slightly outdated, but I'm still not convinced the solution is optimal, so I'll wait with updating this.)*

So, normally Labyrinth programs are supposed to look like mazes. While the instruction pointer is in a corridor, it will follow that corridor. When the IP hits any kind of junction, the direction is determined based on the top value of Labyrinth's main stack (Labyrinth has two stacks, with an infinite amount of zeroes at the bottom). That normally means that any non-trivial loop will be quite expensive, because if you have non-wall cells all over the place *everything* is a junction, and in most cases the top of the stack won't have the right value for the IP to take the path you would like it to take. So what you do is you enlarge the loops such that they have a whole in the centre with only one well-defined entry and exit point each.

But this time I was really lucky and everything fit so well together, that I could squash it all into one big clump. :)

Control flow starts at the `_` going South. The `_` pushes a zero onto the main stack. That may seem like a no-op, but this increases the (non-implicit) stack depth to `1` which we'll need later.

`?` reads an integer from STDIN. If there are no more integers to be read, this pushes zero. In that case, the IP keeps moving South and `@` terminates the program right away (because the input list is empty). Otherwise, the IP turns East.

We're now entering a very tight loop with two exit points:

```
 !?;
 \?
  ;

```

`!` prints the integer back to STDOUT, leaving only a zero on the stack. The IP keeps moving East, and `?` reads the next integer. If that is non-zero, we take a right and move South. `?` reads another one (the next even index). Again, if that is non-zero, we take a right and move West.

Then `\` prints a linefeed without changing the stack, so we take another right, moving North. `!` prints that next even-index integer. Since now there is at least one (positive) odd-index integer on the stack, we keep turning right and the loop repeats.

Once either of those `?` hits the end of the list, they push a zero and move straight onto the corresponding `;`, which discards that zero.

In the case that there was only a single element in the list, we're done (because we've printed that right away), so the IP would keep moving East all the way to the `@`, again terminating the program (printing a trailing linefeed on the way).

Otherwise, we need to print the odd-index integers as well. In that case the two paths (from the two exit points of the first loop) merge on the middle `"`, turning East in either case.

`_` pushes a zero to avoid taking a left into the `@`, and `;` discards that zero. Now we enter a new loop:

```
     "}
     ""

```

The IP enters this on the bottom-left cell, moving North, going around the loop in a clockwise sense. The `}` shifts the top of the main stack over to the auxiliary stack. While there is still an element on the stack, the IP keeps doing its thing. Once everything has been shifted to the auxiliary stack (and reversed in the process), the IP keeps moving East instead, entering the last loop:

```
       \{@
       #!

```

`\` prints a linefeed again, `{` moves an item from the auxiliary stack back to main. If that was still an item of the list, it will be positive, and the IP turns South, where the item is printed with `!`. Then `#` pushes the stack depth (and now this is where the initial `_` is important, because this `#` ensures a positive stack depth), so that the IP still turns right, through the `\` and `{` again.

After we've printed everything, `{` pulls a zero from the bottom of the auxiliary stack, the IP continues East, and `@` terminates the program.
> 9 votes

# Answer
# MATLAB, 24

```
@(x)x([1:2:end 2:2:end])

```

similar to the python one.

Thanks @LuisMendo for saving 2 bytes!
> 8 votes

# Answer
# Haskell, 37 bytes

```
concat.foldr(\x[l,r]->[x:r,l])[[],[]]

```

Try it online!

The `foldr` recursively builds up the even list and odd list. Prepending an element to the list is updated by prepending it to the odd list and calling it the new even list, and calling the previous even list the new odd list. Then, the pair `[l,r]` is concaternated to `l++r`.

Thanks to Ørjan Johansen for saving 5 bytes using two-element lists in place of tuples.

---

**42 bytes:**

```
f l=[x|p<-[even,odd],(i,x)<-zip[0..]l,p i]

```

Adds indices to the list `l` and filters either the even or the odd ones.

---

```
g(a:_:l)=a:(g l)
g l=l
f l=g l++(g$drop 1 l)

```

Yet another format, for 44. The function `g` takes every even-indexed element. The odd indices are gotten by first dropping an element, then applying `g`. If `l` was guaranteed non-empty, we could safely just do `tail` for 41

```
g(a:_:l)=a:(g l)
g l=l
f l=g l++g(tail l)

```
> 7 votes

# Answer
## J, 8 bytes

```
/:0 1$~#

```

This is a monadic (one-argument) verb, used as follows:

```
  (/:0 1$~#) 110 22 3330 4444 55555 6
110 3330 55555 22 4444 6

```

## Explanation

```
/:        Sort the input array according to
  0 1     the array 0 1
     $~   repeated enough times to be of length
       #  length of input

```
> 5 votes

# Answer
## PowerShell v3+, ~~75~~ ~~67~~ ~~49~~ 47 bytes

```
$l=,@()*2
$args|%{$l[($f=!$f)]+=$_}
$l[0]
$l[1]

```

Try it online!

Expects input via splatting, as shown on the TIO link.

Creates an matrix `$l` as an array of arrays, then pipes the input `$args` into a loop `|%{}`. Each time through the loop, we add an element to one of the two child arrays of `$l` by flip-flopping the `$f` variable using Boolean logic. The first time through, `$f` is `$null`, the `!` of which is `$true`, or `1` when indexing into an array. This means the first element gets put into the second array of `$l`, so that's why `$l[1]` gets output first.

*Props to TessellatingHeckler for the golfing assistance and this variation.*
*-2 bytes thanks to mazzy.*

---

### Caveats

Going strictly as the question is written, this is technically invalid, as PowerShell doesn't have a concept of "lists" as pseudo-immutable objects, only arrays or hash tables (aka dictionaries). So, I'm treating the question's line "*Use most natural representation for lists that your language has*" as asking about arrays, as that's the closest PowerShell has. Additionally, output is one element per line, since that's the default PowerShell way to write out an array. This means an input of `(0,1,2,3,4)` will output `0\r\n2\r\n4\r\n1\r\n3\r\n`.
> 5 votes

# Answer
# Jelly, ~~4~~ 3 bytes

```
ŒœF

```

Try it online!

## How it works

```
ŒœF - Main link. Argument: L (a list) e.g.
Œœ  - Odd-even; Group elements at even and odd indices
  F - Flatten

```
> 5 votes

# Answer
# F#, ~~79~~ ~~77~~ 56

```
fun x->List.foldBack(fun x (l,r)->x::r,l)x ([],[])||>(@)

```

Based on one of the Haskell answer

```
fun x->x|>List.indexed|>List.partition(fst>>(&&&)1>>(=)0)||>(@)|>List.map snd

```

We first index the list, then partition it with criteria : first item (the index) anded with 1 equal 0.
That gives us a pair of list of pairs ; first list will contains all indexed evens and the other the indexed odds.
From that we reassemble the two list with append operator and finally discard the index.

*Edit : missed an obvious one there is no need to name the arg "xs" (habits) so can reduce to a 1-letter name*

---

I also have a potential 76 bytes one which is basically the same one but defined as function composition. Problem is it doesn't compile **as a value** but will effectively work with any list argument given so unsure if it's ok or not :

```
List.indexed>>List.partition(fst>>(&&&)1>>(=)0)>>fun(e,o)->e@o|>List.map snd

```

---

*Note: List.indexed is only available from F#4.0 despite not being documented in MSDN yet*
> 4 votes

# Answer
# JavaScript (ES6), 52 bytes

It also does it in one pass

```
x=>x.map((v,i)=>x[(i*=2)>=(z=x.length)?i-z+--z%2:i])

```

```
F=x=>x.map((v,i)=>x[(i*=2)>=(z=x.length)?i-z+--z%2:i])

input.oninput = setValue;

function setValue() {
  var arr = input.value.match(/\d+/g) || [];
  unsorted.innerHTML = arr.join(', ');
  sorted.innerHTML = F(arr).join(', ');
}

setValue();
```

```
* {
  font-family: monospace
}

th {
  text-align: right;
  padding-right: 0.5em;
}
```

```
<input id="input" type="text" value="0 1 2 3 4 5 6"/>
<hr/>
<table>
  <tr>
    <th>Unsorted:</th>
    <td id="unsorted"></td>
  </tr>
  <tr>
    <th>Sorted:</th>
    <td id="sorted"></td>
  </tr>
</table>
```
> 4 votes

# Answer
# convey, 16 bytes

```
{
"\`0
|@&;`}
2}

```

Try it online!

Get the input `{` at the top, copy `"` down and left. The list mod `|` 2 chooses `@` if the elements go down straight into the output `}` or right into the queue `&`. After the last element has passed through `\`, the length `n` of the list gets pushed to `:`, where `n` elements from the queue then gets passed through.
> 4 votes

# Answer
# Julia, 23 bytes

```
i->i[[1:2:end;2:2:end]]

```
> 3 votes

# Answer
## Perl 6, 25 bytes

This is the shortest lambda I could come up with.

```
{|.[0,2...*],|.[1,3...*]} # 25 byte "Texas" version
{|.[0,2…*],|.[1,3…*]}     # 25 byte "French" version

```

```
say {|.[0,2…*],|.[1,3…*]}( ^5 ); # (0 2 4 1 3)␤

say ((0..4),('m'..'q'),(5..9)).map: {|.[0,2…*],|.[1,3…*]}
# ((0 2 4 1 3) (m o q n p) (5 7 9 6 8))␤

# bind it as a lexical sub
my &foo = {|.[0,2…*],|.[1,3…*]}

say foo [110, 22, 3330, 4444, 55555, 6]; # (110 3330 55555 22 4444 6)␤

say [~] foo 'a'..'z' # acegikmoqsuwybdfhjlnprtvxz␤

```
> 3 votes

# Answer
# Japt, 3 bytes

```
ñÏu

```

Try it

```
ñÏu     :Implicit input of array
ñ       :Sort by
 Ï      :Passing the 0-based index of each through a function
  u     :  Modulo 2 of index

```

---

```
ó c

```

Try it

```
ó c     :Implicit input of array
ó       :Split into 2 arrays of every 2nd item
  c     :Flatten
        :Implicit output

```
> 3 votes

# Answer
# Husk, 4 bytes

```
ΣTC2

```

Try it online!

```
  C2    # split list into 2-element sublists
 T      # transpose
Σ       # flatten list of lists

```
> 3 votes

# Answer
# Perl 5 `-p`, 30 bytes

```
s/\S+\K( \S+)( ?)/$\.=$1;$2/ge

```

Try it online!

Input and output are space separated.
> 3 votes

# Answer
# 05AB1E, 2 bytes

```
ι˜

```

Try it online!

## How it works

```
ι˜ - Program. Push the input L to the start
ι  - Uninterleave L
 ˜ - Flatten

```
> 3 votes

# Answer
# K (ngn/k), 21 bytes

```
{t,x^t:x@&(0=2!)'!#x}

```

Try it online!

*Down 2 bytes thanks to ngn*

# K (ngn/k), 23 bytes

```
{t:x@&(0=2!)'!#x;t,x^t}

```

Try it online!

The old solution is kept because of the explanations.

Explanations:

```
{t:x@&(0=2!)'!#x;t,x^t}  Main function. Takes x as input
             !           Create a range from 0 to
              #x         Length of x - 1
            '            For each number in the range (i)
      (    )             Check if
         2!              i mod 2
       0=                is equal to 0
     &                   Where (get indices of truthy values)
   x@                    x at each indices
 t:             ;        Assigned to variable t
                 t,      t concat with
                   x^t   x without the elements in t

```
> 3 votes

# Answer
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
fy

```

Try it online!

```
fy
 y # Uninterleave
f  # Flatten

```
> 3 votes

# Answer
# Perl, ~~35~~ 33 bytes

```
perl -ape 'push@{$|--},$_ for@F;$_="@0 @1"'

```

31 bytes + 2 bytes for `-ap`. Reads a space-delimited string from STDIN:

```
$ echo 0 1 2 3 4 | perl -ape 'push@{$|--},$_ for@F;$_="@0 @1"'
0 2 4 1 3

$ echo 110 22 3330 4444 55555 6 | perl -ape 'push@{$|--},$_ for@F;$_="@0 @1"'
110 3330 55555 22 4444 6

```

When the input is empty, prints a single space, which I would consider equivalent to an empty list. If not, can be fixed at a cost of 4 bytes with:

```
perl -anE 'push@{$|--},$_ for@F;$,=$";say@0,@1'

```

(requires Perl 5.10+, prints a trailing newline)

or at a cost of 5 bytes with:

```
perl -ape 'push@{$|--},$_ for@F;$_=join$",@0,@1'

```

(no trailing whitespace)

## How it works

This solution uses the `-a` flag, which splits the input on whitespace and puts the results in the `@F` array.

The real magic happens in the `push`:

```
push@{$|--},$_

```

The `$|` variable is normally used to force output flushing, but it has another interesting property: when decremented repeatedly, its value toggles between 0 and 1.

```
perl -E 'say $|-- for 0..4'
0
1
0
1
0

```

Taking advantage of the fact that there are no restrictions on identifiers specified via symbolic dereferencing, we alternately push array elements onto the `@0` and `@1` arrays, so `@0` ends up with all the even-indexed elements and `@1` with the odds. Then we simply concatenate the stringified arrays to get our output.
> 2 votes

# Answer
## Mathematica, 40 bytes

```
#[[;;;;2]]~Join~If[#=={},#,#[[2;;;;2]]]&

```

`{}[[2;;;;2]]` will throw an error.
> 2 votes

# Answer
## Burlesque, 12 Bytes

```
J2ENj[-2EN_+

```

Usage as in:

```
blsq ) {0 1 2 3 4}J2ENj[-2EN_+
{0 2 4 1 3}
blsq ) {110 22 3330 4444 55555 6}J2ENj[-2EN_+
{110 3330 55555 22 4444 6}

```

**Explanation:**

```
J     -- duplicate
2EN   -- every 2nd element
j     -- swap
[-    -- tail
2EN   -- every 2nd element
_+    -- concatenate parts

```

Although once the new update is released you can do this with the new *Unmerge* built-in (which does the opposite of the merge `**` built-in):

```
blsq ) {110 22 3330 4444 55555 6}J2ENj[-2EN**
{110 22 3330 4444 55555 6}

```
> 2 votes

# Answer
# K, 10 bytes

```
{x@<2!!#x}

```

Based on the 5-byte Pyth answer.
> 2 votes

# Answer
## C, 70

Nothing special, just a index mapping function.

```
a=0;main(int c,int** v){for(c--;a<c;)puts(v[1+a*2%c+!(a++<c/2|c%2)]);}

```

**Less golfed**

```
a=0;
main(int c, int** v) {
  for(c--; a<c;)
    puts(v[1 + a*2%c + !(a++ < c/2 | c%2) ]);
}

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 11 bytes

```
{⍵[⍒2|⍳≢⍵]}

```

Alternatively:

```
{⍵[⍒≠\=⍨⍵]}

```

Try it online!

Explanation:

```
{⍵[⍒2|⍳≢⍵]}
      ⍳≢⍵       ⍝ indices from 1 to the length of the input vector.
    2|          ⍝ their divisibility by two; essentially generate 1 0 1 0...
   ⍒            ⍝ grade down: put odd indices first before even indexed indices.
 ⍵[      ]      ⍝ pick from the input

```
> 2 votes

# Answer
# JavaScript, 49 bytes

```
n=>[...(x=f=>n.filter((a,b)=>b%2==f))(0),...x(1)]

```

Explanation: Creates a list composed of the results of spreading arrays filtered by the index of each element modulo 2.
> 2 votes

# Answer
# Ruby, ~~53~~ ~~36~~ 30 bytes

```
->a{i=0
a.sort_by{[i%2,i+=1]}}

```

Attempt This Online!

## Ruby, 24 bytes

This appears to work but could fail *in theory* because "the ordering of equal elements is indeterminate and may be unstable." Sorting by `[i%2,i+=1]` above solves this instability.

```
->a{i=1
a.sort_by{i^=1}}

```

Attempt This Online!
> 2 votes

# Answer
# Vyxal, 3 bytes

```
y"f

```

Try it Online!

Uninterleave, pair the results and flatten
> 2 votes

# Answer
# JavaScript (Node.js), 47 bytes

```
x=>f=i=>1/x[i|i]?[x.splice(i,1)[0],...f(-~i)]:x

```

Try it online!

# JavaScript (Node.js), 50 bytes

```
x=>(i=a=[]).concat(x.filter(v=>i++%2||!a.push(v)))

```

Try it online!

Not shortest now but fun
> 2 votes

# Answer
# Elm, 78 bytes

```
g x y i z=case(z,i)of
 (a::b,_)->g(y++[a])x(1-i)b
 (_,0)->x++y
 _->y++x

```

```
g[][]1

```
> 2 votes

# Answer
# Pyth, 8 bytes

```
+%2Q%2tQ

```

Relatively simple
> 1 votes

# Answer
# Vitsy, 22 Bytes

Vitsy *really* wasn't made to do this...

```
r' 'Vl2/\[N{VO]l\[NVO]
r                       Reverse the implicit numerical input stack.
 ' 'V                   Save the "space" character as a global final variable.
     l2/\[....]         Repeat the stuff in the brackets the length of the input
                        stack divided by 2.
          N{VO          Output the top item of the stack as a number, then shift
                        the stack over once to the left, push a space, output it.
               l\[...]  For the rest of the stack, repeat that many times...
                  NVO   Output the top item of the stack as a number separated
                        by a space.
```
> 1 votes

# Answer
## Minkolang 0.12, 15 bytes

```
$nI2:[i1+g]r$N.

```

Try it here.

### Explanation

```
$n                 Read in all of input as numbers
  I2:              The length of the stack divided by 2 (n)
     [             Open for loop that repeats n times
      i1+          Loop counter + 1
         g         Gets the (i+1)th item from the stack and puts it on top
          ]        Close for loop
           r       Reverse the stack (for outputting)
            $N.    Output the whole stack as numbers and stop.

```
> 1 votes

# Answer
# Clojure/ClojureScript, 52 bytes

```
(defn f[l](flatten(map #(take-nth 2 %)[l(rest l)])))

```

Written in a ClojureScript REPL, should also be valid Clojure.
> 1 votes

# Answer
# , 12 chars / 22 bytes (noncompetitive)

```
Ѩťᶏש,Ѩą(ï,2⸩

```

`Try it here (Firefox only).`

Just switched to Lodash, which has way more functions. Thus, this answer is rendered noncompetitive.
> 1 votes

# Answer
## R, 49 bytes

```
q<-function(x)c(x[seq(x)%%2==1],x[seq(x)%%2==0])

```

Call it as q(blah). Or, if x already contains the list to be rearranged, then

```
c(x[seq(x)%%2==1],x[seq(x)%%2==0])

```

is just 35 bytes.
> 1 votes

# Answer
# F#, 64

```
fun x->List.mapi(fun i l->l,i%2)x|>List.sortBy snd|>List.map fst

```

Inspired by Sehnsucht's answer (but not enough rep to comment).

Maps each value to a tuple where the second entry is the modulo of the list index, sorts by modulo, then maps back to the original value.
> 1 votes

# Answer
# Prolog, 103 bytes

```
r([E,O|T],[E|A],[O|B]):-r(T,A,B).
r([],[],[]).
r([E],[E],[]).
p(L):-r(L,A,B),append(A,B,X),write(X).

```

**Example**

```
>p([1,2,3,4,5]).
[1,3,5,2,4]

```
> 1 votes

# Answer
# Hassium, 191 Bytes

This one was pretty long :(
It reads the array from args, so run this with `hassium file.has 0 1 2 3 4`

```
func main(){a=args;e,o=[]for(c=0;c<a.length;c++)if(c%2==0)e.add(a[c])else o.add(a[c])print("["+(e+o).toString().replace("{", "").replace("}", "").replace("Array", "").replace("  ", "")+"]");}

```

Run and see expanded with test case here
> 1 votes

# Answer
# Go, 92 bytes

```
func s(l []int) (r []int){for i:=0;i<len(l)*2;i+=2 {r=append(r,append(l,l...)[i])};return}

```

"Go. at least it's shorter than prolog"

degolf

```
func s(l []int) (r []int){
   for i:=0;i<len(l)*2;i+=2 {
      r=append(r,append(l,l...)[i])
   }
   return
}

```
> 1 votes

# Answer
# bash and GNU coreutils, 68 bytes

We assume that the list is newline-separated and passed on standard input.

```
(paste - <(seq 0 5 9999)|tee x|grep 0$;grep 5$<x)|cut -f1|grep -v ^$

```

Unfortunately this will ignore any inputs beyond index 1999, so it doesn't quite meet the spec.

It also clobbers a hardcoded temporary file ('x'), which could be problematic if run in parallel, and it doesn't remove it afterwards. Sorry about that!
> 1 votes

# Answer
# PHP, ~~78~~ 69 bytes

PHP can chunk and slice, but not interleave arrays; that makes this a bit bulky:

```
function(&$a){while($i++<count($a)>>1)$a[]=array_splice($a,$i,1)[0];}

```

Call by reference or try it online.

---

first approach (programs for 78 bytes):

```
for(;++$i<$argc;)echo",",$argv[$i++];for($i=1;++$i<$argc;)echo",",$argv[$i++];

```

prints a leading comma; insert `[!$i]` before the first`$argv` to remove it.

Two other 78 byte solutions (print a leading and a trailing comma):

```
for($n=$argc-2|1;++$i<$argc*2;)$i&1?print",".$argv[$i]:$argv[$n+=2]=$argv[$i];
for($n=$argc-2;++$i<$argc*2;)$i&1?print",".$argv[$i]:$argv[1|$n+=2]=$argv[$i];

```

Run with `php -nr '<code>' <arguments>` or try them online
> 1 votes

# Answer
# C# 7.3, 100 bytes

```
List<int> M(List<int> x)=>x.Select((y,i)=>(y,i)).GroupBy(y=>y.i%2,y=>y.y).SelectMany(y=>y).ToList();

```

This is pretty much idiomatic for C#, but I don't think a non-idiomatic solution would be much shorter.
> 1 votes

# Answer
# Factor, 34 bytes

```
[ dup <evens> swap <odds> append ]

```

Try it online!

It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence on the data stack as output. It rips out the even indices into a sequence, rips out the odd indices into a sequence, and smushes them back together. `[ 2 group flip concat ]` works for sequences of even length, but `flip` can only transpose square matrices correctly.
> 1 votes

# Answer
# Go, ~~97 96~~ 91 bytes, idiomatic

```
func(L[]int)(E,O[]int){for i,e:=range L{if i%2<1{E=append(E,e)}else{O=append(O,e)}}
return}

```

Attempt This Online!

Because Go supports multiple return values, this returns 2 lists, the even-indexed elements and the odd-indexed elements.

* -1 byte: `==0` into `<1`
* -5 bytes: return values share a type

### Go, 96 bytes, generic

```
func f[T any](L[]T)(E,O[]T){for i,e:=range L{if i%2<1{E=append(E,e)}else{O=append(O,e)}}
return}

```

Attempt This Online!

# Go, ~~122~~ 114 bytes (literal interpretation)

```
func(L[]int)[]int{var E,O[]int
for i,e:=range L{if i%2<1{E=append(E,e)}else{O=append(O,e)}}
return append(E,O...)}

```

Attempt This Online!

This longer solution merges the filtered lists into a single list.

* -8 bytes: `E` and `O` share the same type
> 1 votes

# Answer
# Rust 109 bytes

```
fn f(x:Vec<u8>)->Vec<u8>{x.iter().cloned().step_by(2).chain(x.iter().cloned().skip(1).step_by(2)).collect()}

```

"at least it's shorter than C#"
> 1 votes

# Answer
# Arturo, 27 bytes

```
$=>[i:0arrange&=>[i%2'i+1]]

```

Try it
> 1 votes

# Answer
# Thunno, \\$ 3 \log\_{256}(96) \approx \\$ 2.47 bytes

```
ZlS

```

Attempt This Online!

#### Explanation

```
ZlS  # Implicit input
Zl   # Uninterleave
  S  # Sum (acts as flatten
     # for nested lists)
     # Implicit output

```
> 1 votes

# Answer
# Java 8 (OpenJDK 8), 70 bytes

Pretty much straightforward in Java

```
l->{for(int i=1;i<=l.size()/2;l.remove(i++))l.add(l.get(i));return l;}

```

Sadly not golfable using only streams because index isn't easily accessible from inside, and conversion from stream to list is still a pain until Java 16

Try it online!
> 1 votes

# Answer
# Zsh, 34 bytes

```
for i j;a+=($i) b+=($j);echo $b $a

```

Try it online!. Note that arrays in Zsh are 1-indexed, that's why the output appears backwards from the example given. If the requirement for "even" indices first is relaxed, and the order of outputs is more important, just switch `$a` and `$b`
> 1 votes

# Answer
# Haskell + hgl, 8 bytes

```
mp<$%uak

```

Attempt This Online!

## Explanation

* `uak`: splits a list into even and odd indices
* `mp`: "Monoidal action", concatenates two lists
* `(<$%)`: Uncurry compose, this composes a curried two argument function like `mp` with a function that returns a tuple like `uak`.

## Reflection

I'm pretty happy with this. Really glad to have `(<$%)` and `uak` is proving to be quite useful. It is worth considering if either or both of these deserve a "promotion" to a smaller byte count.
> 0 votes

# Answer
# JavaScript (Node.js), 49 bytes

After a few fails it finally works, but is now longer than expected :-/

```
t=>t.map((_,i)=>t[(i*2-1)%((l=t.length)+~l%2)+1])

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `S`, 1 byte

```
z

```

Attempt This Online!

#### Explanation

```
    # Implicit input
z   # Uninterleave the input into two pieces
    #   e.g.  [1,2,3,4,5,6]  ->  [[1,3,5], [2,4,6]]
    #   e.g.  [0,1,2,3,4]    ->  [[0,2,4], [1,3]]
    # S flag takes the sum of this list
    #  i.e. flattens the nested list
    #   e.g.  [[1,3,5], [2,4,6]]  ->  [1,3,5,2,4,6]
    #   e.g.  [[0,2,4], [1,3]]    ->  [0,2,4,1,3]
    # Implicit output

```
> 0 votes

---
Tags: code-golf, array
---


title: Average of your code

text:
# Question
Title: Average of your code
Inspired by this

# Task

Your task is to output the average character of your code.

## What is an average character?

Say we have a string `golf()`. We then take the ASCII value of each separate symbol, so our string is `103 111 108 102 40 41`, and calculate the average of those values, rounded to an integer. In our case the average is `505 / 6 = 84.1666... = rounded to 84`. That value is printed out as an ASCII character, in our case `T`.

# Rules

You must take no input and must not read the source code directly, while outputting the average character of its source code. Integers are rounded by function `floor(x+0.5)`. Empty programs are not allowed. This is code-golf, so lowest byte count wins!

# Answer
> 23 votes
# ///, 1 byte

```
A

```

Try it online!

As it is 1 byte, simply outputting the source code gives the average. `///` just outputs the source code unchanged if it doesn’t contain any `/` characters, so almost any ASCII character works in place of `A`

# Answer
> 23 votes
# Unreadable, 111 bytes

> '"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""

Try it online! or Check average

Note that the average character is `$` and does not appear in the source code, which contains only 37 `'`s and 74 `"`s.

# Answer
> 18 votes
# Malbolge, 17 bytes

```
(=<;:9876543210TA

```

Try it online!

Test the code average

Explanation:

```
(=<;:9876543210TA

(                    Copies the value pointed by register d to register d.
                     (d = 0 so it copies the '(' ASCII value)
 =<;:9876543210      Succesive calls to the crazy operation to update the value
                     in register a until the value stored meets the code average
               T     Prints the value in a
                A    Ends the program

```

Luckily this time we don't need to cope with Malbolge's code encryption feature.

# Answer
> 15 votes
# HQ9+ Family, 1 bytes

```
Q

```

Believe it or not, there are challenges can be solved by HQ9+ in 2020.

# Answer
> 14 votes
# Python 2, 8 bytes

```
print"Y"

```

Try it online!

Average Character Verified

# Answer
> 13 votes
# APL (Dyalog Unicode) and lots of other languages and REPLs, 1 byte

```
4

```

Try it online!

---

However, more interesting is:

```
''''

```

Which actually evaluates to the single quote. Try it online!

# Answer
> 12 votes
# brainfuck, 15 bytes

```
+[+++++>+<]>++.

```

Try it online!

Requires an 8 bit interpreter as it uses modulo 256 arithmetic.

Average is 53.4. Outputs `5` which is character 53.

# Answer
> 8 votes
# COW, ~~11~~ 8 bytes

```
BOOM!!

```

Try it online! or verify the average.

Explosively prints `0` (average 48.375), using the fact that all non-instructions (`B`, `!!`, and the two newlines) are no-ops.

### 6 bytes

I'm retaining the 8-byte version above because it's my favourite, but here's a 6-byter thanks to @JoKing:

```
OOM!

```

(Note the code ends with two tabs.) Also prints `0` (average 47.66...).

And here's another, with an average of exactly 48:

```
OOM!

```

---

# COW, ~~87~~ 78 bytes

```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMOOMMMMOOmoOMoOmOoMOomooMMMMOomoomoOMoo

```

Try it online! or verify the average.

No no-ops this time. Prints `[` (average 90.54...) by counting up to 91.

### Commented

```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO    push 13 to first memory block
MOO        begin outer loop
  MMM      copy value to register
  MOO      begin inner loop
    moO    switch to second memory block
    MoO    increment
    mOo    switch to first memory block
    MOo    decrement
  moo      end inner loop
  MMM      paste register value into first memory block
  MOo      decrement
moo        end outer loop
moO        switch to second memory block
Moo        print as ASCII character

```

# Answer
> 5 votes
# , 8 bytes

```
cat("B")

```

Try it online! or Check average

or

```
cat('C')

```

Try it online! or Check average

Also,

```
cat(8)

```

(with 2 null bytes) doesn't work on TIO, but works in RStudio on my Kubuntu machine.

Try it online! or Check average.

# Answer
> 5 votes
# Pyramid Scheme, 29 bytes

```
   ^
  / \
 /out\
^-----
-

```

Try it online!

This has an average of ~48.137, so this outputs `0`.

If we're allowed a trailing newline, then we can get 4 bytes

```
^,
-

```

Try it online!

Again, this outputs `0`, but by printing the return of the pyramid, which has an extra newline

# Answer
> 5 votes
# cat, 1 byte

```
a

```

If your challenge can be competitively solved with `cat`, there is probably something wrong with the challenge.

# Answer
> 4 votes
# Retina 0.8.2, 1 byte

```
0

```

Try it online! Works by counting the number of `0`s in the input. This can of course be extended to any arbitrary number of bytes just by repeating the number of `0`s, or substituting other characters which happen to have an average byte value of `0`, e.g. `.2`, as long as the result remains a valid regular expression that doesn't match the empty string.

Without using a Match (count) stage, I think the minimum possible is 3 bytes:

```
^
4

```

This program outputs `4`, whose ASCII code `52` is the average of `94` (for `^`) and `10` (for the newline).

# Answer
> 4 votes
# Lost, ~~19~~ ~~13~~ 11 bytes

```
v<<<<
>%(9@

```

-6 bytes thanks to *@JoKing*.

The average is 57.090..., which will be rounded to 57 (character `'9'`).

Try it online or verify that it's deterministic.

### Explanation:

**Explanation of the language in general:**

Lost is a 2D path-walking language. Most 2D path-walking languages start at the top-left position and travel towards the right by default. Lost is unique however, in that ***both the start position AND starting direction it travels in is completely random***. So making the program deterministic, meaning it will have the same output regardless of where it starts or travels, can be quite tricky.

A Lost program of 2 rows and 5 characters per row can have 40 possible program flows. It can start on any one of the 10 characters in the program, and it can start traveling up/north, down/south, left/west, or right/east.

In Lost you therefore want to lead everything to a starting position, so it'll follow the designed path you want it to. In addition, you'll usually have to clean the stack when it starts somewhere in the middle.

**Explanation of the program:**

All arrows will lead the path towards the leading `>` on the second line. From there the program flow is as follows:

* `>`: travel in an east/right direction
* `%`: Put the safety 'off'. In a Lost program, an `@` will terminate the program, but only when the safety is 'off'. When the program starts, the safety is always 'on' by default, otherwise a program flow starting at the exit character `@` would immediately terminate without doing anything. The `%` will turn this safety 'off', so when we now encounter an `@` the program will terminate (if the safety is still 'on', the `@` will be a no-op instead).
* `(`: Pop the top value, and push it to the scope. This is basically used to make the stack empty if we started somewhere in the middle.
* `9`: Push a `9`
* `@`: Terminate the program if the safety is 'off' (which it is at this point). After which all the values on the stack will be output implicitly. So it'll output the `9` for the average character of unicode `57`.

# Answer
> 4 votes
# Perl 5 \+ `-M5.10.0`, 67 bytes

I know this isn't the shortest, but I think it's what OP was after.

```
$_=q{$_="\$_=q{$_};eval";$-+=ord for/./g;say chr(.5+$-/y///c)};eval

```

Try it online!

# Answer
> 4 votes
# MATLAB... and MS-DOS and Bash? 7 bytes

```
!echo P

```

Outputs `P`. Length verification

---

*First post here.*

I thought this was going to be easy with MATLAB, as you can just enter a single digit number and it will return that as-is. Except that MATLAB prints more than just the number back out...

```
>> 0
ans =
     0

```

Same goes for strings.

```
>> 'a'
ans =
    'a'

```

Now I might've just waved my hands and said good enough, but where's the fun in that? :)

The only methods I knew of, that can print something to console without the extra `ans =`  would be to use the `fprintf()` or `disp()` functions.

**12 Bytes**.

```
>> fprintf('T')
T

```

**9 Bytes**. *Note, `Disp(0)` and other single-digit variations will not work due to average length constraint.*

```
>> disp('J')
J

```

These two are valid submissions, but I kept wondering... *Can I do better?*

Then I learned I could send commands to the operating system with the Shell Escape Function. i.e. `!COMMAND`

*Except the command is sent to whatever operating system that machine is running on.* Since MATLAB is available for both Windows and Unix, whatever command I choose needs to work on both; ensuring that my code runs on all machines.

This more or less locked me to the single command; `echo`. *(Kinda anti-climactic, really)*

A few trials and error with the output character, and I converged to the final answer. **7 Bytes**.

```
>> !echo P
P

```

---

*I really hope this isn't breaking any rules here...*

# Answer
> 3 votes
# MAWP 0.1, 3 bytes

```
99:

```

Outputs 9. Works because `:` and `9` are neighbours in the table, so `9:` gives a value thats in between them, so adding another `9` guarantees that the average corresponds to `9`

# Answer
> 3 votes
# Backhand, 6 bytes

```
"o@7"

```

Try it online!

## Explanation

```
"  7   Start a quote, then the character 7
 o  "  (backwards) End a quote, output the character
  @    Stop the program + no-op.

```

# Answer
> 3 votes
# Hexagony, 3 bytes

```
0!@

```

Try it online! or Check the average character

## Explanation

```
0     Set current memory edge to 0
 !    Output current memory edge as a number
  @   Terminate the program

```

# Answer
> 3 votes
# SuperMarioLang, 2 bytes

```
:%

```

Try it online!

A simple answer in SuperMarioLang. The only command that gets executed is `:` which prints the value of the currently pointed memory position (0) as a number (initially 0). The second command `%` never gets executed as Mario (the command pointer) falls because there is no floor under him, so the program stops. The average between `:` and `%` is `0`.

Also works in MarioLANG, where `%` is just interpreted as a comment.

# Answer
> 3 votes
# Java (JDK), 4 bytes

```
A->9

```

Try it online!

Outputs the number `9` which as a character is the average character of the code.

Defined as a `int f(Void v)`. Note that `Void` is an accepted argument type for "no input" challenges.

If an `int` isn't an acceptable output for this challenge, the following is most definitely valid, for an extra byte.

```
A->56

```

Try it online!

Outputs `8` which is the average character.

Defined as a `char f(Void v)`. I was surprised that no casting to `char` was required, but it beats `v->';'` by one byte.

# Answer
> 3 votes
# Python 3, 10 bytes

```
print("N")

```

Try it online!

# Answer
> 3 votes
# Ruby, 6 bytes

```
$><<?8

```

average is 56.16

```
$ cat mean.rb
$><<?8
$ ruby mean.rb
8
$ python -c "[print(chr(int(0.5 + sum([ord(c) for c in s])/len(s)))) for s in [l.strip() for l in open('mean.rb')]]"
8

```

# Answer
> 2 votes
# JavaScript (Browser), 10 bytes

```
alert('M')

```

Try it online!

# Answer
> 2 votes
# Befunge-93, 5 3 bytes

```
.@!

```

Try it online!

`.@` prints `0`. `!` was added so the average is `47.667`, which rounds to `48`, which is the ASCII code for `0`.

# Answer
> 2 votes
# SQLite, 9 bytes

```
SELECT"@"

```

Try it online!

# Answer
> 2 votes
# brainfuck, 16 bytes

Outputs `6`, the average of the program.

```
-[>+<-----]>+++.

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 5 bytes

```
()=>3

```

Try it online!

# Answer
> 2 votes
# AlphaBeta, 10 bytes

```
edaaaaaCLz

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 1 byte

```
0

```

Or any other single digit.

Try it online.

# Answer
> 2 votes
# Z80Golf, 4 bytes

```
00000000: 3e 91 ff 76

```

Try it online!

This is `ld a, 0x91``rst 0x38` (putchar) → `halt`.

It prints a single `0x91` byte, and `(0x3e + 0x91 + 0xff + 0x76) / 4 = 0x91`.

# Answer
> 2 votes
## Batch, 7 bytes

```
@echo U

```

I used the average character calculator to calculate the average of `@echo`  (with trailing space) and just appended the result, as that won't change the average.

# Answer
> 2 votes
# ArnoldC, 59 bytes

```
IT'S SHOWTIME
TALK TO THE HAND "A"
YOU HAVE BEEN TERMINATED

```

Try it online!

Test the average

Mandatory answer in ArnoldC. New line characters have been added to the average as a single character of value 10.

# Answer
> 2 votes
# PowerShell, 1 byte

```
0

```

Try it online!

This will work with every single digit. It just gets echoed.

# Answer
> 2 votes
# Vim, 2 bytes

```
ii

```

Try it online!

# Answer
> 2 votes
# Lenguage, 4 bytes

```
����
```

Is this the first time where a lenguage program is totally written?

# brainfuck, 14 bytes

```
+[+++++>+<]>.�
```

Try it online!

Forcefix average

# Answer
> 2 votes
# vim, 3 bytes

Four versions; one for each of the "insert on the same line" commands: `A`, `a`, `i`, and `I`:

* `A.<ESC>`
* `a><ESC>`
* `iB<ESC>`
* `I2<ESC>`

`<ESC>` is 0x1b.

(We can shave off a byte if we're willing to terminate while still in insert mode.)

Try it online! (For the `A.<ESC>` variant)

# Answer
> 2 votes
# Sandwich, 2 bytes

```
pp

```

Sandwich is comprised of opcodes. The first letter of each line is the opcode, and the rest of the line is the arguments.

The opcode for this code is `p`, which means `print`. The arguments are also `p`, which is passed to the opcode.

The result of this code is that it prints out `p`, AKA ASCII 112.

Since the code is 2 bytes long, simply using the same two characters will give the average of the entire code segment.

# Answer
> 2 votes
# Plumber, 191 bytes

```
[]
]
]
...88 more ']'...
]
]
][[=

```

Try it online!

Drops a packet down, which is incremented up to 92 and printed. 92 is the ASCII value for `\`.

# Answer
> 1 votes
# perl -Mfeature=say, 6 bytes

```
say"P"

```

Try it online!

I wrote a small program to find the program above:

```
#!/opt/perl/bin/perl

use 5.028;

use strict;
use warnings;
no  warnings 'syntax';

use experimental 'signatures';
use experimental 'lexical_subs';

for my $c (32 .. 127) {
    my $char = chr $c;
    my $s = qq [say"$char"];
    my $score = 0;
    $score += ord $_ for split // => $s;
    $score = int (.5 + $score / length ($s));
    if ($score == $c) {
        say $s;
    }
}

__END__

```

Try it online!

# Answer
> 1 votes
# Bash, 6 bytes

```
echo Y

```

Try it online!

```
echo Z

```

works as well.

Just like my Perl solution, this was found using a brute force search.

# Answer
> 1 votes
# AWK, 15 bytes

```
BEGIN{print"X"}

```

Try it online!

# Answer
> 1 votes
# , 1 byte

```
3

```

Try it online!

After the code cycles, **`3`** tries to output itself. However, **`3`** is an unnamed command, so it can't be directly outputted. Instead, it gets turned into `73`, which is outputted. `7` specifies the output format as "the same as the input", so the `3` after it prints `3`.

A more interesting solution:
# , 3 bytes (8 characters)

```
01116743

```

Try it online!

This outputs `3` as a number.

# Answer
> 1 votes
# naz, 8 bytes

```
8a9m7a1o

```

Short and sweet. Verify the average character here.

**Explanation**

```
8a9m7a # Set the register to a value of 79
1o     # Output once

```

# Answer
> 1 votes
# JavaScript (Node.js), 16 bytes

```
console.log('U')

```

Here's how I brute-forced the solution:

```
const average = str => String.fromCharCode([...str]
  .reduce((total, char) => (total += char
    .charCodeAt(0)) || total, 0) / str.length);

for (let i = 0; i < 2 ** 16; i++) {
  const char = String.fromCharCode(i);
  const avg = average(`console.log('${char}')`);
  char == avg && console.log({ code: i, char, avg });
  // { i: 85, char: 'U', avg: 'U' }
}
```

# Answer
> 1 votes
# 99, 22 bytes

```
99 99 9
99 99 9
9 99
9m

```

Try it online!

# Answer
> 1 votes
# T-SQL, 8 bytes

```
PRINT'D'

```

DB Fiddle

# Answer
> 1 votes
# SimpleTemplate, 10 bytes

This is a simple code that outputs the average character itself:

```
{@echo"X"}

```

The average was calculated previously using JavaScript:

```
var code = '{@echo"X"}';

var sum = code.split('').reduce((a,_)=>a+_.charCodeAt(0), 0);

document.body.innerHTML += String.fromCharCode(sum/code.length);
```

To get the right character, I just used a random one, until I got one where the result was the same (in this case, `"X"`).

The rules don't specify that the character can't be pre-calculated before. They only specify that you can't read the source code or that you can't take any input.

---

## SimpleTemplate, 1 byte

Just simply outputs the character average:

```
1

```

This generates a PHP echo (example below):

```
echo (<<<'DATA6229934543895a3c69912b6e6658160198d45280523b34711abdc124745'
1
DATA6229934543895a3c69912b6e6658160198d45280523b34711abdc124745
);

```

---

---

You can try both versions on: http://sandbox.onlinephpfunctions.com/code/36449dad6c5de136ae489bcbeaddd97a6a7124bc

You can change the line 1048 to test the desired code.

# Answer
> 1 votes
# Rust, 23 bytes

```
fn main(){print!("Q");}

```

Used modified Perl answer's script.

# Answer
> 1 votes
# Python 3, 11 bytes

```
print('K')#

```

The average value is 75.09, which rounds to 75 - `K`.

# Answer
> 1 votes
# PHP, 1 byte

```
A

```

Try it online!

This will just output itself. Works with almost all of the printable ASCII characters.

# Answer
> 1 votes
# Whitespace, 13 bytes

Outputs Data Link Escape (0x16)

I can't figure out how to put raw whitespace into a code block, so here you go:

```
[space][space][space][tab][space][tab][tab][space][lf]
[tab][lf]
[space][space]

```

Try it online

Explanation:

```
[space][space][space]           Push a number onto the stack
[tab][space][tab][tab][space]   Have that number be 22 (0x16)
[lf]                            End instruction
[tab][lf][space][space]         Output character from stack

```

# Answer
> 1 votes
# Ada (GNAT), 53 bytes

```
procedure GNAT.IO.F is begin Put("M"); end GNAT.IO.F;

```

Try it online!

Why not?

# Answer
> 1 votes
# C (gcc), 15 bytes

```
A(){return 84;}

```

Average is T. Returns ASCII code.

Try it online!

# Answer
> 1 votes
# \- 18 chars

```
main(){puts("S");}

```

# Answer
> 1 votes
# Scala, 10 bytes

```
print("N")

```

Online demo

# Answer
> 1 votes
# PowerShell, 3 bytes

```
+$A

```

Try it online!

`(43+36+65)/3 == 144/3 == 48 == ASCII('0')`

# Answer
> 1 votes
# bitch, 2 bytes

```
/1

```

Try it online! or verify the average.

Following up my COW answer with one in bitch . . . read nothing into that. Outputs `0` (average 48 exactly). `/` outputs the accumulator value (initialised to zero); `1` is a no-op here.

# Answer
> 1 votes
# Rust, 5 bytes

```
||'R'

```

Try it online, Verify

Straightforward solution, just a closure that implements `Fn() -> char`.

# Answer
> 1 votes
# MAWP v1.1, 6 bytes

```
33W/:.

```

I tried a different approach from Dion's answer.

Try it!, Verify

# Answer
> 1 votes
# 1+ (with NOP), 3 bytes

```
'1:

```

Try it online! Verify!

# 1+ (without NOP), 4 bytes

```
11+:

```

Try it online! Verify!

# Answer
> 1 votes
# Grok, 4 bytes

```
I[Wq

```

Characters are `73 91 87 113`. Average is `91`, which is `[`.

# Answer
> 1 votes
# Vyxal, 1 byte

```
0

```

Try it Online!

Any digit works.

Or, if you think that doesn't count,

```
\\

```

Try it Online!

`\` is a single-character string.

# Answer
> 1 votes
# Vyxal, 1 byte

```
7

```

Try it Online!

Somehow the average of this program turns out to be the luckiest number in universe

# Answer
> 1 votes
# Zsh, 5 bytes

```
<<< 5

```

Try it online!

# Answer
> 0 votes
# Gol\>\<\>, 3 bytes

```
`TH

```

Try it online! and Check the average character.

```
`T   Escape the char T and push its charcode to stack
  H  Print all values on the stack and halt

```

Found by making the template ``<any char>H` and repeating the average calculator until it converges.

# Answer
> 0 votes
# Io, 8 bytes

I feel that this is too boring to find...

```
"Y"print

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 4 bytes

```
" o;

```

Try it online!

Outputs `;` using a looping string literal.

# Answer
> 0 votes
# Pyth, 2 bytes

```
"!

```

ASCII value of " is 34, and ASCII value of ! is 33.

```
(33 + 34) / 2 = 33.5 = 33

```

Try it online!

# Answer
> 0 votes
# Keg, 1 byte

```
e

```

Try it online!

Haha. I'm not gonna be late to the party!

# Answer
> 0 votes
# Factor, 8 bytes

```
"Y"print

```

Try it online!

This actually works...................

# Answer
> 0 votes
# Ruby, 4 bytes

```

p 3

```

Try it online!

Adding a leading newline to lower the average from capital-letter land to digit land.

# Answer
> 0 votes
# Rexx (Regina), 5 bytes

```
SAY C

```

Try it online!

# Answer
> 0 votes
# MATLAB/Octave, 4 bytes

```
''''

```

Try it online!
Outputs single `'` character. And basically it's the way to write that as an immidiate value - the outer apostrofes are to indicate the value is char array so we're left with `''` which is escape code for a single apostrofe.

# Answer
> 0 votes
# Excel, 2 bytes

```
51

```

For once, there isn't some overly long Excel function to get in the way.

# Answer
> 0 votes
# Julia, 9 bytes

```
print(:W)

```

Try it online!

also works with

`:d|>print` Try it online!

# Answer
> 0 votes
# Thunno 2, 16 bytes

```
"DṘs+ĊmĊ"DṘs+ĊmĊ

```

Attempt This Online!

#### Explanation

```
"DṘs+ĊmĊ"DṘs+ĊmĊ  # Full program
"DṘs+ĊmĊ"         # String literal
         DṘ       # Duplicate and push the representation
           s+     # Prepend this to the original string
             Ċ    # Convert to charcodes (using Thunno 2 encoding)
              m   # Take the mean of this list
               Ċ  # Convert it back to a character (using Thunno 2 encoding)

```

Alternative (but boring) answers:

* **1 byte**: `0` (or any other number)
* **2 bytes:** `''` (a character literal)

---
Tags: code-golf, string, self-referential
---


# Question
Title: Be the First 1 (leave only the first Truthy)
### 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.

# Answer
# 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`.
> 36 votes

# Answer
# 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. Python 3 no longer allows `True` and `False` to be redefined, so this answer uses Python 2.

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`. See Kevin Cruijssen's answer for a shorter way to handle this redefinition.
> 49 votes

# Answer
# Aceto, ~~19~~ 17 bytes

### 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):

```
|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.

Aceto programs run on a Hilbert curve, starting on the bottom left, and ending on the bottom right. First, we `r`ead a string, `d`uplicate, 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 `i`nteger 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 `p`rint what's on the stack (since the stack is empty, a zero) and jump to the `O`rigin 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 `r`ead 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 (`<`), `p`rint 0 (because the stack is empty), and jump back to the `O`rigin.
> 27 votes

# Answer
# 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
> 18 votes

# Answer
# Python 2, 33 bytes

```
while 1:b=input();print b;True^=b

```

Port of @xnor's Python answer, minus 2 bytes. Normally I would just suggest it as a golf in the comments, but since *@xnor* has specifically stated we can outgolf any of his answers for a bounty, here it is as a separated answer.

Try it online.

The difference? `True&=b<1` has been changed to `True^=b`.

**Why does this work?**

First we get some potential `False` inputs (`b=input();`). Each of those will be printed as is (`print b;`). And the `True^False` will remain `True`, so 'variable' `True` remains truthy.

Then we encounter the first `True` input, which will also be printed. After that, the `True^True` will evaluate to `False`, so the 'variable' `True` is from now on falsey.

After that it doesn't matter what our input is anymore, since `True` is redefined as falsey. So the `print b;` will always print `False` at this point. And in addition, the `True^=b` can now only be `False^False`, so 'variable' `True` will remain falsey.
> 13 votes

# Answer
## Retina, 6 bytes

```
1>`1
0

```

Try it online!

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

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

# Answer
# 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.
> 12 votes

# Answer
# , 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

```
> 11 votes

# Answer
# 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!
> 10 votes

# Answer
# Haskell, 25 bytes

Anonymous function taking and returning a list of `Bool`s.

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 `True`s in `l` into `False` if `x` is `True`.
> 10 votes

# Answer
## JavaScript (ES6), ~~33~~ 26 bytes

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

```

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

# Answer
# 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!
> 6 votes

# Answer
## , 3 bytes

```
</\

```

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

# Answer
# 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!
> 5 votes

# Answer
# brainfuck, 55 bytes

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

```

Try it online!
> 5 votes

# Answer
# 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.
> 4 votes

# Answer
# , 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.
> 4 votes

# Answer
# Octave, 23 bytes

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

```

Try it online!

First difference of cumulative max of the list.
> 4 votes

# Answer
# 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.
> 3 votes

# Answer
# PHP, 37 bytes

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

```
> 3 votes

# Answer
# 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]

```
> 3 votes

# Answer
# unsure, 222 bytes

```
hm um err wait oops um but oops yeah umm err heh well wait oops then but heh wait oops no um um yeah err heh um but oops oops um heh well wait oops then um but oops yeah um err heh well wait then um but oops okay well wait

```

Unsure is a stack based esolang I recently created. This answer takes input as a string of `0x00` and `0x01` bytes.

First, here's the code broken into more readable sections:

```
hm um err wait oops

um but oops yeah umm err heh well wait oops then

but heh wait oops no um um yeah err heh

um but oops oops um heh well wait oops then

um but oops yeah um err heh well wait then

um but oops okay well wait

```

The first section is a loop, which first reads input (`hm`), and adds one (`um err`). The `wait` instruction usually ends a while loop, but because there is nothing to start the loop it defaults to the beginning of the program. Because it's adding `1` to each input, and EOF is `-1`, the loop will end once it reaches EOF with an additional `0` on the stack, which is discarded by `oops`.

The next line is a loop through the entire stack. For the first iteration, the stack length is unneeded, so it pushed `1` with `um`. The `but` starts a loop, and the `oops` discards the stack length. It then negates the top of the stack (`yeah`) and adds two (`umm err`, essentially the inverse of the input). It finally pushes this to the other stack (`heh`) and pushes the length of the current stack (`well`). Once the loop ends, the extra `0` is discarded and `then` switches the active stack.

The next line consists of two parts: `but heh wait oops no` (a simple loop which pops items to the other stack until one is `0`), then `um um yeah err heh` which pushes `0` to the other stack.

It then pads the other stack to the right length with `1`s (`um but oops oops um heh well wait oops`) and switches to the other stack (`then`). This is necessary because the output would be backwards otherwise. The other stack does about the same thing, but inverts each item by negating it and adding one (`yeah um err`).

Finally, the `um but oops okay well wait` loop just uses `okay` to output each item in the stack.
> 3 votes

# Answer
# 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']

```
> 2 votes

# Answer
# 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!
> 2 votes

# Answer
# 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 `false`s and `true`s. This is a list comprehension of `false`s 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!
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
## 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.
> 2 votes

# Answer
## 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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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)
([])
{
 {}({}<>)<>([])
}<>{}

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
## 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.
> 2 votes

# Answer
# 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!
> 2 votes

# Answer
## Perl 5, 12 bytes

**10 bytes code + 2 for `-pl`.**

```
$_&&=!$-++

```

Try it online!
> 2 votes

# Answer
# Jelly, 3 bytes

```
ŒQa

```

Try it online!

`ŒQ` was added to the language about two months after the previous Jelly solution.

```
ŒQ     Nub sieve: for each element, is it the first occurrence of that value?
  a    Take the logical AND of that and the original list.

```

user62131's solution can also be 3 bytes with a newer builtin:

# Jelly, 3 bytes

```
Ä=a

```

Try it online!
> 2 votes

# Answer
# tinylisp, 63 bytes

```
(d F(q((L B)(i L(c(i B(h L)0)(F(t L)(i(h L)0 B)))(
(q((L)(F L 1

```

The solution is the anonymous function in the second line; the first line is a helper function. Try it online!

### Ungolfed/explanation

```
(load library)                 ; Library contains ungolfed aliases for builtins

(def F                         ; Define F
  (lambda (L B)                ; as a function that takes a list L and an int B (where B
                               ; is a flag indicating if we're in the beginning section):
    (if L                      ;  If L is nonempty:
      (cons                    ;   Prepend
        (if B (head L) 0)      ;   head of L if B is truthy, else 0
        (F                     ;   to a recursive call
          (tail L)             ;   with tail of L as the new list
          (if (head L) 0 B)))  ;   and 0 as the new flag if head of L is truthy, else B
      nil)))                   ;  Else, return empty list

(lambda (L)                    ; Anonymous function that takes a list
  (F L B))                     ; and passes it to F with a second argument of 1

```
> 2 votes

# Answer
# 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.
> 1 votes

# Answer
# 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
    }
}

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Scala, 44 bytes

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

```
> 1 votes

# Answer
# PowerShell, 29 bytes

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

```

Try it online!
> 1 votes

# Answer
### 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).
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# PHP, 34 bytes

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

```

Try it online!
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
ε¾›D½

```

Try it online!

explanation:

```
ε for each value in the (implicit) input
¾ push the counter variable
› check if it's bigger than the current value (0 0 - 0, 0 1 - 1, 1 0 - 0, 1 1 - 0)
D duplicate
½ increment the counter variable if it's true (which means that if the current value is 1 and the counter is 0, increment it)

```
> 1 votes

# Answer
# \[Python 2\], ~~83~~ 68 bytes

I try classic approach.

```
def t(l,b=1>0):
 r=[]
 for x in l:r+=[x and b];b=(1-x)*b>0
 return r

```

I use `and` boolean operator between each value of list and a value that is true until first truely value in list and false after.

es.

```
list val. --> F F T F T F F
b         --> T T T F F F F
and op.   --> F F T F F F F

```

Tanks @AdHocGarfHunter
> 1 votes

# Answer
# Ruby `-nl`, 22 bytes

Input is STDIN.

```
a|=p
p !a&&a|=eval($_)

```

Try it online!

### Explanation

```
                  # For each line of STDIN:
a|=p              # Set a to falsy if it wasn't defined before
                  #  (needed or else the next line crashes)
p !a&&a|=eval($_) # Output false if a is truthy, otherwise OR it with the value in STDIN
                  #  and output that instead

```
> 1 votes

# Answer
# K (oK), 13 bytes

**Solution:**

```
{@[x;1_&x;~]}

```

Try it online!

**Explanation:**

```
{@[x;1_&x;~]} / the solution
{           } / lambda taking implicit argument x
 @[x;    ; ]  / apply func to target at indices @[target;indices;func]
          ~   / not, the function being applied
       &x     / indices where x is true
     1_       / drop the first occurrence

```
> 1 votes

# Answer
# Python 3, ~~52~~ ~~46~~ ~~44~~ 38 bytes

Input is a list of bools, requires Python 3.8 (for the walrus operator `:=`).

```
lambda x,b=0:[a>b and(b:=a)for a in x]

```

To be called as `(lambda x,b=0:[a>b and(b:=a)for a in x])(bools_list)`

Previous attempts:

Input is a list of `1`s and `0`s

```
lambda x,b=0:[(b:=1)if a>b else 0for a in x]

```
~~```
def f(x):a=[0]*len(x);a[x.index(1)]=1;return a

```~~

The above doesn't work with an all-falsey list, `list.index` throws `ValueError` if the value isn't present. Edit: and neither do most (all?) other Python 3 entries, for the same reason.

Input `x` is an iterable of bools, returns iterable of bools.

```
map(lambda a,b=[0]:not(b[-1]or b.append(a)or 1-a),x)

```
> 1 votes

# Answer
# Fig, \\$6\log\_{256}(96)\approx\\$ 4.939 bytes

```
=1*eSk

```

Try it online!

cumsum builtin when
> 1 votes

# Answer
# PHP, 61 Bytes

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

```

Try it online!
> 0 votes

# Answer
# Japt, 7 bytes

```
®?!T°:Z

```

Try it online!
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
## 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.
> 0 votes

# Answer
# 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])

```
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# Retina, 16 bytes

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

```

Try it online! My first Retina submission ever.
> 0 votes

# Answer
# 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 `memset`s 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;
}

```
> 0 votes

# Answer
# 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 ]

```
> 0 votes

# Answer
# Whitespace, 66 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Dupe_0][S N
S _Dupe_0][S N
S _Dupe_0][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_integer][T    S S T   _Subtract][N
T   T   S N
_If_negative_Jump_to_Label_FIRST_TRUTHY][S S S N
_Push_0][T  N
S T _Print_as_integer][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_FIRST_TRUTHY][S S S T N
_Push_1][S N
S _Dupe_1][T    N
S T _Print_as_integer][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

The input is newline separated, and the output is all joined together. If this is not allowed, it's 80 bytes (both newline separated) or 82 bytes (both joined together) instead.
Uses `1` for truthy and `0` for falsey.

**Explanation in pseudo-code:**

```
Integer flag = 0
Start LOOP:
  Integer input = STDIN as integer
  If(flag - input < 0):
     Jump to Label FIRST_TRUTHY
  Print 0 as integer to STDOUT
  Go to next iteration of LOOP

FIRST_TRUTHY:
  flag = 1
  Print 1 as integer to STDOUT
  Go to next iteration of LOOP

```
> 0 votes

# Answer
# Kotlin, 31 bytes

```
{List(size){it==indexOf(true)}}

{                             }  // lambda; input is `this`
 List(    )                      // build new list
      size                       // same size as input
           {                 }   // based on lambda
            it==                 // index of this element equal to
                indexOf(true)    // index of first true in input

```

To actually solve this challenge you only need to know two things about the input:

* its length
* where the first true is.

The shotgun approach of just generating a new list worked out best here.

Try it online!
> 0 votes

# Answer
# Io, 38 bytes

```
method(x,x map(i,v,i==x indexOf(1<2)))

```

Try it online!

## Explanation

```
method(x, // Take an operand x
    x map(i,v, // Map every item with index/value
        i==    // Is the index equal to
        x indexOf(1<2) // the index of true in x?
    )
)

```
> 0 votes

# Answer
## Processing.js (Khanacademy version), 67 bytes

```
var a=[];for(var i=0;i<a.length;i++){if(i!==0){a[i]=0;}}print(a);

```

A is the input (khanacademy version of processing has no real input method)

The output is printed to console. Truth = 1, false = 0;

Try it online!
> 0 votes

# Answer
# sed, 8 bytes

```
0,/./!c

```

Try it online!

Note the trailing linefeed.

Inputs are linefeed separated. Any single character is truthy (I used `1`) and an empty line is falsey.

Input should not have a trailing linefeed, as that will be interpreted as an extra falsey value. Note that TIO adds a final linefeed, and thus a falsey value, at the end. This is a limitation of TIO, the program works just fine without.

Commented:

```
0,/./ #Run the following commands from the first line to the first line containing a character
#If we are *not* in the previous range, replace the line with an empty line
!c

```

To make it easier to read the output, you can make `0` falsey and replace the program with

```
0,/1/!c0

```

at the cost of one byte. Try it online!
> 0 votes

# Answer
# Vyxal, 3 bytes

```
¦=*

```

Try it Online!

### Explained

```
¦=*
¦   # cumulative sum
 =  # equal
  * # multiply bits

```
> 0 votes

# Answer
# BQN, 3 bytes

```
×⟜∊

```

Anonymous tacit function; takes and returns a list of 0's and 1's. Try it at BQN online!

### Explanation

```
  ∊  Mark firsts: a list the same length as the argument, containing 1 at the first
     occurrence of each element of the argument and 0 for subsequent occurrences
×⟜  Multiply by the argument, itemwise

```
> 0 votes

# Answer
# Go, 129 bytes

```
func f(i[]int)(o[]int){k:=0
for _,e:=range i{if e>0&&k<1{k=1
o=append(o,1)}else if k>0{o=append(o,0)}else{o=append(o,e)}}
return}

```

Attempt This Online!
> 0 votes

# Answer
# x86-64 machine code, 9 bytes

```
56 59 31 C0 F3 AE F3 AA C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI the address of an array of 8-bit integers and its length in RSI, and modifies it in place, taking 0 as a falsy value and any nonzero value as a truthy value.

In assembly:

```
f:  push rsi; pop rcx   # Put the length into RCX.
    xor eax, eax        # Set EAX to 0. In particular, its low byte AL is 0.
    repe scasb  # Read bytes from the array and compare them with AL,
                #  advancing the pointer and counting down from the length in RCX,
                #  stopping when the comparison result is not equal or RCX is 0.
    rep stosb   # Repeatedly write AL into the array, advancing the pointer,
                #  and counting down RCX, stopping when RCX is 0.
                # This writes 0 into all the remaining places.
    ret         # Return.

```
> 0 votes

# Answer
# TI-Basic, 7 bytes

```
Ans and 1=cumSum(Ans

```

Takes input as Ans (last input value)
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
ṡ=&

```

Attempt This Online!

#### Explanation

```
ṡ=&  # Implicit input      ->  [0,1,0,1,0,0,1]
ṡ    # Cumulative sums     ->  [0,1,1,2,2,2,3]
 =   # Check for equality  ->  [1,1,0,0,0,0,0]
  &  # Logical AND         ->  [0,1,0,0,0,0,0]
     # Implicit output

```
> 0 votes

# Answer
## 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!
> -1 votes

---
Tags: code-golf, array, logic
---