title: Find the maximum deviation

text:
# Question
Title: Find the maximum deviation
This problem is "inspired" from a question that was originally asked on Quora (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here).

Given an array of integer elements `v` and an integer `d` (we assume that d is lower or equal to the array's length), consider all the sequences of `d` consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation.

Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value.

Worked-through Example:

```
v: (6,9,4,7,4,1)
d: 3

The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6

Thus the maximal deviation is 6, so the output is 6.

```

This is code golf, so the shortest answer in bytes wins.

# Answer
# Dyalog APL, 7 bytes

```
⌈/⌈/-⌊/

```

Test it on TryAPL.

### How it works

```
⌈/⌈/-⌊/  Dyadic chain. Left argument: d. Right argument: v

     ⌊/  Reduce v by d-wise minimum, yielding the minima of all slices of length d.
  ⌈/     Reduce v by d-wise maximum, yielding the maxima of all slices of length d.
    -    Subtract, yielding the ranges of all slices of length d.
⌈/       Take the maximum.

```
> 16 votes

# Answer
## JavaScript (ES6), 73 bytes

```
with(Math)(v,d)=>max(...v.map((a,i)=>max(...a=v.slice(i,i+d))-min(...a)))

```
> 5 votes

# Answer
# Python, 60 bytes

Saving 5 bytes thanks to Neil

```
f=lambda v,d:v and max(max(v[:d])-min(v[:d]),f(v[1:],d))or 0

```

My first recursive lambda!

Usage:

```
print f([6,9,4,7,4,1], 3)

```
> 4 votes

# Answer
# R, ~~63~~ ~~62~~ 56 bytes

Billywob has already provided a great R answer using only the base functions. However, I wanted to see if an alternative approach was possible, perhaps using some of R's extensive packages. There's a nice function `rollapply` in the `zoo` package designed to apply a function to a rolling window of an array, so that fits our purposes well. We use `rollapply` to find the `max` of each window, and we use it again to find the `min` of each window. Then we take the difference between the maxes and mins, which gives us the deviation for each window, and then return the `max` of those.

```
function(v,d)max((r=zoo::rollapply)(v,d,max)-r(v,d,min))

```
> 4 votes

# Answer
# Perl, 48 bytes

Includes +5 for `-0pi`

Give the width after the `-i` option, give the elements as separate lines on STDIN:

```
perl -0pi3 -e '/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F'
6
9
4
7
4
1
^D

```

Just the code:

```
/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F

```

(use a literal `\n` for the claimed score)
> 4 votes

# Answer
# Husk, <sup>~~13~~</sup> 7 bytes

```
▲m§-▼▲X

```

Try it online!

-6 bytes from Jo King.

## Explanation

```
▲m§-▼▲X Slices of length n
 m      map to
  §-    difference between
    ▼▲  min and max
▲       take the maximum of that

```
> 4 votes

# Answer
# R, 80  77 bytes bytes

Edit: Saved 3 bytes thanks to @rturnbull

```
function(s,d)max(sapply(d:sum(1|s)-d+1,function(i)diff(range(s[i:(i+d-1)]))))

```
> 3 votes

# Answer
# Mathematica, ~~41~~ 37 bytes

```
Max[MovingMap[MinMax,#,#2-1].{-1,1}]&

```
> 3 votes

# Answer
# 05AB1E, ~~12~~ 10 bytes

Uses CP-1252 encoding.

```
Œù€{øÀ`-ÄZ

```

Try it online!

**Explanation**

```
Œ              # sublists of v
 ù             # of length d
  €{           # sort each
    ø          # zip
     À         # rotate left (last 2 lists will be largest and smallest)
      `        # flatten (lists with smallest and largest item will be on top)
       -       # subtract largest from smallest
        Ä      # take absolute value (as we will have negatives after the previous step)
         Z     # take the largest

```
> 2 votes

# Answer
## PowerShell v2+, 68 bytes

```
param($v,$d)($v|%{($x=$v[$i..($i+++$d-1)]|sort)[-1]-$x[0]}|sort)[-1]

```

Iterative solution. Loops through `$v`, but really we're just using that as a counter rather than actually going through the values. Each iteration, we're slicing `$v` by `$i..($i+++$d-1)`, where `$i` defaults to `0`. We `|sort` those elements, and store the result into `$x`. Then we take the biggest `[-1]` and subtract the smallest `[0]`. We then `|sort` those results and take the biggest `[-1]` of that. That number is left on the pipeline and output is implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(6,9,4,7,4,1) 3
6

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(1,2,3,4,5,6) 3
2

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(7,2,3,4,5,6) 3
5

```
> 2 votes

# Answer
# Ruby, 45 bytes

```
->a,d{a.each_cons(d).map{|b|b.max-b.min}.max}

```

I feel like this could be a lot better.
> 2 votes

# Answer
# Scala, 48 bytes

```
(_:Seq[Int])sliding(_:Int)map(s=>s.max-s.min)max

```

Ungolfed:

```
(a:Seq[Int],d:Int)=>a.sliding(d).map(s=>s.max-s.min).max

```

Explanation:

```
(_:Seq[Int])   //define a function with a seq of ints as an argument
sliding(_:Int) //get the sequences with the length of an int argument
map(s=>        //map each sequence
  s.max-s.min    //to its deviation
)max           //and take the maximum value

```
> 2 votes

# Answer
# Java 8, 140 128

Shaved a bunch off, in part thanks to VTCAKAVSMoACE.

```
int l(int[]a,int d){int x=0,i=0,f,j,k;for(;i<=a.length-d;i++)for(j=i;j<i+d;j++)for(k=i;k<i+d;)x=(f=a[j]-a[k++])>x?f:x;return x;}

```

Ungolfed

```
int l(int[]a,int d){
    int x=0,i=0,f,j,k;
    for(;i<=a.length-d;i++)
        for(j=i;j<i+d;j++)
            for(k=i;k<i+d;)
                x=(f=a[j]-a[k++])>x?f:x;
    return x;
}

```
> 2 votes

# Answer
# Factor \+ `math.statistics`, 32 bytes

```
[ clump [ range ] map supremum ]

```

Try it online!

* `clump` Get the windows of \[first input\] of length \[second input\]
* `[ range ] map` Map each window to its 'deviation' (which Factor calls `range`)
* `supremum` Maximum element
> 2 votes

# Answer
# PowerShell, 70 bytes

```
(0..(-$d+$v.count)|%{$s=$v[$_..($_+$d-1)]|sort;$s[-1]-$s[0]}|sort)[-1]

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
ŒIùεW-}à

```

Inputs in the order \\$v,d\\$.

Try it online.

**Explanation:**

```
Œ       # Get all sublists of the first (implicit) input-list `v`
 Iù     # Only keep those with a length equal to the second input-integer `d`
   ε    # Map over each d-sized sublist:
    W   #  Push the minimum of the current sublist (without popping the list)
     -  #  Subtract this minimum from each value in the list
   }à   # After the map: pop and push the flattened maximum
        # (which is output implicitly as result)

```

The map `εW-}` could alternatively be `D€ß-` for a vectorized subtraction.
> 2 votes

# Answer
# MATL, 10 bytes

```
YCS5LY)dX>

```

Try it online!

### Explanation

Consider inputs \[6,9,4,7,4,1\], 3 as an example.

```
       % Implicitly take the two inputs: v, d
       % STACK: [6,9,4,7,4,1], 3
YC     % Matrix of overlapping d-blocks of v
       % STACK: [6 9 4 7
                 9 4 7 4
                 4 7 4 1]
S      % Sort each column
       % STACK: [4 4 4 1
                 6 7 4 4
                 9 9 7 7]
5LY)   % Keep first and last rows
       % STACK: [4 4 4 1
                 9 9 7 7]
d      % Differences along each column
       % STACK: [5 5 3 6]
X>     % Maximum
       % STACK: 6
       % Implicitly display

```
> 1 votes

# Answer
# MATLAB with Statistics and Image Processing Toolboxes, 33 bytes

```
@(v,d)max(range(im2col(v,[1 d])))

```

This defines an anonymous function. Example use:

```
>> f = @(v,d)max(range(im2col(v,[1 d])));
>> f([6,9,4,7,4,1], 3)
ans =
     6

```

You can also try it on Octave at Ideone (but Octave, unlike Matlab, requires explicitly loading the image package).

### Explanation

```
im2col(v,[1 d]))   % Takes overlapping blocks of size d from v, and arranges them as
                   % columns of a matrix
range(...)         % Maximum minus minimum of each column. Gives a row vector
max(...)           % Maximum of the above row vector

```
> 1 votes

# Answer
# PHP, ~~89~~ 87 bytes

```
for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;

```

Not particularly clever or pretty but it works. Use like:

```
php -r "for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;" 3 6 9 4 7 1

```

for `v`=`6,9,4,7,4,1`, `d`=`3`

Edit: 2 bytes saved thanks to Jörg Hülsermann
> 1 votes

# Answer
# Java 7,159 bytes

Java = expensive(i know it can be golfed much more)

```
int c(int[]a,int d){int[]b=new int[d];int i,j,s=0;for(i=-1;i<a.length-d;){for(j=++i;j<i+d;)b[i+d-1-j]=a[j++];Arrays.sort(b);s=(j=b[d-1]-b[0])>s?j:s;}return s;}

```

# Ungolfed

```
static int c ( int []a , int d){
    int []b = new int[ d ];
    int i , j , s = 0 ;
    for ( i = -1 ; i < a.length - d ;) {
        for ( j = ++i ; j < i + d ;)
        b[ i + d - 1 - j ] = a[ j++ ] ;
        Arrays.sort( b ) ;
        s = ( j = b[ d - 1 ] - b[ 0 ] ) > s ? j : s ;
    }
    return s ;
    }

```
> 1 votes

# Answer
# Jelly, 8 bytes

```
ṡµṂ€ạṀ€Ṁ

```

Try it online!

Uses the same algorithm as Dyalog APL, but I figured this myself before looking at it.

Explanation:

```
ṡµṂ€ạṀ€Ṁ ḷ“Main link. Arguments: v d.”
ṡ        ḷ“Overlapping sublists of x of length y.”
 µ       ḷ“Start a new monadic chain.”
  Ṃ€ạṀ€  ḷ“Find the deviation of each of the elements of x.”
       Ṁ ḷ“Take the maximum of x.”

```

Note: `x`, `y` are left, right arguments respectively.
> 1 votes

# Answer
# Brachylog, 10 bytes

```
s₎ᶠ⟨⌉-⌋⟩ᵐ⌉

```

Try it online!
> 1 votes

# Answer
# Arturo, 59 bytes

```
$[a,n][max map 0..-size a n'x[z:a\[x..x+n-1](max z)-min z]]

```

Try it
> 1 votes

# Answer
# Japt `-h`, 12 bytes

```
ãV mÍ®Ì-ZÎÃÍ

```

Try it

```
ãV     # subsequences of length V
mÍ     # sort each, ascending
®Ì-ZÎÃ # map each to last - first
Í      # sort, ascending
# -h flag prints the last element

```
> 1 votes

# Answer
# Desmos, ~~62~~ 58 bytes

```
r=v[i-d+1...i]
f(v,d)=[r.max-r.minfori=[d...v.length]].max

```

Try it on Desmos!
-4 bytes thanks to Aiden Chow
> 1 votes

# Answer
# Vyxal `G`, 12 bytes

```
ÞS'L⁰=;ƛG$g-

```

Try it Online!

#### Explanation

```
ÞS'L⁰=;ƛG$g-  # Implicit input
ÞS            # All sublists of the first input
  '   ;       # Filtered by the following:
   L          #  The length of the sublist
    ⁰=        #  Equals the second input
       ƛ      # Map over the filtered list:
        G     #  Push the maximum of the sublist
         $g   #  Swap and push the minimum
           -  #  Subtract to find the deviation
              # G flag gets the maximum of this list
              # Implicit output

```
> 1 votes

# Answer
# Uiua, 10 bytes

```
/↥-⊃/↧/↥⍉◫

```

Try it!

```
/↥-⊃/↧/↥⍉◫
         ◫  # windows
        ⍉   # transpose
   ⊃/↧/↥    # maxes and mins of each column
  -         # subtract
/↥          # maximum

```
> 1 votes

# Answer
# CJam, 17 bytes

```
q~ew{$)\(\;-}%:e>

```

(Also `q~ew:$z)\(\;.-:e>`)

Try it online!

### Explanation

```
q~                   e# Read the two inputs. Evaluate
  ew                 e# Overlapping blocks
    {       }%       e# For each block
     $               e# Sort
      )              e# Get last element (that is, maximum)
       \(            e# Swap, get first element (minimum)
         \;          e# Swap, delete rest of the block
           -         e# Subtract (maximum minus minimum)
              :e>    e# Maximum of array

```
> 0 votes

# Answer
## Haskell, 56 bytes

```
_#[]=0
d#l|m<-take d l=max(maximum m-minimum m)$d#tail l

```

Usage example: `3 # [6,9,4,7,4,1]` -\> `6`.

Considering ranges less than `d` doesn't change the overall maximum, so we can run `take d` down to the very end of the list (i.e. also include the ranges with the last `d-1`, `d-2`, ... `0` elements). The recursion stops with the empty list where we set the deviation to `0`.
> 0 votes

# Answer
# Actually, 13 bytes

```
╗╜@V`;m@M-`MM

```

Try it online!

-6 bytes from the observation in nimi's Haskell answer, that slices shorter than `d` don't affect the maximum deviation.

Explanation:

```
╗╜@V`;m@M-`MM
╗              store d in register 0
 ╜@            push d, swap so v is on top
   V           push all slices of v whose length is in [1, d]
    `;m@M-`M   map (for each slice):
     ;m@M-       get minimum and maximum, subtract min from max
           M  get maximum of list of deviations

```
> 0 votes

# Answer
## Java, 126 bytes

I got inspired by dpa97's answer and found this:

```
int f(int v[],int d){int m=0,i=0,j,t,l=v.length;for(;i<l;i++)for(j=i;j<l;j++)m=j-i<d&&(t=Math.abs(v[i]-v[j]))>m?t:m;return m;}

```

Expanded, golfed and example code
> 0 votes

# Answer
## Racket 121 bytes

```
(let p((v v)(j 0))(let*((l(take v d))(k(-(apply max l)(apply min l)))
(j(if(> k j)k j)))(if(= d(length v))j(p(cdr v)j))))

```

Ungolfed:

```
(define (f d v)
  (let loop ((v v)
             (mxdev 0))                     ; start with max deviation as 0
    (let* ((l (take v d))                   ; take initial d elements in v
           (dev (- (apply max l)            ; find deviation
                    (apply min l)))
           (mxdev (if(> dev mxdev)          ; note max deviation
                   dev
                   mxdev)))
      (if (= d (length v)) mxdev            ; if all combinations tested, print max deviation
          (loop (rest v) mxdev))            ; else test again
      )))                                   ; with first element of list removed

```

Testing:

```
(f 3 '(6 9 4 7 4 1))

```

Output:

```
6

```
> 0 votes

# Answer
# q, 25 bytes

```
{max mmax[y;x]-mmin[y;x]}

```

`mmax` and `mmin` are sliding window maximum and minimum respectively

Example

```
q){max mmax[y;x]-mmin[y;x]}[6 9 4 7 4 1;3]
6

```
> 0 votes

# Answer
## C#, 131 bytes

here is a verbose linq solution

```
int c(int[]a){var x=from j in Enumerable.Range(0,a.Length-2)let p=new[]{a[j],a[j+1],a[j+2]}select p.Max()-p.Min();return x.Max();}

```
> 0 votes

# Answer
# C#, 163 bytes

Golfed:

```
int m(List<int> v,int d){var l=new List<List<int>>();for(int i=0;i<v.Count;i++){if(v.Count-i>=d)l.Add(v.GetRange(i,d));}return l.Select(o=>o.Max()-o.Min()).Max();}

```

Ungolfed:

```
public int m(List<int> v, int d)
{
  var l = new List<List<int>>();

  for (int i = 0; i < v.Count; i++)
  {
    if (v.Count - i >= d)
      l.Add(v.GetRange(i, d));
  }

  return l.Select(o => o.Max() - o.Min()).Max();
}

```

Test:

```
var maximumDeviation = new MaximumDeviation();
Console.WriteLine(maximumDeviation.f(new List<int> {6,9,4,7,4,1}, 3));

```

Output:

```
6

```
> 0 votes

# Answer
## Clojure, ~~73~~ 67 bytes

Edit: Using `#(...)` instead of `(fn[...])` and `for` instead of `map`.

```
#(apply max(for[p(partition %2 1 %)](-(apply max p)(apply min p))))

```
> 0 votes

# Answer
# Pyth, 11 bytes

```
eSms.+Sd.:F

```

### Explanation

```
eSms.+Sd.:FQ   Implicit input
          FQ   Unpack the input (v, d)
        .:     Get all subsequences of length d
  m   Sd       Sort each
   s.+         Take the sum of differences to get the deviation
eS             Get the maximum

```
> 0 votes

# Answer
# Perl 6, 44 bytes

```
{$^a.rotor($^b=>1-$^b).map({.max-.min}).max}

```

`$^a` and `$^b` are the two arguments to the function, called `v` and `d` respectively in the problem statement. The `rotor` method returns the sequence of subsequences of `v` of size `d`.
> 0 votes

# Answer
# Python 3, 80 bytes

```
lambda v,d:max(map(lambda g:max(g)-min(g),[v[i:i+d]for i in range(-~len(v)-d)]))

```
> 0 votes

---
Tags: code-golf, math, array, optimization
---


title: Tips for golfing in sed

text:
# Question
Title: Tips for golfing in sed
What general tips do you have for golfing in sed? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to sed (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
If you need to use labels then for sure you'll want your label names to be as short as possible. In fact taken to the extreme, you may even use the empty string as a label name:

```
:    # define label ""
p    # print pattern space
b    # infinite loop! - branch to label ""

```
> 10 votes

# Answer
The GNU sed documentation describes the `s` command as *"sed's Swiss Army Knife"*. But if all you want to do is replace all instances of one character with another, then the `y` command is what you need:

```
y/a/b/

```

is one char shorter than:

```
s/a/b/g

```
> 8 votes

# Answer
When repeatedly replacing in a loop:

```
loop:
s/foo/bar/g
tloop

```

it's usually unnecessary to replace globally, as the loop will eventually replace all occurrences:

```
# GNU sed
:
s/foo/bar/
t

```

Note also the GNU extension above: a label can have an empty name, saving more precious bytes. In other implementations, a label cannot be empty, and jumping without a label transfers flow to the end of script (i.e. same as `n`).
> 7 votes

# Answer
Consider using extended regex syntax (in GNU sed). The `-r` option costs one byte in scoring, but using it just once to eliminate the backslashes from a pair of `\(...\)` has already paid for itself.
> 6 votes

# Answer
As mentioned in `man sed` (GNU), you can use any character as a delimiter for regular expressions by using the syntax

```
\%regexp%

```

where `%` is a placeholder for any character.

This is useful for commands like

```
/^http:\/\//

```

which are shorter as

```
\%^http://%

```

What is mentioned in the GNU sed manual but **not** in `man sed` is that you can change the delimiters of `s///` and `y///` as well.

For example, the command

```
ss/ssg

```

removes all slashes from the pattern space.
> 6 votes

# Answer
# Read the whole input at once with `-z`

Often you need to operate on the whole input at once instead of one line at a time. The `N` command is useful for that:

```
:
$!{N;b}

```

...but usually you can skip it and use the `-z` flag instead.

The `-z` flag makes sed use NUL (`\0`) as its input line separator instead of `\n`, so if you know your input won’t contain `\0`, it will read all of the input at once as a single “line”:

```
$ echo 'foo
> bar
> baz' | sed -z '1y/ao/eu/'
fuu
ber
bez

```

Try it online!
> 6 votes

# Answer
There's no built-in arithmetic, but calculations can be done in unary or in unary-coded decimal. The following code converts decimal to UCD, with x as the unit and 0 as the digits separator:

```
s/[1-9]/0&/g
s/[5-9]/4&/g
y/8/4/
s/9/4&/g
s/4/22/g
s/[37]/2x/g
s/[26]/xx/g
s/[1-9]/x/g

```

and here's the conversion back to decimal:

```
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/42/6/g
s/21/3/g
s/61/7/g
s/41/5/g
s/-//g

```

These are both taken from an answer to "Multiply two numbers without using any numbers".

Plain old unary can be converted using this pair of loops from this answer to "{Curly Numbers};", where the unit is `;`. I've used `v` and `x` to match Roman for `5` and `10`; `b` comes from "bis".

```
# unary to decimal
:d
/;/{
s/;;;;;/v/g
s/vv/x/g
/[;v]/!s/x\+/&0/
s/;;/b/g
s/bb/4/
s/b;/3/
s/v;/6/
s/vb/7/
s/v3/8/
s/v4/9/
y/;bvx/125;/
td
}

# Decimal to unary
:u
s/\b9/;8/
s/\b8/;7/
s/\b7/;6/
s/\b6/;5/
s/\b5/;4/
s/\b4/;3/
s/\b3/;2/
s/\b2/;1/
s/\b1/;0/
s/\b0//
/[^;]/s/;/&&&&&&&&&&/g
tu

```
> 5 votes

# Answer
# Append a newline in one byte

The `G` command appends a newline and the contents of the hold space to the pattern space, so if your hold space is empty, instead of this:

```
s/$/\n/

```

You can do this:

```
G

```

# Prepend a newline in three bytes

The `H` command appends a newline and the contents of the pattern space to the hold space, and `x` swaps the two, so if your hold space is empty, instead of this:

```
s/^/\n/

```

You can do this:

```
H;x

```

This will pollute your hold space, so it only works once. For two more bytes, though, you could clear your pattern space before swapping, which is still a savings of two bytes:

```
H;z;x

```
> 5 votes

# Answer
If not explicitly banned by the question, the consensus for this meta question is that numerical input may be in unary. This saves you the 86 bytes of decimal to unary as per this answer.
> 4 votes

# Answer
I know this is an old thread, but I just found those clumsy decimal to UCD converters, with almost a hundred bytes, some even messing the hold space or requiring special faulty `sed` versions.

For **decimal to UCD** I use (68 bytes; former best posted here 87 bytes)

```
s/$/\n9876543210/
:a
s/\([1-9]\)\(.*\n.*\)\1\(.\)/\3x\2\1\3/
ta
P;d

```

**UCD to decimal** is (also 66 bytes; former best posted here 96)

```
s/$/\n0123456789/
:a
s/\([0-8]\)x\(.*\n.*\)\1\(.\)/\3\2\1\3/
ta
P;d

```
* `\n` in the replacement is not portable. You can use a different character instead and save two bytes, but you'll need more bytes to remove the appendix instead of `P;d`; see next remark. Or, if your hold space is empty, do `G;s/$/9876543210/` without byte penalty.
* If you need further processing, you'll need some more bytes for `s/\n.*//` instead of `P;d`.
* You could save two bytes each for those buggy old GNU `sed` versions
* No, you can't save those six backslashes as extended regular expressions don't do backreferences
> 4 votes

# Answer
## Empty regexes are equivalent to the previously encountered regex

<sup>(thanks to Riley for discovering this from an anagol submission)</sup>

Here is an example where we are tasked with creating 100 `@`s in an empty buffer.

```
s/$/@@@@@@@@@@/;s/.*/&&&&&&&&&&/ # 31 bytes
s/.*/@@@@@@@@@@/;s//&&&&&&&&&&/  # 30 bytes

```

The second solution is 1 byte shorter and uses the fact that empty regexes are filled in with the last encountered regex. Here, for the second substitution, the last regex was `.*`, so the empty regex here will be filled with `.*`. This also works with regexes in `/conditionals/`.

Note that it is the previously *encountered* regex, so the following would also work.

```
s/.*/@@@@@@@@@@/;/@*/!s/$/@/;s//&&&&&&&&&&/

```

The empty regex gets filled with `@*` instead of `$` because `s/$/@/` is never reached.
> 4 votes

# Answer
# Unary-UCD-Decimal conversions

The programs below are adapted from solutions in anarchy golf. The solutions below work on GNU sed 4.2.2, where empty labels are allowed. It is possible I've missed better solutions on anarchy golf.

## Unary to Decimal, `sed -r` at 47 bytes

From solutions by %20 and tails. Works only for integers greater than 0. The chosen unary digit (`-` in the below program) occurs 3 times in the program.

```
:
s/-/<<123456789-01>/
s/(.)<.*\1(-*.).*>/\2/
t

```

Try it online! and (bash wrapper for easier testing)

## Decimal to UCD, `sed` at 39 bytes

From a solution by %20. Works on all integers, including negative ones.

```
:
s/[1-9]/&;/g
y/123456789/012345678/
t

```

Try it online!

## Decimal to Unary (via UCD), `sed` 55 bytes

From a solution by tails. Works on all integers, including negative ones.

```
:
s/[1-9]/&;/g
y/123456789/012345678/
s/;0/9;/
t
s/0//g

```

Try it online! and (bash wrapper)
> 4 votes

# Answer
Instead of clearing the pattern space with `s/.*//`, use the `z` command (lowercase) if you go with GNU sed. Besides the lower bytes count, it has the advantage that it won't start the next cycle as the command `d` does, which can be useful in certain situations.
> 3 votes

# Answer
Let's talk about the `t` and `T` commands, that although they are explained in the man page, it's easy to forget about it and introduce bugs accidently, especially when the code gets complicated.

**Man page statement for `t`:**

> If a `s///` has done a successful substitution since the last input line was read and since the last t or T command, then branch to label.

**Example showing what I mean:** Let's say you have a list of numbers and you want to count how many negatives there are. Partial code below:

```
1{x;s/.*/0/;x}                   # initialize the counter to 0 in hold space
s/-/&/                           # check if number is negative
t increment_counter              # if so, jump to 'increment_counter' code block
b                                # else, do nothing (start a next cycle)

:increment_counter
#function code here

```

Looks ok, but it's not. If the first number is positive, that code will still think it was negative, because the jump done via `t` for the first line of input is performed regardless, since there was a successful `s` substitution when we initialized the counter! Correct is: `/-/b increment_counter`.

If this seemed easy, you could still be fooled when doing multiple jumps back and forth to simulate functions. In our example the `increment_counter` block of code for sure would use a lot of `s` commands. Returning back with `b main` might cause another check in "main" to fall in the same trap. That is why I usually return from code blocks with `s/.*/&/;t label`. It's ugly, but useful.
> 3 votes

# Answer
Expanding upon this tip answer, regarding the conversions between decimal and plain unary number formats, I present the following alternative methods, with their advantages and disadvantages.

**Decimal to plain unary:** 102 + 1(r flag) = 103 bytes. I counted `\t` as a literal tab, as 1 byte.

```
h
:
s:\w::2g
y:9876543210:87654321\t :
/ /!s:$:@:
/\s/!t
x;s:-?.::;x
G;s:\s::g
/\w/{s:@:&&&&&&&&&&:g;t}

```

**Try it online!**

Advantage: it is 22 bytes shorter and as extra, it works with negative integers as input

Disadvantage: it overwrites the hold space. However, since it's more likely that you'd need to convert the input integer right at the start of the program, this limitation is rarely felt.

**Plain unary to decimal:** 102 + 1(r flag) = 103 bytes

```
s:-?:&0:
/@/{:
s:\b9+:0&:
s:.9*@:/&:
h;s:.*/::
y:0123456789:1234567890:
x;s:/.*::
G;s:\n::
s:@::
/@/t}

```

**Try it online!**

Advantage: it is 14 bytes shorter. This time both tip versions work for negative integers as input.

Disadvantage: it overwrites the hold space

For a complicated challenge, you'll have to adapt these snippets to work with other information that may exist in the pattern space or hold space, besides the number to convert. The code can be golfed more, if you know you only work with positive numbers or that zero alone is not going to be a valid input / output.

An example of such challenge answer, where I created and used these snippets, is the Reciprocal of a number (1/x).
> 3 votes

# Answer
# Make use of sed's line-handling ability

With flexible challenge I/O, it can pay to have input/output separated by newlines instead of any other character by taking advantage of sed's commands for handling lines (like `D`, `N`, `n`, `G`, `H`, `P`, `s`'s `m` flag) instead of only being limited to `s` substitutions.

This can also open the opportunity for using `D` for looping instead of labels and goto, especially in sed versions that don't permit empty labels.
> 3 votes

# Answer
# The `L` command in old GNU sed versions

Used, for example, in the second solution in https://codegolf.stackexchange.com/a/220633/. Older versions of GNU sed like GNU sed 4.2.2 have the `L` command, which was later removed in newer versions. From the archived docs,

> `L` *n*
>
> This GNU `sed` extension fills and joins lines in pattern space to produce output lines of (at most) *n* characters, like `fmt` does; if *n* is omitted, the default as specified on the command line is used. This command is considered a failed experiment and unless there is enough request (which seems unlikely) will be removed in future versions.
> 2 votes

# Answer
# `#n` at first to imply `-n`

> The "#" and the remainder of the line are ignored (treated as a comment), with the single exception that if the first two characters in the file are #n, the default output is suppressed; this is the equivalent of specifying -n on the command line.

Source: sed (from SUSv2)

This is useful if you prefer NOT to output something by default.

...But is it really useful? `-n` adds either 1 or 2 bytes but `#n` and LF adds 3.
> 2 votes

# Answer
# `i`, `a`, and `c`

(The answer focuses on GNU sed because GNU sed's invocation of these commands is slightly shorter than that of POSIX, but otherwise I think the functionality should be the same).

These insert to, append to, and change the pattern space respectively. The lines they add are printed and so are not edited into the pattern space, meaning that the program will not be able to manipulate these lines. But they are shorter than `s`, if you want to insert some unchanging lines. Compare the following two lines:

```
s/^/text\n/ # 11 bytes
itext       #  5 bytes

```

Now I want to focus on `c`. `c text` replaces the pattern space with `text`. This text will be printed immediately, since the `c` makes sed move on to the next line. This means that the commands follows a call to `c` are effectively ignored. This behaviour of `c` can be useful in challenges where there are only few possible outputs, particularly when combined with the conditional `/.../`.

An example is the 'Hello, World!' challenge, where `c` is shorter than `s`:

```
s/^/Hello, World!/ # 18 bytes
cHello, World!     # 14 bytes

```

Another example is this challenge (sed answer) to swap the strings `Good` and `Bad`. The outputs are restricted to being `Good` (when the input is `Bad`) or `Bad` (when the input is `Good`).

`s` gives 21 bytes:

```
s/Goo/Ba/;t;s/Ba/Goo/

```

Using `c` (in combination with `/.../`) gives 13 instead:

```
/B/cGood
cBad

```

If the input matches `/B/`, i.e. it the input is `Bad`, `Good` is printed and the program skips processing this input line. So the program only ever reaches the second line if the input doesn't match `B`, i.e. if the input is `Good`. Then in this case the output is set to `Bad`.
> 2 votes

# Answer
Mostly useless step:

```
y|A-y|B-z|

```

This will only translate `A` to `B` and `y` to `z` (... and `-` to `-` ;), but nothing else, so

```
sed -e 'y|A-y|B-z|' <<<'Hello world!'

```

will just return:

```
Hello world!

```

You could ensure this will be useless, for sample by using this on lower-case hexadecimal values (containing only `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `a`, `b`, `c`, `d`, `e` or `f`.)

A little worst:

```
sed '; ;/s/b;y|A-y|B-z|;s ;s/ //; ; ;' <<<'Hello world'
Hello world

```

Why did this **not** suppress the space?
> 1 votes

# Answer
In sed, the closest thing to a function that you can have is a label. A function is useful because you can execute its code multiple times, thus saving a lot of bytes. In sed however you would need to specify the return label and as such you can't simply call this "function" multiple times throughout your code the way you would do it in other languages.

The workaround I use is to add in one of the two memories a flag, which is used to select the return label. This works best when the function code only needs a single memory space (the other one).

**Example showing what I mean:** taken from a project of mine to write a small game in sed

```
# after applying the player's move, I overwrite the pattern space with the flag "P"
s/.*/P/
b check_game_status
:continue_turn_from_player
#code

```

---

```
b calculate_bot_move
:return_bot_move
# here I call the same function 'check_game_status', but with a different flag: "B"
s/.*/B/
b check_game_status
:continue_turn_from_bot
#code (like say 'b update_screen')

```

---

```
:check_game_status   # this needs just the hold space to run
#code
/^P$/b continue_turn_from_player
/^B$/b continue_turn_from_bot

```

The labels should be golfed of course to just one letter, I used full names for a better explanation.
> 1 votes

# Answer
# Combine `s` substitutions

The `s` command takes many bytes (4 + 1 for the statement separator), so combining them can save bytes.

An example: the following is at 17 bytes

```
s/\S+ //
s/\S+$//

```

while combining the two substitutions gives 15 bytes

```
s/^\S+ |\S+$//g

```
> 1 votes

# Answer
Okay, here's a weird functioning of (GNU) sed's regex. For example, if the pattern space is only `qqq`, then the extended regex `s/^|q|$/<&>/g` gives `<q><q><q>`. Try it online!

I'm not sure, but I think it is because if a character matches, then do the empty strings surrounding it. So because the terminal `q` matches, the match also includes the end of the pattern space, so `$` by itself doesn't get matched because otherwise it would overlap with the previous match (and likewise for `^` and even I think for word boundaries and the like).

An example where this is useful is in the following (rather contrived) task:

* an input of `a` should give `ab`,
* and inputs matching `/a(c+)/` should give `ab\1b`, for example, an input of `accc` should give `abcccb`

Without the trick I can get 11 bytes (with the `-E` flag)

```
s/a|c+/&b/g

```

but using it gives 10 bytes

```
s/a|$/&b/g

```

Try it online!

(Do let me know if there is a better example that uses this behaviour).
> 1 votes

# Answer
# Use back references

Most people know that you can mark some parts of your regex with `\(\)` and later refer to it as `\1` (or `\2` for the second and so on) in your substitution.

But you hardly ever see *back references*, using `\1` in the regex itself. For extended regular expressions (option `-E` to `sed`), this has been removed from the standard, but GNU `sed` supports it anyhow, so it works at tio.run, for example.

For example, this ERE `(.)\1` matches a double character or this one `(.).*\1` appearing twice in the pattern space. See here for an example, how this makes things easier (and much shorter!).

Complicated task like this one looking for matches in a file or this one or this one would almost be impossible without this feature.

# Math with back references

And it's great for teaching `sed` to count. I know you can solve some of those problems using `y`, but as soon as you have more than one thing to increment or decrement, this is the way to go. See examples here or here or try the 151-byte decimal add online to examine how it works.
> 1 votes

---
Tags: code-golf, tips
---


title: Decode the date in Christmas Eve format

text:
# Question
Title: Decode the date in Christmas Eve format
This is the inverse of "Encode the date in Christmas Eve format."

Write a program that takes as input the string `Christmas`, possibly followed by  `Eve` between 1 and 365 times, and outputs the date encoded in YYYY-MM-DD format, or any format from which the year, month, and date can be easily obtained. Assume that the "Christmas" being referred to is the next Christmas, or today, if today is Christmas. Christmas is December 25.

Your program may also take the current date as input in the same format used for output, if there is no way to get it in the language you use.

Remember to take leap years into account.

Examples if run on or before Christmas 2023:

| Input | Output |
| --- | --- |
| Christmas | 2023-12-25 |
| Christmas Eve | 2023-12-24 |
| Christmas Eve Eve | 2023-12-23 |
| Christmas Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve | 2023-11-15 |
| Christmas Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve | 2022-12-26 |

# Answer
# Excel, ~~35~~ 33 bytes

```
"26/12"-ROWS(TEXTSPLIT(A1,," "))

```

Input in cell `A1`.
> 5 votes

# Answer
# shell + coreutils, ~~78~~ 76 bytes

```
d=date\
$d-d$(((`$d+%s`>=`$d+%s -d12/26`)+`$d+%Y`))-12-25-$((${#1}/4-2))day

```

Attempt This Online!

Edit: the previous version outputs (incorrectly) the *previous* Christmas \\$n\\$-th Eve when the current date is between December 26th and 31st.
> 5 votes

# Answer
# PowerShell, ~~35~~ ~~56~~ 55 bytes

```
($c=date 12/26)|% *ars((date)-ge$c)|% *ys(-$args.Count)

```

Try it online!

+21: Fixed to get the *next* Christmas eve, including when called between 12/26 and 12/31, thanks to @i-t-delinquent.
-1: Setting/outputting $c, thanks to @julian

Returns DateTime objects.
Nothing remarkable; gets a date object for the 26th of December, adds a year if past the 25th, and subtracts the argument count as days.
`(date) -ge $c` will return a boolean, which will be evaluated as 0/1 when passed to AddYears, which expects an integer.

*Disclaimer:* Don't use 'date' in your day-to-day scripts; this is fit for golfing only. PowerShell will first search through all available commands, and if it doesn't find one named "date", it will prepend "Get-" and try again. Very slow, and will fail if a command line program date.exe exists somewhere in the path.

**Ungolfed** (method call using ForEach-Object; golfs better):

```
$c = Get-Date 12/26
$c | ForEach-Object -MemberName AddYears ((Get-Date) -ge $c) | ForEach-Object -MemberName AddDays (-$args.Count)

```

**Ungolfed alternative** (usual method call):

```
$c = Get-Date 12/26
$c.AddYears((Get-Date) -ge $c).AddDays(-$args.Count)

```
> 4 votes

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

```
s=>new Date(/c 2[6-9]|c 3/.test(t=new Date)+t.getFullYear(),11,109-s.length>>2)

```

Try it online!

73 bytes if take today as input.
> 3 votes

# Answer
# Google Sheets / Microsoft Excel, ~~30~~ ~~67~~ ~~58~~ ~~50~~ 39 bytes

`=(year(now()+6)&"-12-26")-(len(A1)-5)/4`

Put the input in cell `A1` and the formula in `C1`.

The formula outputs a numeric dateserial value. The question specifies *"any format from which the year, month, and date can be easily obtained"*. To obtain those date fields, format the formula cell as **Format \> Number \> Date** or similar.

The question also specifies "next Christmas". When the current moment is within 26 to 31 December, the formula looks at Christmas *next year*, and outputs a date counting down from that Christmas date. Otherwise, it looks at Christmas in the current year.

The first part of the formula obtains a string in the ISO8601 format `yyyy-MM-dd` which is a valid date format in any locale. The string gets coerced to a dateserial while subtracting the second part (the number of `Eve`s plus one.)

You can include formatting in the formula at a cost of 9 bytes (Google Sheets):

`=to_date((year(now()+6)&"-12-26")-(len(A1)-5)/4)`

...or at a cost of 17 bytes (Microsoft Excel):

`=text((year(now()+6)&"-12-26")-(len(A1)-5)/4,"M/d/yyyy")`

| input | expected | output (as Date) |
| --- | --- | --- |
| Christmas | 2023-12-25 | 12/25/2023 |
| Christmas Eve | 2023-12-24 | 12/24/2023 |
| Christmas Eve Eve | 2023-12-23 | 12/23/2023 |
| Christmas Eve Eve Eve... (40 times in total) | 2023-11-15 | 11/15/2023 |
| Christmas Eve Eve Eve... (364 times in total) | 2022-12-26 | 12/26/2022 |
> 3 votes

# Answer
# Python, ~~136 125 121~~ 94 bytes

Returns a `datetime` object.

```
lambda x:d((d.today()+t(6)).year,12,25)-t(len(x)/4-2)
from datetime import*
d=date
t=timedelta

```
> 2 votes

# Answer
# GAWK, 74 65 64 bytes

```
$0=mktime(strftime("%Y",systime()+720^2)" 12 26 0 0 0")-86400*NF

```

Try it online!

* -9 bytes, reassign `$0`, as epoch time will be `>1` will print the line. And replaced the make time to one day later to account for the first field.
* -1 byte, replaced `518400` with its root squared `720^2`

This will print the epoch time of the date you asked for. From which you can easily obtain any date format.
> 2 votes

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

```
s=>new(D=Date)(new D(+new D+5184e5).getFullYear(),9,353-s.length>>2)

```

Try it online!

From tsh's

-3B from Arnauld
> 2 votes

# Answer
# Julia, 72 bytes

```
using Dates
~s=tonext(==((12,26))∘monthday,today())-Day(sum(<('D'),s))

```

Attempt This Online!

Based on the Julia solution to the inverse problem

* -2 bytes thanks to MarcMush: replace `sum(==(' '),s)` with `count(' ',s)`
* -1 byte thanks to MarcMush: replace `count(' ',s)+1` with `sum(<('D'),s)`
> 2 votes

# Answer
# , ~~67~~ 65 bytes

```
\(x)as.Date(ISOdate(substr(Sys.Date()+6,1,4),12,25))-nchar(x)/4+3

```

Attempt This Online!

A function taking a string and returning a date.

* Thanks to @pajonk for saving two bytes
> 2 votes

# Answer
# Bash + GNU date, ~~48~~ ~~43~~ 38 bytes

```
date -d`date -d6day +%Y`1226-$#day +%F

```

We count the number of arguments and subtract that from Boxing Day (26 December).

If today is after Christmas, we need to start from *next* Boxing Day, so we look ahead six days from today to find the appropriate year to use.

Thanks to Nahuel Fouilleul for suggesting we read standard input rather than command arguments, saving 5 bytes.

Thanks to Neil for suggesting we let the shell do the splitting and counting.

Online version
> 2 votes

# Answer
# PowerShell, 61 bytes

```
(Get-Date '25/12').AddDays(-($c-split"( )"-match"^\s").count)

```

Try it online!

`$c` would need to be declared with the "Christmas eve" string in the same environment. Would output in the format of:

> 23 December 2023 00:00:00

*FYI doesn't seem to run in the browser but runs fine in ISE and PowerShell console.*
> 1 votes

# Answer
# Go, 108 bytes

```
import(."time";."strings")
func f(s string)Time{return Date(Now().Year(),12,25-Count(s," Eve"),0,0,0,0,UTC)}

```

Attempt This Online!

Returns a `Time`.
> 1 votes

# Answer
# 05AB1E, ~~103~~ 36 bytes

```
ð¢žg’IO.ÃÍ Dâì.‚±(~D[ÿ-12-25],-ÿ)’.E

```

Outputs the date in `yyyy-mm-dd` format with automatically trailing `"\nok"`.

Try it online or verify all test cases.

**Explanation:**

```
ð¢       # Count the amount of spaces in the (implicit) input-string
  žg     # Push the current year
    ’IO.ÃÍ Dâì.‚±(~D[ÿ-12-25],-ÿ)’
         # Push dictionary string "IO.puts Date.add(~D[ÿ-12-25],-ÿ)",
         # where the first `ÿ` is filled with the pushed year
         # and the second `ÿ` is filled with the amount of spaces of the input
     .E  # Evaluate it as Elixir:

```

```
IO.puts           % Print
~D[y-12-25]       % Christmas Day of the given year `y` as Date-object
Date.add(...,-n)  % After we went back in time the given `n` amount of days

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `’IO.ÃÍ Dâì.‚±(~D[ÿ-12-25],-ÿ)’` is `"IO.puts Date.add(~D[ÿ-12-25],-ÿ)"`.
> 1 votes

# Answer
# Jelly, 84 bytes

```
ċ⁶“£ṠạƙƓḢỤṢ]Ẉ¬z=æ¦ŀḥØo?3€ñḥqṅẹḂḟ⁽ḟ“œ4»j “ÇyṪ⁸ȷ6Ė|6¤ƤY¢ḷ/q³ȦþỵMñ§.ṣs)~ṛßẠ»Ḳ¤ṣḢ}¹jʋƒŒV

```

Try it online!

A monadic link taking a Jelly string and printing a date to STDOUT. Jelly lacks date handling, so this builds and executes a Python expression that looks like this:

```
print(__import__("datetime").date((__import__("datetime").date.today()+__import__("datetime").timedelta(7)).year,12,25)-__import__("datetime").timedelta(x))

```

where `x` is the count of spaces in the input. Most of the Jelly code is compressed strings. These are used to shorten the code along with some simple substitutions of repetitive code (`__import__("datetime").`, `date` and `timedelta(`). `__import__()` is used because Jelly doesn’t import the datetime module itself.
> 1 votes

# Answer
# Scala, 98 bytes

Golfed version. Try it online!

```
x=>java.time.LocalDate.of(java.time.LocalDate.now.plusDays(6).getYear,12,25).minusDays(x.size/4-2)

```

Ungolfed version. Try it online!

```
import java.time.{LocalDate, Period}

object Main {
  def main(args: Array[String]): Unit = {
    println(f("Christmas Eve Eve Eve").toString)
  }

  def f(x: String): LocalDate = {
    val d = LocalDate.now().plusDays(6)
    val christmas = LocalDate.of(d.getYear, 12, 25)
    val daysDiff = x.length / 4 - 2
    christmas.minusDays(daysDiff)
  }
}

```
> 1 votes

# Answer
# Charcoal, 65 bytes

```
≔”8±AHＦ@ε✂hλ”θ≔≕⁺θ.resolutionη⁻▷θ⟦Ｉ…⭆¹⁺▷⁺θ.today⟦⟧×⁷η⁴⁺²χ²⁵⟧×№Ｓ η

```

Try it online! Link is to verbose version of code. Based on @NickKennedy's Jelly answer. Explanation:

```
≔”8±AHＦ@ε✂hλ”θ

```

Get the compressed string `datetime.date`, which prefixes all of the necessary functions.

```
≔≕⁺θ.resolutionη

```

Get the result of `datetime.date.resolution`, which is another way of saying `datetime.timedelta(1)`, but golfier because it reuses the string `datetime.date`.

```
⁻▷θ⟦Ｉ…⭆¹⁺▷⁺θ.today⟦⟧×⁷η⁴⁺²χ²⁵⟧×№Ｓ η

```

Take today's date, add on 7 days, cast to string so that the year can be extracted (Charcoal can't call instance methods), create Christmas Day in that year, then subtract a day for each space in the input string.
> 1 votes

# Answer
# Ruby, ~~80~~ 73 bytes

```
f=->s,a=Date.today{a.to_s=~/12-25/?a-(s.count'v'):f[s,a+1]}
require"date"

```

Try it online!

Instead of using date range I've switched to recursion.

`a.to_s=~/12-25/?` If current date matches /25-12/ then
`a-(s.count'v')` return that day minus how many 'v' in input
`:f[s,a+1]` else try next day
> 1 votes

# Answer
# Elixir, 110 bytes

```
fn(s)->Date.add(Date.new(Date.utc_today.year,12,25)|>elem(1),-(s|>String.graphemes|>Enum.count(& &1==" ")))end

```

Only my second or third Elixir answer, so can definitely be golfed.

Try it online.

**Explanation:**

```
fn(s)->                    % Function with string argument and Date return-type
  Date.add(                %  Go back in time by adding a negative amount of days:
    Date.new(              %   Create a new {:ok,Date}-tuple:
      Date.utc_today.year, %    Using the current year
      12,25)               %    And Christmas Day
    |>elem(1),             %   Extract the Date from the ok-tuple
    -(                     %   And go back the following amount of days:
      s|>String.graphemes  %    Convert the input-string to a list of unicode characters
       |>Enum.count(& &1==" ")))end
                           %    And then count the amount of space characters among them

```
> 1 votes

# Answer
# Lua, 108 bytes

```
d=os.date a=86400_,n=(...):gsub(' ',0)t=os.time()while d('%d%m',t)~='2512'do t=t+a end print(d('%x',-n*a+t))

```

Try it online!
> 1 votes

# Answer
# Perl 5 -MPOSIX, 71 bytes

```
sub f{strftime"%Y%m%d",1..3,25-$_[0]=~s/E//g,11,(gmtime 518400+pop)[5]}

```

Try it online!

```
sub f{
  strftime "%Y%m%d",       #return date as eight digits YYYYMMDD
    1..3,                  #three args for sec, min, hour, values dont matter
    25-$_[0]=~s/E//g,      #day of month, 25th minus the number of E's ("Eve"s)
                           #strftime deals with overflow into negative numbers
                           #in previous months and years potentially
    11,                    #11 = December with 0=the first month January
    (gmtime 518400+pop)[5] #output year found from given date pop'ed from @_ the
                           #input args plus 6 days (518400 sec) to account for
                           #the last days of the year after 25th Dec that should
                           #focus on Christmas the next year
  }

```
> 1 votes

# Answer
# APL (Dyalog Unicode), with `date` and `days` dfns, 43 bytes

```
{n(⊃(n←date days)0 0 6+3↑⎕TS),12,27-⌊4÷⍨≢⍵}

```

Try it online!
> 1 votes

---
Tags: code-golf, date
---


title: Source Code Metamorphosis

text:
# Question
Title: Source Code Metamorphosis
mbomb007 asked us to make a self mutilating program. Its an interesting challenge, but I personally don't like to encourage my programs to be self-mutilating. I like to think that, at the heart of every program is a beautiful butterfly waiting to break out.

As such, for my first ever Code Golf challenge, I challenge Stack Exchange to metamorph a butterfly. Your program should accept its own code as input and output `I am a caterpillar!` followed by the code for another program in the same language (you may put a divider between the outputs or not... but we're talking butterflies, so prettiness counts!). This second program should output `I am a beautiful butterfly!`

Metamorphosis: This program should modify itself, which is why it is being passed itself as input. I don't want a boring nested program that is nothing but a print statement `I am a caterpillar!` followed by printing source code. You have to metamorph the code itself, so the most boring acceptable answer is one which prints `I am a caterpillar`, then rips a string out of the input (which happens to be code) and prints that. Of course, this is a very tricky little requirement to write, so it should be thought of as a "spirit of the challenge." The formal requirement is going to be set at "If your program is given a random string of the same length as your program, there should be less than a 5% chance of printing `I am a butterfly` when the second program is run."

Summary:

* Write a program which, when provided its own code as input, prints `I am a caterpillar!` followed by a block of source code (with a delimiter between them or not).
* This second block of source code, when compiled/interpreted as the same language, prints `I am a beautiful butterfly!`
* If your program is not fed its own source code as input, and is instead given a random string of characters that does not match its own code, the result must either fail to compile/interpret, or not print `I am a butterfly!` for at least 95% of random strings (spirit: you are expected to read your own source code from the input, and stitch it together into a butterfly).
    + *I'm comfortable with you not proving this, so long as you're holding to the spirit of the metamorphosis idea, modifying your own code, but if you're trying to play loophole games to work around using your inputs, expect to have to prove it.*
* Standard loopholes apply

I'd like these to be judged by their beauty, but that's a decidedly non-quantitative approach, so the usual "number of bytes" route can be used to judge

**Bonus**: -20% - pick any 3 letter string that doesn't match the first 3 letters of your program. If I run the caterpillar program, but modify the input so that the first 3 character are changed to the specified ones, print `I am Batman!` instead. Always be Batman. (*Same random string rules apply for this... metamorphosis!*)

Trivial example (python):

```
"""
    print "I am a beautiful butterfly!"
    #print "I am Batman!"
"""
import sys
code = sys.stdin.read()
if code.startswith("YYZ"):
   # swap the comments between the print statements
   code = code.replace("#print", "_a").replace("print", "#print").replace("_a", "print")
code = [3:] # remove """ or XYZ
code = code.split('"""')[0]
print "I am a caterpillar!"
print code

```

# Answer
# Befunge-98, 602 bytes

```
                                        "^@<"v@@
                                     "'I'"00v>00g::
                                   "@v"0v@@@>g::a">#"
                                 "a">v@@>      0g::'"1>                                 /
                             ":\"'"v@>            'm'"00g:a                       >"@v$"
 "lufituaeb"'"'v00ga"@v\"'":'b\00v@>                :'a\":*84>"00ga"\>@@@@_,#:>"00g:a'<'"
"et"'"'va'v'":'l\00g5k:'""y!">>v@>                    g::'''""ut"'"'>a'<'""fr"'"00g3k:'">
 "ma"00g>'I~48*-~48*-+#@_>:#,_@>                        '"aa"---"aa"!rallipretac"00g:'a\

```

Tested in PyFunge.

When run with a string not starting with 2 spaces (probability well over 95% when random) outputs nothing. This isn't exactly what the OP is looking for, but fits the specification.

When passed a string starting with 2 spaces (like itself) outputs this:

```
I am a caterpillar!

---

"!y"       "l"v
v"te"     "rf"<
>"tu"'   "b"\v@
 v"beautiful"<
  >:#,_@@@@>\
 >48*:"a"\:$v@
  "ma"   v@#>
   'I'   <@^

```

The lower part of that, in turn, outputs:

```
I am a beautiful butterfly!

```
> 63 votes

# Answer
# PHP, 74 Bytes

```
<?=~¶ßž’ßžß,$s="caterpillar!",strtr($argv[1],[$s=>~šžŠ‹–™Š“ßŠ‹‹š™“†Þ]);

```
* `<?=` is equivalent to `<?php echo` and can take several comma separated values to output
* `¶ßž’ßžß` and `šžŠ‹–™Š“ßŠ‹‹š™“†Þ` are valid constant names in PHP, but because the constants do not exist are treated as string literal. `~` inverts them to `"I am a "` and `"beautiful butterfly!"` (saving a byte for one quotation mark each)
* `strtr` replaces "caterpillar!" with "a beautiful butterfly!" in the argument
> 18 votes

# Answer
# Pyth, ~~50~~ 46 bytes

```
"I am a caterpillar!"+<z8"beautiful butterfly!

```

## Explanation

```
"I am a caterpillar!"        print "I am a caterpillar!"
 z<8                         first 8 chars of input
+   "beautiful butterfly!    add "beautiful butterfly!" to that and print

```

The resulting source code is

```
"I am a beautiful butterfly!

```

Which basically prints the text.
> 7 votes

# Answer
# Perl 6, ~~60~~ 56 bytes

```
say "I am a caterpillar!"; s/\S+\!/beautiful butterfly!/

```

Requires -p to run properly; I have accounted for this in the byte count. Sadly one of the downsides to Perl 6 is that the syntax is much more strict now...
> 6 votes

# Answer
# Retina, 53 bytes

```
caterpillar
beautiful butterfly
^
I am a caterpillar!

```

**Prints out:**

```
I am a caterpillar!beautiful butterfly
beautiful butterfly
^
I am a beautiful butterfly!

```

Notice that there is no separator between `I am a caterpillar!` and the new program. The new program expects no input.
> 4 votes

# Answer
# `bash` / `awk` / `cksum` \- ~~179.2~~ ~~169.6~~ 168 bytes

```
awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'

```

Demo:

```
$ awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'<<'E'
> awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'
> E
I am a caterpillar!
echo|awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."10"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'
$ echo|awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."10"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'
I am a beautiful butterfly!

# Batman!
$ awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'<<'E'
> xyzawk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'
> E
I am Batman!

# Invalid input
$ awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0}'<<'E'
> awk '/^xyz/{print"I am Batman!";exit}NF{("cksum<<<'"'"'"substr($0,100))|getline r;if(r!~/^6689751/)exit}{printf"I am a %s%."!NF"s!\n",NF?"caterpillar":"beautiful"," butterfly"}NF&&sub(/!NF/,10){print"echo|"$0{'
> E

```

I hope the 20% applies for *any* string starting with `xyz`, otherwise the original count is ~~224~~ ~~212~~ 210 bytes (fixed the `"I am Batman!"` part).

Transformation done: replaces the only occurrence of the literal `!NF` with `10`, so that `" butterfly"` is also printed using the `printf`.

Performs a simple `cksum` on a portion (i.e. the remainder) of the source code, hence its requirement as well.

~~Caveat: first input must end with `'`.~~ Not so much a caveat as to suppress *wrong* input...

No second input is expected.
> 3 votes

# Answer
# Python - 184 bytes -20% for bonus = 147.2

```
""""""
import sys;c=sys.stdin.read();print"I am a caterpillar!";x=c[3:] if"\'''"!=c[:3] else c
print x+c[:3]
""";print"I am a beautiful butterfly!" """
''';print"I am Batman";'''

```

To print `I am batman`, replace the first three double quotes with single quotes in the input.(First line is `'''"""`)
> 1 votes

# Answer
# FMSLogo, 169.6 bytes

from 212 * 0.8

```
to f[:b]1
type[I am]type char 32 ifelse name? "b[make "b last :b
print[a caterpillar!;beautiful butterfly
](foreach[23 8 19 2][10 32 13 97][repeat ?2[ignore pop "b]repeat ?1[type pop "b]])][print[Batman!]]print "

```

The online logo interpreters I know of do not support every logo feature this program is using. calormen.com, for example, does not support anonymous functions. The program works on FMSLogo 8.3.2.

Luckily for readability, the newlines are either necessary or have no cost. The program, in caterpillar form, is a variadic function which defaults to 1 argument. Pass the program code to it by pasting it between the bars in `f "||`. It will print "I am a caterpillar!", then splice together the output program from its own parts character by character by popping from the string. It will output this:

```
type[I am]type char 32 print[a beautiful butterfly!]

```

I should change the `type char 32` part, but then the splicing code will look less epic.

In Batman form, achieved by replacing `to`  with `;` , thereby commenting out the function header, the Program will run when you load the file, and obviously not take input. For me, non-declarative code pasted into the edit window runs twice, but loading it as a file will still make it run once. To decide whether it is Batman, the program checks whether the input variable exists.
> 0 votes

# Answer
# morsecco:  ~~190~~  193 bytes

Morsecco itself ignores those boring strings without any dots or dashes, but if you provide it as input, why not use it and modify it?

```
I am a caterpillar!beautiful butterfly!.    .-. - - . - .-. -... -.. --.. --.- --.- -.-. -..-- - - --- -.-. --- - .. -.-. -.-.. - .-. -.-. . . . - . -.- .- -.-. .... .   -.- - ---  -.-. ... ---

```
* `. .-. - - . - .-.` to `R`ead the own source code and stdin
* `-... -.. --.. --.- --.-` for a `B`inary `D`iff and to `Z`eroskip the `Q`uit if it's identical
* `-.-. -..-- - - ---` `C`uts the caterpillar string, keeps a copy and `O`utputs it
* `-.-. --- - .. -.-. -.-.. - .-. -.-. .` gets rid of the caterpillar and sets in the butterfly
* `. . - . -.- .- -.-. ....` `K`onverts from `·T`ext to hide the butterfly in the caterpillar
* `. -.- - --- -.-. ... ---` finally `C`oncatenates the code for butterfly `O`utput and put this code `O`ut.

Other languages may need to do some ASCII art now, but the output of the code (if given the correct source, otherwise silently quit) will be:

```
I am a caterpillar!
.   -..-..- -..... --....- --.--.- -..... --....- -..... --...-. --..-.- --....- ---.-.- ---.-.. --.-..- --..--. ---.-.- --.--.. -..... --...-. ---.-.- ---.-.. ---.-.. --..-.- ---..-. --..--. --.--.. ----..- -....-  -.- - ---

```

and honestly: It looks a little like crawling caterpillars anyhow! Maybe like a millipede, but you wouldn't expect this to turn into a butterfly, wouldn't you? But execute it with morsecco and be surprised about the metamorphosis!
> 0 votes

---
Tags: code-golf, source-layout
---


title: Jelly's Untruth

text:
# Question
Title: Jelly's Untruth
Jelly has an "untruth" atom: . This takes a non-empty array of positive integers and returns a Boolean array with **1**s at the indexes in the input. For example:

```
[1,3,5,6]Ṭ ⁼ [1,0,1,0,1,1]
[5]Ṭ       ⁼ [0,0,0,0,1]
[2,1,1,2]Ṭ ⁼ [1,1]
[5,4,3]Ṭ   ⁼ [0,0,1,1,1]
[1]Ṭ       ⁼ [1]

```

Try it online!

Note that Jelly uses 1-indexing, and that duplicate values in the array have no effect.

Your job is to take a non-empty array of positive integers and output the result of applying  on the array. If your language has a builtin with this exact behaviour, you may not use it. You may also choose to use zero indexing if you wish (so the above examples become `[0,2,4,5], [4], [1,0,0,1]` etc) and take non-negative integers in the input array.

You may use your language’s `true` and `false` values instead of `1` and `0`, so long as they are the Boolean values rather than general truthy and falsey values (e.g. `0` and non-zero integers). You may also take input as a set if your language has that type. The input is not guaranteed to be sorted and may be in any order. The output may not have trailing zeros (or any other "trailing" values).

This is so the shortest code in bytes wins.

# Answer
# APL (Dyalog Extended), 3 bytes

```
×¯⍸

```

Try it online!

A tacit function. Banning only the *exact* built-in actually gives APL a massive advantage!

### How it works

```
×¯⍸
  ⍸  ⍝ Takes a vector v and gives another vector containing v[i] copies of i
     ⍝ for each index i
 ¯   ⍝ Inverse of the above, which counts occurrences of i which becomes v[i]
×    ⍝ Signum of each number, converting any positive count to 1

```

---

# APL (Dyalog Unicode), 7 bytes

```
⊢∊⍨∘⍳⌈/
(⍳⌈/)∊⊢

```

Try it online!

Non-Extended solution. Works exactly like the 3-byte Jelly solution.

# APL (Dyalog Unicode), 7 bytes

```
∨⌿-↑⍤0×

```

Try it online!

A fun way to do the job. For each number `n`, create a length-`n` vector that has a 1 at the end and 0 for the rest. Then promote the entire array to a matrix (padding as necessary) and take the logical OR of the rows.
> 13 votes

# Answer
# Python 3, <sup>~~42~~</sup> 41 bytes

*-1 thanks to @ovs*

```
lambda a:[i+1in a for i in range(max(a))]

```

Try it online!
> 7 votes

# Answer
# Brachylog, 11 bytes

```
{~l,1}ᵐz₁⌉ᵐ

```

Try it online!

It's certainly interesting to consider what approach is the best in a language without a concept of a Boolean. 0-indexed. For some reason the unbound variables that are *pretty much* 0 are actually displaying as variables, so tack a  onto the end if that's a problem.

```
{    }ᵐ        For each element of the input:
   ,1          append 1 to
 ~l            something that long.
       z₁      Ragged zip. (i.e. non-cycling, doesn't stop until all lists are exhausted)
         ⌉ᵐ    Take the maximum of each column.

```
> 6 votes

# Answer
# Wolfram Language (Mathematica), 20 bytes

```
SparseArray[#->1^#]&

```

Try it online!

Returns a `SparseArray`.
> 6 votes

# Answer
# Haskell, 30 bytes

```
f a=map(`elem`a)[1..maximum a]

```

Try it online!

The relevant function is `f`, which takes as input a list of integers `a` (1-indexed) and returns a list of `Bool`s.
> 6 votes

# Answer
# Neim, 5 bytes

```
Γ₁

```

Try it online!

Explanation:

```
        # Get Greatest element
        # Inclusive range: (0 .. n]
  Γ      # For each element in range do:
   ₁     # 1st input line
        # Check that the int is in the list

```
> 5 votes

# Answer
# Factor, 35 bytes

```
[ 0 [ 2^ bitor ] reduce make-bits ]

```

Try it online!

Takes a sequence of 0-based indices and returns a virtual boolean sequence of `t` (true) and `f` (false).

### How it works

```
[
  0 [ 2^ bitor ] reduce  ! Reduce all 2^n bitmasks by bitwise OR
                         ! for each n in the sequence
  make-bits  ! Create a virtual sequence of bits from the integer
]

```
> 5 votes

# Answer
# Ruby 2.7, 33 bytes

```
->a,n=[0]*a.max{a.map{n[_1]=1};n}

```

Try it online!

Uses the 0-indexing. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes.
> 4 votes

# Answer
# Java (JDK), 82 bytes

```
a->{int m=0,r[];for(int i:a)m=i>m?i:m;r=new int[m];for(int i:a)r[i-1]=1;return r;}

```

Try it online!
> 4 votes

# Answer
# MATL, 4 bytes

```
v1i(

```

Try it online! Or verify all test cases.

### Explanation

```
v   % Concatenate stack contents vertically. Gives an empty array
1   % Push 1
i   % Take input
(   % Assignment indexing: write 1 into the array at the input positions.
    % This automatically extends the array and fills with 0
    % Implicit display

```
> 4 votes

# Answer
# Jelly, 3 bytes

```
Ṁe€

```

Try it online!

This does seem somewhat difficult to outdo.

```
  €    Map over (the range from 1 to)
Ṁ      the largest element of the input:
 e     is it in the input?

```

Silly, 0-indexed bonus:

# Jelly, 6 bytes

```
2*BUo/

```

Try it online!

```
2*        For each element of the input, raise 2 to that power.
  B       Convert to binary
   U      and reverse each,
     /    then reduce by
    o     vectorizing logical OR.

```
> 3 votes

# Answer
# Husk, 7 bytes

```
mo±€¹ḣ▲

```

Try it online!

I feel like I'm missing a way to do this with `η`.

## Explanation

```
mo±€¹ḣ▲
     ḣ▲ range 1..max(input)
mo      map each to
   €¹   whether it's present in the input(index if present, 0 if not)
  ±     and take the sign of that

```
> 3 votes

# Answer
# 05AB1E, ~~4~~ 3 bytes

```
ZLå

```

Try it online!

Yes it is just a port of every other answer.

## Explained

```
ZLå
ZL   # Push the range: [1, max(input)]
  å  # Vectorise: is item in input? over that range

```
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 49 bytes

```
a=>Enumerable.Range(1,a.Max()).Select(a.Contains)

```

Try it online!

Saved 3 bytes thanks to caird

Saved 1 byte thanks to didymus

Saved 2 bytes thanks to NonlinearFruit
> 3 votes

# Answer
# , 12 bytes

```
e.~1 i.@+>./

```

Try it online!

0-indexed; similar to Bubbler's APL solution

# K (oK), ~~14~~ 12 bytes

-2 bytes thanks to coltim

```
{~^x?!1+|/x}

```

Try it online!

0-indexed
> 3 votes

# Answer
# Nim, 60 58 bytes

```
func t[S](n:S):S=
 for i in 1..n.max:result.add int i in n

```

Try it online!
> 3 votes

# Answer
# , ~~32~~ ~~25~~ 24 bytes

```
function(x)1:max(x)%in%x

```

Try it online!

Taking advantage of `%in%` operator and abusing weird precedence.

*-1 thanks to Dominic van Essen*

### 21 bytes using `scan`

```
1:max(x<-scan())%in%x

```

Try it online!
> 3 votes

# Answer
# Scala, 19 bytes

```
i=>1 to i.max map i

```

Try it online!

Returns a `Seq` of `Boolean`s. Takes a `Set[Int]` as input, since sets are also predicates in Scala. If a list is taken as input, `i.contains` would have to be used instead.
> 3 votes

# Answer
# Octave, 17 bytes

```
@(x){y(x)=1,y}{2}

```

Anonymous function that takes a row (or column) vector as input and produces a row vector as output.

Uses the last trick on this list to effectively include several statements in an anonymous function.

**Try it online!**
> 3 votes

# Answer
# PowerShell, 45 bytes

1-indexed, which felt weird to do in a 0-indexed language. Accepts only non-negative integers; negative indexing in powershell is 1-based, so this answer breaks down for negative cases.

```
$a=,0*($args|sort)[-1];$args|%{$a[$_-1]=1};$a

```

Try it online!
> 3 votes

# Answer
# Julia 1.0, ~~25~~ 21 bytes

```
x->1:max(x...).∈[x]

```

Try it online!
> 3 votes

# Answer
# , ~~24~~ 23 bytes

*Edit: -1 byte thanks to pajonk*

```
F[scan()]=1;F&!is.na(F)

```

Try it online!

A different approach to pajonk's R answer.
Shorter at time of posting, but this is a precarious situation, as it would be longer in a fair 'apples-with-apples' comparison (using `scan()` for both approaches).
> 3 votes

# Answer
# JavaScript (Node.js), ~~45~~ 44 bytes

```
a=>a.map(b=>c[b]=1,c=[])&&[...c].map(d=>d|0)

```

Try it online!

This implementation uses zero indexing and returns an array of `0`s and `1`s.

I think the code isn't very difficult to understand. Here's a summary explanation:

* `c=[]`: create the output array.
* `a.map(b=>c[b]=1 )`: for each value of the input array, set 1 at the respective index in the output array.
* `[...c].map(d=>d|0)`: convert the output array into a non-sparse array, then map each element to a 32-bit integer. This will map `1` to `1` and `undefined` to `0`.

Thanks to Neil for -1 byte.
> 3 votes

# Answer
## x86\_64 (zero indexed, length given), 19 16 bytes

Raw machine code:

```
31 c0 57 f3 aa 5f 89 d1 8d c6 04 07 01 e2 f9 c3

```

Uncommented assembly:

```
        .intel_syntax noprefix
        .globl untruth
untruth:
        xor     eax, eax
        push    rdi
        rep stosb byte ptr [rdi]
        pop     rdi
        mov     ecx, edx
.Lloop:
        lodsd   dword ptr [rsi]
        mov     byte ptr [rdi + rax], 1
        loop    .Lloop
.Lend:
        ret

```

### Explanation

I'm not too good at x86, so I am pretty sure there is a better way to do this.

C signature:

```
// System V ABI (rdi, rsi, rdx, rcx)
void untruth(bool *out, const uint32_t *indices, uint32_t indices_len, uint32_t out_len);

```

It's my function, I can order the parameters however I please.

First: `memset(out, 0, out_len)` using `rep stosb`. Since we need to save the pointer and `stosb` clobbers it, we `push` and `pop` it.

The standard calling conventions say that the direction flag is always cleared when calling, so we know this will be a forwards operation.

```
untruth:
        xor     eax, eax
        push    rdi
        rep stosb byte ptr [rdi]
        pop     rdi

```

Using the fancy `loop` instruction, loop through each index in the array, storing 1 to `out[index]`

```
        mov     ecx, edx
.Lloop:
        lodsd   dword ptr [rsi]
        mov     byte ptr [rdi + rax], 1
        loop    .Lloop

```

At the end of the loop, return.

```
.Lend:
        ret

```

Note: It also happens to be x86-compatible on the binary level.

Thanks to Neil for the -3 bytes (using lodsd)!

## x86\_64 (zero indexed, calculates max), 28 bytes

Raw machine code:

```
31 c0 57 51 af 0f 42 47 fc e2 f9 91 56 56 5f f3
aa 5f 59 5e ad c6 04 07 01 e2 f9 c3

```

Assembly:

```
        .intel_syntax noprefix
        .globl untruth
        # void untruth(const uint32_t *indices{rdi}, char *out{rsi}, uint32_t indices_len{rcx})
untruth:
        xor     eax, eax
        push    rdi
        push    rcx
.Lfind_max:
        scasd   eax, dword ptr [rdi]
        cmovb   eax, dword ptr [rdi - 4]
        loop    .Lfind_max
.Lfind_max.end:
        xchg    ecx, eax
        push    rsi
        push    rsi
        pop     rdi
        rep stos byte ptr [rdi], al
        pop     rdi
        pop     rcx
        pop     rsi
.Lloop:
        lodsd   eax, dword ptr [rsi]
        mov     byte ptr [rdi + rax], 1
        loop    .Lloop
.Lloop_end:
        ret

```

This version will check for the maximum itself, *but the output buffer provided must be large enough.*

Probably many things here can be optimized.

## Explanation

Note that the parameters are different than the first: `indices` is in `rdi`, `out` is in `rsi`, `rdx` is unused, and `indices_len` is in `rcx`.

I don't know why `scasd` uses `rdi` but whatever.

This is a simple max loop. It compares each dword in `indices`, and sets `eax` to the maximum.

This seems to be smaller than doing something with `lodsd`, although that 4 byte `cmovb` is pretty yucky.

```
untruth:
        xor     eax, eax
        push    rdi
        push    rcx
.Lfind_max:
        scasd   eax, dword ptr [rdi]
        cmovb   eax, dword ptr [rdi - 4]
        loop    .Lfind_max

```

Since we know `ecx` will be zero due to the loop condition, we can set `ecx` to the maximum *and* set `eax` to zero in one byte.

```
.Lfind_max.end:
        xchg    ecx, eax

```

Unfortunately, our output array is in `rsi`, not `rdi`. We `push` and `pop` twice to mov without the `REX` tax and save a copy, then do a `memset` with `rep stosb`.

```
        push    rsi
        push    rsi
        pop     rdi
        rep stos byte ptr [rdi], al
        pop     rdi

```

Now we need to get `indices` and `indices_len` from the stack. Note that this time, we put `indices` into `rsi`.

```
        pop     rcx
        pop     rsi

```

For each dword in indices, `out[indices[i]]` to 1 using `lodsd` and `loop`

```
.Lloop:
        lodsd   eax, dword ptr [rsi]
        mov     byte ptr [rdi + rax], 1
        loop    .Lloop

```

Return.

```
.Lloop_end:
        ret

```
> 3 votes

# Answer
# Uiua, 4 bytes

```
>0⍘⊚

```

Try it!

0-indexed

```
>0⍘⊚
  ⍘⊚  # inverse where (occurrences)
>0    # where is it greater than zero?

```
> 3 votes

# Answer
# Add++, 9 bytes

```
L,dbMR$€e

```

Try it online!

Given that no-one besides me really uses Add++, I figured I wouldn't be sniping anyone

## How it works

```
L,dbMR$€e - Anonymous lambda function
L,        - Define the lambda function. Takes l as input
  d       - Duplicate; STACK = [l l]
  bM      - Maximum;   STACK = [l max(l)]
  R       - Range;     STACK = [l [1 2 ... max(l)]]
  $       - Swap;      STACK = [[1 2 ... max(l)] l]
  €       - Over each:
    e     -   In l?

```
> 2 votes

# Answer
# Perl 5, `-pa` 33 bytes

```
@r[@F]=(1)x@F;map$_+=0,@r;$_="@r"

```

Try it online!

`0` indexed. Input and output are space separated.
> 2 votes

# Answer
# Zsh, 44 bytes

```
for i ({1..${${(nO)@}[1]}})<<<$[$@[(I)$i]>0]

```

Try it online!

Explanation:

```
             ${(nO)@}                          # sort the arguments numerically, in reverse
           ${        [1]}                      # take the first (i.e. maximum value)
       {1..              }                     # range from 1 to that
for i (                   )                    # for each i
                                @[(I)$i]       # find the index of `i` in `argv`, or 0 if not present
                              $[        >0]    # is that positive? (1 or 0)
                           <<<                 # print

```
> 2 votes

# Answer
# JavaScript (ES6), 50 bytes

```
a=>a.map(g=(x,i)=>x&&g(--x,g,o[x]|=++i/i),o=[])&&o

```

Try it online!

### Commented

```
a =>                // a[] = input array
  a.map(            // for each ...
    g = (x, i) =>   // ... value x at position i in a[]:
      x &&          //   if x is not equal to 0:
        g(          //     do a recursive call:
          --x,      //       decrement x
          g,        //       force i to a non-numeric value
          o[x] |=   //       update o[x]:
            ++i / i //         set it to 1 if i is numeric (≥ 0)
                    //         or just coerce it to a number otherwise
                    //         (i.e. undefined values are turned into 0's)
        ),          //     end of recursive call
      o = []        //   start with o[] = empty array
  ) && o            // end of map(); return o[]

```
> 2 votes

# Answer
# Japt, 6 bytes

```
rÔõ!øU

```

Try it

```
ÍÌÆøXÄ

```

Try it
> 2 votes

# Answer
# Zsh, 25 bytes

```
for x;a[x]=1
<<<${a/#%/0}

```

Try it online!

The `#` and `%` in globs act like the regex `^` and `$` anchors, but for full words instead of lines.

Altenatively, `<<<${a:///0}` works.

---

Very similar Zsh solution to another question
> 2 votes

# Answer
# C (gcc) with `-m32`, 87 bytes

Zero-indexed, using `-1` as a sentinel value for arrays.

To get the size of the output array, I recursively scan the input array and allocate the output array with the maximum size found (plus one for the sentinel.) After that, each input index is marked and the resulting array is returned.

```
*j;*g(i,m)int*i;{~*i?g(i+1,m<*i?*i:m)[*i]=1:(j=calloc(++m+1,4))[m]--;i=j;}f(i){g(i,0);}

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~52~~ 49 bytes

```
t=foldl(#)[]
l#i=take i(l++[0,0..])++1:drop(i+1)l

```

Try it online!

* 0 indexed
> 2 votes

# Answer
# Gaia, 7 bytes

```
e:⌉┅¤Ė¦

```

Try it online!

Identical to, e.g., pajonk's R answer.

```
e:		# eval implicit input as a list and duplicate
⌉┅		# take the max of the list and compute [1...M]
¤		# swap so [1..M] is on the bottom
Ė¦		# For each element of [1..M], is it in the input list?

```
> 2 votes

# Answer
# jq, ~~30~~ ~~29~~ 27 bytes

```
range(max)as$a|[$a+1]-.==[]

```

Try it online!

## Explanation

```
range(                      # the 0-range up to
  max)                      # the largest item of the input - 1
as$a                        # And assign it to $a

|                           # And then, for every item in $a:
[$a+1]-.==[]                #     Is the item + 1 contained in the original input?

```
> 2 votes

# Answer
# Vyxal, 6 bytes

```
Gɾƛ?$c

```

Try it Online!

```
Gɾƛ?$c
G      Maximum
 ɾ     Range
  ƛ    Map:
   ?     Push the input
    $    Swap
     c   Contains?

```
> 2 votes

# Answer
# Desmos, 38 bytes

```
f(l)=[0^{(k-l)^2}.maxfork=[1...l.max]]

```

Try It On Desmos!
> 2 votes

# Answer
# Pyt, 5 bytes

```
Đ↑ř⇹∈

```

Try it online!

```
Đ          implicit input; Đuplicate
 ↑         get maximum
  ř        řangify
   ⇹∈      is each element in [1,2,...,max] in the input?; implicit print

```
> 2 votes

# Answer
# Thunno 2, 3 bytes

```
GRƇ

```

Try it online!

#### Explanation

```
GRƇ  # Implicit input
G    # Maximum
 R   # Range
  Ƈ  # Contains
     # Implicit output

```
> 2 votes

# Answer
# Go 1.21+, 112 bytes

```
import."slices"
func f(I[]int)(o[]int){
for i:=1;i<=Max(I);i++{e:=0
if Contains(I,i){e=1}
o=append(o,e)}
return}

```

Attempt This Online!

Uses the new `slices.Max` function from the standard library, which doesn't exist pre-1.21.
> 2 votes

# Answer
# Noulith, 33 bytes

```
\l->for(x<-1to(max l))yield x in l

```

Uses 1-indexing.

Try it online!
> 2 votes

# Answer
# TI-BASIC, 13 bytes

```
seq(max(I=Ans),I,1,max(Ans

```

Takes input in `Ans`.
> 2 votes

# Answer
# Retina 0.8.2, 51 bytes

```
.+
$*01
+`^((.)*).?(.*)¶(?<-2>.)*(?(2)$)(.+)
$1$4$3

```

Try it online! Takes input as a newline-separated list but link includes test suite that converts from comma-separated for ease of use. Outputs a binary string. 0-indexed. Explanation:

```
.+
$*01

```

Convert each entry into a string of `0`s followed by a `1`.

```
+`

```

For each additional entry, its `1` is merged into the first line in turn:

```
^((.)*)

```

Match the prefix on the first line.

```
.?(.*)¶

```

Skip the digit above the `1`, if any, but keep the suffix of the first line.

```
(?<-2>.)*(?(2)$)

```

Match a prefix of the same length on the second line.

```
(.+)

```

Match the any `0`s needed for padding and the `1`.

```
$1$4$3

```

If the first line was shorter than the second line, then append the suffix of the second line to the first line, otherwise insert the `1` from the second line in between the prefix and suffix of the first line.

Example 1: When merging `10001` with `001`, the prefix is two characters, `10` (captured as `$1`) on the first line corresponding to `00` on the second line. The `1` (captured as `$4`) from the second line is then inserted, and then the suffix `01` on the first line (captured as `$3`) is appended, resulting in `10101`.

Example 2: When merging `101` with `00001`, the prefix is three characters `101` (captured as `$1`) on the first line corresponding to `000` on the second line. The `01` (captured as `$4`) from the second line is then appended (`$3` is empty as the first line is shorter than the second), again resulting in `10101`.
> 1 votes

# Answer
# Charcoal, 9 bytes

```
⭆⊕⌈θ∧№θι¹

```

Try it online! Link is to verbose version of code. Outputs a binary string. 0-indexed. Explanation:

```
   θ        Input array
  ⌈         Maximum
 ⊕          Incremented
⭆           Map over implicit range and join.
     №      Count of
       ι    Current index
      θ     In input array
    ∧       Logical Or
        ¹   Literal `1`
            Implicitly print

```

1-indexed version is also 9 bytes:

```
⭆⌈θ∧№θ⊕ι¹

```

Try it online! Link is to verbose version of code. Explanation: Same as the first version, except that the increment is in a different place.
> 1 votes

# Answer
# FALSE, 183 bytes

```
0$$b:c:d:[^$1_=~][$32=$[%%0a:[a;b;=~][a;1\[$0=~][\10*\1-]#%*a;0=~[+]?a;1+$b;=~[@\]?a:]#0b:c;1+c:$d;>[$d:]?1_]?~[b;1+b:48-]?]#%[b;d;>~][0$e:[$1=~e;c;=~&][e;1+$e:øb;=[%1]?]#.32,b;1+b:]#

```

Try it online!

NOTE: Since FALSE does not actually have arrays, input is space-separated numbers with one space at the end, and output is the same.

Most of this answer is just input string to int.

0 indexed.
> 1 votes

# Answer
# HBL, 9.5 bytes

```
'?(*(*-,.
*().(0(/.

```

1-indexed. Try it here!

### Explanation

The helper function on the first line takes two arguments: a list of indices and a specific index. It returns 1 if the index appears in the list, 0 if it does not.

```
'?(*(*-,.
    (*   )   For each element of
        .    the list,
      -      subtract it from
       ,     the index
  (*      )  Take the product of the resulting list
'?           Is the product zero?

```

The main function takes a list of indices and returns the "untruthed" list of 0's and 1's:

```
*().(0(/.
    (0    )  Range from 1 to
      (/ )   the maximum of
        .    the list
*            For each element,
 ()          call the helper function
   .         with the index list as first argument
             and the element of the range as second argument

```
> 1 votes

# Answer
# Arturo, 29 bytes

```
$->a->map 0..max a'x->a<>a--x

```

Try it
> 1 votes

# Answer
# PowerShell, 33 bytes

```
1..($a=$args|sort)[-1]|%{$_-in$a}

```

Try it online!

Takes in an array of positive integer, returns an array of booleans.

I stole the test cases from Zaelin's answer, thank you!

## Explanation

```
1..($a=$args|sort)[-1]            # Generate a range from 1 to the maximum number in the input
                      |%{$_-in$a} # If the number is in the input list, returns $true, otherwise $false

```
> 1 votes

# Answer
# Rust, ~~94~~ 83 bytes

Saved 11 bytes thanks to @att

Golfed version. Attempt This Online!

```
|a:Vec<_>|->Vec<_>{(1..=*a.iter().max().unwrap()).map(|i|a.contains(&i)).collect()}

```

Ungolfed version. Attempt This Online!

```
fn f(a: Vec<usize>) -> Vec<bool> {
    let max_val = *a.iter().max().unwrap();
    (0..max_val).map(|i| a.contains(&(i+1))).collect()
}

```
> 1 votes

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