title: Print a Cantor Set

text:
# Question
Title: Print a Cantor Set
## The Challenge

Build a N-Leveled Cantor Set.

> The Cantor ternary set is created by repeatedly deleting the open middle thirds of a set of line segments.

The program receives one parameter `N` (a integer number) and then prints (in console or similar way) a Cantor Set of N levels. The print can only contain undescore (`_`) and whithe spaces characters. The parameter can be positive or negative and the sign indicates the Cantor Set construction orientation: If `N > 0` the Cantor Set is constructed downwards and if `N < 0` the Cantor Set is constructed upwards. If `N = 0` then the program prints a single line (`_`).

For example:

N = 2

```
_________
___   ___
_ _   _ _

```

N = -2

```
_ _   _ _
___   ___
_________

```

N = 3

```
___________________________
_________         _________
___   ___         ___   ___
_ _   _ _         _ _   _ _

```

N = -3

```
_ _   _ _         _ _   _ _
___   ___         ___   ___
_________         _________
___________________________

```

## Winning criteria

As it is a code golf challenge, the shortest code wins.

Edited: Modify 0 input by ugoren's suggestion.

# Answer
## GolfScript, 49 42 40 chars

```
~.abs.3\?'_'*\{.3%..,' '*\++}*](0>2*(%n*

```

With thanks to hammar for 42-\>40.

My best attempt yet at a more number-theoretic approach is sadly much longer:

```
~.abs:^3\?,{3^)?+3base(;1+1?.'_'*^@-)' '*+}%zip\0>2*(%n*

```

or

```
~.abs 3\?:^,{6^*+3base.1+1?.('_'*@,@-' '*+}%zip\0>2*(%n*

```

and I suspect that the length of `base` and `zip` will make it impossible to catch up.
> 10 votes

# Answer
## Python, 116 113 104 103 chars

```
n=input()
d=n>0 or-1
for i in range(n*d+1)[::d]:
 s='_'*3**i
 while i<n*d:s+=len(s)*' '+s;i+=1
 print s

```

Older algorithm topped out at 113 characters

```
r=input()
u='_'
l=[u]
for _ in abs(r)*u:o=len(l[0]);l=[s+o*' '+s for s in l]+[u*o*3]
print'\n'.join(l[::r>0 or-1])

```
> 7 votes

# Answer
# Ruby (97)

Based on Steven Rumbalski's python version:

```
n,r=$*[0].to_i,[?_]
n.abs.times{z=r[0].size;r=r.map{|s|s+' '*z+s}+[?_*z*3]}
puts n<0?r:r.reverse

```

## Previous attempts, both same length (112)

Build lines from parts:

```
c=->x,n{n<1??_*x :(z=c[s=x/3,n-1])+' '*s+z}
r=(0..m=(n=$*[0].to_i).abs).map{|i|c[3**m,i]}
puts n<0?r.reverse: r

```

Start with one line, make holes in it:

```
r=[?_*3**a=(n=$*[0].to_i).abs]
a.times{|c|r<<r[-1].gsub((x=?_*o=3**(a-c-1))*3,x+' '*o+x)}
puts n<0?r.reverse: r

```
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~32~~ 31 bytesSBCS

```
{' _'[⊖⍣(0>⍵)∧⍀1⍪1≠3⊥⍣¯1⍳3*|⍵]}

```

Try it online!

Saved 1 byte thanks to Adám by changing the conditional flipping `⊖⍣(0>⍵)` to *inside* the indexing.

**How it works**:

This answer builds on the mathematical properties of the Cantor set itself. It is known that a number is in the Cantor set iff its ternary expansion contains no 1s. So what we do is discretize the interval \[0, 1\], compute the ternary expansion of the numbers in there, check which ones have a 1 in their ternary expansion and exclude them from the subsequent iterations of the drawing.

```
{' _'[⊖⍣(0>⍵)∧⍀1⍪1≠3⊥⍣¯1⍳3*|⍵]}   ⍝ dfn expecting an integer as right argument (e.g. 2)
                         ⍳3*|⍵     ⍝ discretize the interval (e.g. 0 1 2 3 4 5 6 7 8)
                   3⊥⍣¯1           ⍝ compute the ternary expansion in columns (e.g.
                                   ⍝    0 0 0 1 1 1 2 2 2
                                   ⍝    0 1 2 0 1 2 0 1 2 )
               1⍪1≠                ⍝ find which numbers are ≠ from 1 and
                                   ⍝ append a row of 1s (e.g.
                                   ⍝    1 1 1 1 1 1 1 1 1
                                   ⍝    1 1 1 0 0 0 1 1 1
                                   ⍝    1 0 1 1 0 1 1 0 1 )
             ∧⍀                    ⍝ propagate the 0s downwards (e.g.
                                   ⍝    1 1 1 1 1 1 1 1 1
                                   ⍝    1 1 1 0 0 0 1 1 1
                                   ⍝    1 0 1 0 0 0 1 0 1 )
      ⊖⍣(0>⍵)                     ⍝ mirror if the input number is negative
 ' _'[                        ]    ⍝ and index into ' _' to draw

```
> 5 votes

# Answer
## Perl, 93 chars

```
@x=($t=$x=_ x 3**($a=abs($n=<>)),map$x.=$"x($x=~s/(.)../$1/g).$x,1..$a);say for$n<0?sort@x:@x

```

I thought I'd try to see how well Peter Taylor's GolfScript solution would port to Perl. Notable features include the use of `sort` instead of `reverse` to save three chars, using the fact that a space sorts before `_`.
> 3 votes

# Answer
## C, 219 193 179 143 136 131 characters

Followed another of Petyer Taylor's ideas, plus an improvement of my own, saved 6 more.
Integrated some tips from @PeterTaylor, plus copied his main function, with slight changes, which save a character (is it fair to copy it? Since neither of us will win this one, I guess it isn't too bad).
I thought of a significant improvement in how my recursion works, and after seeing Peter Taylor's answer, I implemented it to regain the lead. When reading his answer again, I saw that I did almost exactly what he did. So this seems like the hybridization he suggested.
Also simplified the loop in `main`, keeping the same length.
And took Peter's trick to print newline, instead of `puts("")` \- saves a character.

Removed `int` from variable declaration - a warning, but saves 4 chars.
New algorithm doesn't calculate 3^x in advance, but uses a single loop to print 3^x characters.
Can save one more by defining `int*v`, but then 64bit won't work.
Characters count excludes whitespace (which can be removed).

```
o,i,n;
p(c) {
    n-- ?
        p(c),p(o>n?c:32),p(c)
    :
        putchar(c);
    n++;
}
main(c,v)int**v; {
    for(n=abs(c=atoi(v[1]));i<=n;i++)o=c+n?n-i:i,p(95),puts("");
}

```

Older algorithm, 219 chars:

```
p(l,o,i,m,c,j) {
    for(;i<(m=l);i++)
        for(j=0,c=95;m/o||!putchar(c);j++)
            i/m%3-1||(c=32),m/=3;
    puts("");
}
main(c,v,n,i,l,o)int**v;{
    (n=atoi(v[1]))<0?n=-n:(c=0);
    for(i=n,l=1;i;i--)l*=3;
    o=c?1:l;
    for (;i<=n;i++)p(l,o,0),c?o*=3:(o/=3);
}

```
> 2 votes

# Answer
## C (163 161 chars)

```
i,l,N;f(n,m,s){if(n){s=--n<l?m:s;f(n,m,s);f(n,s,s);f(n,m,s);}else
putchar(m);}main(n,v)int**v;{for(i=N=abs(n=atoi(1[v]));i+1;i--)l=n<N?N-i:i,f(N,95,32),f(0,10);}

```

Borrows a couple of tricks from ugoren's answer, but the core logic is quite different. I couldn't follow his for loop, so it may be possible to hybridise and save a few more.
> 2 votes

# Answer
## Common Lisp, 217 210 characters

```
(defun m(x)(flet((c(n v)(if(= n 0)`((,v))(cons(substitute v nil(make-list(expt 3 n)))(mapcar #'append(c(1- n)v)(c(1- n)" ")(c(1- n)v))))))(format t "~{~{~a~}~%~}"(let((r(c(abs x)'_)))(if(< x 1)(reverse r)r)))))

```

**Expanded:**

```
(defun m(x)
  (flet((c(n v)
    (if(= n 0)
       `((,v))
       (cons(substitute v nil(make-list(expt 3 n)))
            (mapcar #'append
                    (c(1- n)v)
                    (c(1- n)" ")
                    (c(1- n)v))))))
   (format t "~{~{~a~}~%~}"(let((r(c(abs x)'_)))(if(< x 1)(reverse r)r)))))

```

I figure if the Lisp code manages to beat any initial count for another language (C, 219) I'm doing OK :)
> 2 votes

# Answer
# J, ~~44~~ ~~39~~ ~~38~~ 37 bytes

```
' _'{~0&>_&(]|.)(,:1)1&(,],.0&*,.])~|

```

Uses iteration to build the next set starting with 1 (representing `_`) initially.

## Usage

```
   f =: ' _'{~0&>_&(]|.)(,:1)1&(,],.0&*,.])~|
   f 0
_
   f 1
___
_ _
   f _1
_ _
___
   f 2
_________
___   ___
_ _   _ _
   f _2
_ _   _ _
___   ___
_________
   f 3
___________________________
_________         _________
___   ___         ___   ___
_ _   _ _         _ _   _ _
   f _3
_ _   _ _         _ _   _ _
___   ___         ___   ___
_________         _________
___________________________

```

## Explanation

```
' _'{~0&>_&(]|.)(,:1)1&(,],.0&*,.])~|  Input: integer n
                                    |  Absolute value of n
                (,:1)                  The array [1]
                     1&(          )~   Repeat abs(n) times starting with x = [1]
                                 ]       Identity function, gets x
                            0&*          Multiply x by 0
                               ,.        Join the rows together
                         ]               Identity function, gets x
                          ,.             Join the rows together
                     1  ,                Prepend a row of 1's and return
      0&>                              Test if n is negative, 1 if true else 0
         _&(   )                       If n is negative
             |.                          Reverse the previous result
            ]                            Return that
                                       Else pass the previous result unmodified
' _'                                   The string ' _'
    {~                                 Select from the string using the result
                                       as indices and return

```
> 2 votes

# Answer
# , ~~141 139~~ 137 bytes

```
m=abs(n<-scan());write("if"(n<m,rev,c)(c(" ","_")[Reduce(`%x%`,rep(list(matrix(c(1,1,1,1,0,1),3)),m),t(1))[,1+2^m-2^(m:0)]+1]),1,3^m,,"")

```

Try it online!

-15 bytes thanks too Giuseppe's use of `'('` as the identity function; `write` instead of `cat` to print output; clever use of`%x%`.

-2 bytes thanks to Kirill L. by using `c` instead of `'('` as the identity function.
> 2 votes

# Answer
## Python, 177 164 characters

```
N=input()
n=abs(N)
c=lambda x:0if x<1 else x%3==1or c(x/3)
r=["".join([["_"," "][c(x/3**i)]for x in range(3**n)])for i in range(n+1)]
print"\n".join(r[::N>0 or-1])

```
> 1 votes

# Answer
# Perl, 113 chars

```
$i=abs($I=<>);@w=$_='_'x3**$i;while($i--){$x=3**$i;s/(__){$x}/'_'x$x.' 'x$x/eg;push@w,$_}say for$I>0?reverse@w:@w

```

**Expanded:**

```
$i=abs($I=<>);
@w=$_='_'x3**$i;
while($i--){
    $x=3**$i;
    s/(__){$x}/'_'x$x.' 'x$x/eg;
    push@w,$_
}
say for$I>0?reverse@w:@w

```
> 1 votes

# Answer
## Batch, ~~265~~ ~~262~~ ~~242~~ ~~236~~ 235 bytes

```
@echo off
set/pn=
set c=%n%,-1,0
if %n% lss 0 set c=0,1,%n:-=%
for /l %%i in (%c%)do call:l %%i
exit/b
:l
set s=_
for /l %%j in (1,1,%n:-=%)do call:m %1 %%j
echo %s%
:m
set t=%s%
if %1 lss +%2 set t=%s:_= %
set s=%s%%t%%s%

```

Edit: Saved ~~12~~ 19 bytes thanks to @l4m2. Saved 8 bytes by removing the unnecessary `%a%` variable.
> 1 votes

# Answer
# JavaScript 121 bytes

Inner recursive function, then take care of backward output if needed

```
n=>(f=(n,t=n&&f(n-1),r=t[0])=>n?[r+r+r,...t.map(x=>x+t[n]+x)]:['_',' '],f=f(n<0?-n:n),f.pop(),n<0?f.reverse():f).join`\n`

```

*Less golfed*

```
n=>{
  var f = n => { // recursive function
    var t = n && f(n-1), r = t[0]
    return n
      ? [r+r+r, ...t.map(x => x+t[n]+x)]
      : ['_',' ']
  };
  f = f(n < 0 ? -n : n);
  f.pop(); // last row is all blanks
  if (n<0) f.reverse();
  return f.join`\n`
}

```

**Test**

```
var F=
n=>(f=(n,t=n&&f(n-1),r=t[0])=>n?[r+r+r,...t.map(x=>x+t[n]+x)]:['_',' '],f=f(n<0?-n:n),f.pop(),n<0?f.reverse():f).join`\n`

function go()
{
  var n=+I.value
  O.textContent = F(n)
}

go()
```

```
<input id=I type=number value=3 oninput='go()'>
<pre id=O></pre>
```
> 1 votes

# Answer
# PowerShell, 111 bytes

```
filter f{if($s=[math]::Sign($_)){($x=$_-$s|f|%{$_+' '*($l=$_|% Le*)+$_})|?{$s-1};'_'*3*$l;$x|?{$s+1}}else{'_'}}

```

Try it online!

Less golfed:

```
filter f{
    if($sign=[math]::Sign($_)){
        $x=$_-$sign|f|%{
            $_+' '*($length=$_|% Length)+$_
        }
        $x|?{$sign-1}  # output $x if $_ is negative
        '_'*3*$length
        $x|?{$sign+1}  # output $x if $_ is positive
    }
    else{
        '_'
    }
}

```
> 1 votes

# Answer
# Husk, 31 bytes

```
*±¹↑→a¹¡oṁ§ṘȯJ' R2←o/3LgR'_`^3a

```

Try it online!

Doesn't really use the cantor set, just uses a replacement method (and an infinite list).

Now, you may ask: why is an infinite list useful here? Here's an explanation:

## Explanation

```
¡oṁ§ṘȯJ' R2←o/3LgR'_`^3a
                       a take abs(n)
                 R'_`^3 repeat underscore n times(take n=3)
¡o                      iterate on this string, collecting results
                g       group the string into equal runs:
                        ["_________"]
  ṁ                     map each group to the following, and concatenate:
         R2←            repeat the first character twice
      J'                join with spaces
                        "_________" → "_ _"
            o/3L        take length /3 → 3
   §Ṙ                   Repeat each character that many times
                        "___   ___"

Then:
   ↑→a¹ take n+1 elements from the list
*±¹     multiply by sign(n) (reverse if negative)

```
> 1 votes

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

```
n=>f=(L=n<0&&n,R=n>0&&n)=>[...Array(r=3**(n>0?n:-n))].map(_=>((j++).toString(3)+1).indexOf(1)>(L>0?L:-L)?'_':' ',j=r+r).join``+`
${L++<R?f(L,R):''}`

```

Try it online!
> 0 votes

# Answer
# Python 2, 102 bytes

```
lambda n:'\n'.join(eval("[i+' '*len(i)+i for i in"*abs(n)+"'_'"+"]+['___'*len(i)]"*abs(n))[::n<1or-1])

```

Try it online!
> 0 votes

# Answer
# Prolog (SWI), ~~265~~ ~~232~~ 213 bytes

```
S-E-R:-between(S,E,R).
[]/R/R.
[H|T]/B/R:-T/[H,32,H|B]/R.
N+R:-(N>0->O is N-1,O+S,S/[]/R;R=`_`).
N*[H|T]:-1-N-_,writef("%n",[H]);N*T.
_*[]:-nl.
-N:-(0-N-J,K is N-J;N-0-I,J is -I,K is I-N),L is 3^K,J+R,L*R,1=0;1=1.

```

Try it online!
> 0 votes

# Answer
# Rust, 243 bytes

```
|i:i8|(0..i.abs() as usize).any(|j|print!("{}
",if i>0{f(j,3usize.pow(i as u32-1))}else{f(-i as usize-j-1,3usize.pow(-i as u32-1))})>());fn f(i:usize,j:usize)->String{if i<1{"_".repeat(j)}else{[f(i-1,j/3)," ".repeat(j/3),f(i-1,j/3)].concat()}}
```

Once again I win the prize for the longest answer

Attempt This Online!

# Rust, 247 bytes

```
|x:i32|->String{let r=(0..x.abs() as u32).map(|d|{(0..3_usize.pow(x.abs() as u32-1)).map(move|w|if(0..d).all(|v|w/3_usize.pow(x.abs() as u32-2-v)%3!=1){'_'}else{' '}).chain(['\n'])});if x<0{r.rev().flatten().collect()}else{r.flatten().collect()}};
```

Attempt This Online!
> 0 votes

---
Tags: code-golf, ascii-art, fractal
---


title: Which ghosts are missing?

text:
# Question
Title: Which ghosts are missing?
In this challenge, given a list of ghosts from Pac-Man, you must output which ghosts are missing. You must do it in as few bytes as you can

## Input

Input will consist of a string or list, which will include a number ghosts, which could include:

* Blinky
* Inky
* Pinky
* Clyde

However, input may also include Pac-Man (with that punctuation). So, the maximum amount of items in a list will be five, in any order. It can be assumed that no invalid items will be in the list

## Output

Output will consist of a string, or list. This will include of all the ghosts that are not in the input, in any order. However, if Pac-Man is in the input, all ghosts will be considered missing (because he eats them).

## Test cases

```
input: Clyde
output: Blinky, Inky, Pinky
alternate output: Inky, Pinky, Blinky
or one of the other 4 permutations

input: Clyde, Blinky # or however you delimit it
output: Inky, Pinky
alt: Pinky, Inky

input: Pac-Man, Clyde
Output: Blinky, Inky, Pinky, Clyde
or you could output one of the other 23 permutations

input:[null]
Output: Blinky, Inky, Pinky, Clyde
or you could output one of the other 23 permutations

```

This is codegolf, so the lower the bytecount, the better.

# Answer
# Jelly, ~~25~~ 22 bytes

```
Ff”-ȯ⁸“JLKqḤṢ&F⁻ı»ṣ⁶¤ḟ

```

This is a monadic function. I/O is in form of lists. Try it online!

### How it works

```
Ff”-ȯ⁸“JLKqḤṢ&F⁻ı»ṣ⁶¤ḟ  Monadic link. Argument: A (list of strings)

F                       Flatten A.
 f”-                    Filter it with the string "-" to detect "Pac-Man".
    ȯ⁸                  Flat logical OR with A. This yields A if there is no '-'
                        in the input, the string "-" otherwise.
                    ¤   Combine the three links to the left into a niladic chain.
      “JLKqḤṢ&F⁻ı»        Yield "Blinky Inky Pinky Clyde", using Jelly's built-in
                          English dictionary.
                  ṣ⁶      Split at spaces to yield
                          ["Blinky", "Inky", "Pinky", "Clyde"].
                     ḟ  Filter-false; removing all elements from that list that
                        appear in A or "-". This is a noop if A contains "Pac-Man".

```
> 3 votes

# Answer
## Retina, 45 bytes

```
A`-
$
,;BliNClyde,INPiN
N
nky,
D`\w+,
.*;|,$

```

The trailing linefeed is significant. Input and output are comma separated.

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

I did not expect to be able to show off Retina's latest addition (deduplication stages) so soon, but it's really helpful for this challenge. :)

**Stage 1: Anti-Grep**

```
A`-

```

Anti-grep stages discard all lines that match the given regex. The regex is just `-` and the input is always a single line, so this discards all ghosts if the input contains `Pac-Man`.

**Stage 2: Substitution**

```
$
,;BliNClyde,INPiN

```

This simply appends the fixed string `,;BliNClyde,INPiN`. This will be the list of ghosts in the output after some clean-up.

**Stage 3: Substitution**

```
N
nky,

```

Note that we've written the three `*nky` ghosts with an `N` in the previous stage (and omitted the comma after them), and we now expand this shorthand, which saves a couple of bytes. There is now a comma after every single ghost, and we've got the input ghosts and list of all ghosts separated by a semicolon.

**Stage 3: Deduplication**

```
D`\w+,

```

This is the new part. Deduplication stages find all instances of the given regex and discard all matched substrings which are equal to an earlier matched substring. The regex simply matches all the ghosts, both in the input and in the list of potential outputs. If the input contains a ghost, then the same ghost will be matched again in the second list and is discarded. Otherwise, the ghost is matched for the first time in the second list and kept. So after this, the list after the semicolon is our desired output. All that's left is a bit of clean-up:

**Stage 5: Substitution**

```
.*;|,$

```

We simply match everything up to the semicolon as well as the comma at the end of the string and remove them.
> 15 votes

# Answer
## Python 3, 75 bytes

```
lambda s:[x for x in['Blinky','Inky','Pinky','Clyde']if(x in s)<1or'-'in s]

```

Input is a comma-separated string, and the output will be a list.
> 7 votes

# Answer
# JavaScript ES6, ~~85~~ 78 bytes

As an anonymous function

```
a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)|a.some(v=>v[6]))

```

Today I learned about this `filter` function. Fun!

15 bytes saved thanks to Neil.

Usage:

```
(a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)||a.includes("Pac-Man")))(["Pac-Man"])
> ["Blinky","Inky","Pinky","Clyde"]
(a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)||a.includes("Pac-Man")))(["Pinky"])
> ["Blinky","Inky","Clyde"]
(a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)||a.includes("Pac-Man")))([])
> ["Blinky","Inky","Pinky","Clyde"]

```
> 6 votes

# Answer
# C, 171 bytes

Pass a NULL-terminated array of strings to `f()`, and it will print out the missing names.

```
*a[]={"Blinky","Inky","Pinky","Clyde",0},**s,**r,n;f(int**p){for(r=p;*p;)r=strcmp(*p++,"Pac-Man")?r:a+4;for(s=a;*s;++s){for(p=r,n=1;n&&*p;)n=strcmp(*s,*p++);n&&puts(*s);}}

```

Try it on ideone.
> 3 votes

# Answer
# Pyth \- 45 38  35 Bytes

```
=GwI!:G"a")j-["inky""pinky""blinky""clyde")cG

```

```
I!:=Gw"a")j-c:" p bl clyde"d"inky "dcG

```

```
j-c:" p bl clyde"d"inky "d?:z\aZYcz

```

*-1 more byte thanks to Leaky Nun!*

Input must be space delimited, all lowercase; outputs missing ghosts on separate lines unless pac-man is in the input.
> 3 votes

# Answer
# Ruby, ~~55~~ 49 bytes

Try it online!

*-6 bytes from @MartinEnder*

```
->a{%w"Blinky Inky Pinky Clyde"-(a*''=~/-/?[]:a)}

```

Ruby arrays can undergo set subtraction, making it very easy to remove the appropriate ghosts.
> 3 votes

# Answer
## Perl, 51 bytes

**50 bytes code + 1 for `-n`**

```
for$@(Blinky,Inky,Pinky,Clyde){print$@if/-/|!/$@/}g}

```

### Usage

```
perl -ne 'for$@(Blinky,Inky,Pinky,Clyde){print$@if/-/|!/$@/}' <<< 'Pac-Man, Clyde'
BlinkyInkyPinkyClyde

```

I can amend the output if necessary, adding a space after each ghost, for + 3 bytes replacing `print$@` with `print"$@ "`.

-6 bytes thanks to @MartinEnder!

---

## Perl, 53 bytes

**51 bytes code + 2 for `-na`**

An alternative solution, using the smartmatch operator:

```
print grep/-/~~@F|!($_~~@F),Blinky,Inky,Pinky,Clyde

```

### Usage

Requires a space separated list of input:

```
perl -nae 'print grep/-/~~@F|!($_~~@F),Blinky,Inky,Pinky,Clyde' <<< 'Clyde Pinky Inky'
Blinky
perl -nae 'print grep/-/~~@F|!($_~~@F),Blinky,Inky,Pinky,Clyde' <<< 'Clyde Pinky Inky Pac-Man'
BlinkyInkyPinkyClyde'

```
> 3 votes

# Answer
# Python 2, ~~66~~ ~~61~~ 96 bytes

```
g={"Blinky","Inky","Pinky","Clyde"};i=set(input());print",".join(g-i if not"Pac-Man"in i else g)

```

Input must be a list, output will be a string of names separated by a `,`.

61 bytes version that doesn't handle Pac-Man:

```
print",".join({"Blinky","Inky","Pinky","Clyde"}-set(input()))

```
> 2 votes

# Answer
# Haskell, 91 bytes

```
import Data.List
p l=(if elem"Pac-Man"l then id else(\\l))["Blinky","Inky","Pinky","Clyde"]

```

Input is a list of strings. It decides whether to use the list as-is or do a list-difference based on the presence of "Pac-Man".

For extra fun, here is no Pac-Man:

```
import Data.List
(["Blinky","Inky","Pinky","Clyde"]\\)

```

Will be improving this answer soon, did it super late at night.
> 2 votes

# Answer
## 05AB1E, ~~47~~ 44 bytes

```
•1g!Z~÷kÅ]°%Ï0›K/•35B0¡™svy'-åi,q}}v¹ykÌiy)˜

```

**Explaination**

```
•1g!Z~÷kÅ]°%Ï0›K/•35B0¡™                      # push list of the 4 ghosts
                        svy'-åi,q}}           # if Pac-Man is in input, quit and output list of all 4 ghosts
                                  v¹ykÌiy)˜   # otherwise, generate the list of ghosts missing from input

```

Try it online
> 2 votes

# Answer
## PowerShell v4+, 107 bytes

```
param($n)((($n+($x='Pinky','Inky','Blinky','Clyde')|group|?{$_.count-eq1}).Name),$x)['-'-in[char[]]-join$n]

```

A little clunky compared to others, as PowerShell lacks a ternary operator or any sort of `map`-style operator. As a result, we build our own.

Takes input `$n` as an explicit array of strings (e.g., `.\which-ghosts-are-missing.ps1 @('Clyde','Blinky')`. The rest of the program is one pseudo-ternary that's composed of an array that we index into via some logic `[...]`. The logic is simply whether the `-` character is anywhere in the input array `-join`ed together into a single string and then re-cast as a `char` array, in order to use the `-in` operator. Thus, if `Pac-Man` is in the input array, this will be `$TRUE` and the second element of the pseudo-ternary array will be chosen, else the first will be chosen.

If it's the case that `Pac-Man` is not in the array, the first portion of the pseudo-ternary array is output. That is a combination of the input array `$n` concatenated with an array of all the ghosts (saved into `$x`). We pipe that new array into `Group-Object` which will group like items together, then select using `Where-Object` (aliased via `|?{...}` only the items where their `.count` is `-eq`ual to `1`. That's all encapsulated in a parens, and we select the `.Name` property. This is where the v4 requirement comes in, as under v4 you can reference a hashtable label like this rather than using something like `|Select Name`, which saves several bytes.

Otherwise, since `Pac-Man` is in the input array, we need to output all the ghosts. Thankfully we already saved those into `$x`, so that's the choice in this case. Either way, the pipeline now contains a string array of ghosts, and output is implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @('Clyde')
Pinky
Inky
Blinky

PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @('Pac-Man','Clyde')
Pinky
Inky
Blinky
Clyde

PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @()
Pinky
Inky
Blinky
Clyde

PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @('Clyde','Blinky')
Pinky
Inky

```
> 2 votes

# Answer
## Python 3, 77 bytes

```
lambda i:[g for g in"Blinky Inky Pinky Clyde".split()if g not in i or"-"in i]

```

Here is another answer at 89 bytes that I was playing with but didn't work out :(

```
lambda i:[g for g in[s+"nky"for s in"Bli I Pi".split()]+["Clyde"]if g not in i or"-"in i]

```

And here's the original at 85 bytes:

```
lambda i,n="Blinky Inky Pinky Clyde":([g for g in n.split()if g not in i],n)["-"in i]

```

These all take a single string of the names separated by spaces/commas.
> 2 votes

# Answer
# Python 2, 151 bytes

As there are already Python answers using sets and strings I decided to restrict myself to work with lists, which turned out to be pretty long and uncompetitive. However, as the approach taken is different as the common one used, here it is:

```
o=['Blinky','Clyde','Inky','Pinky']
p=lambda x:[l for l in reduce(lambda z,x:z+[y+[x]for y in z],o,[[]])if sorted(l+x)==o][0]if'Pac-Man'not in x else o

```

where the expected input is a list of strings.

The approach is to bruteforce all possible combinations (without taking order into account) of 0,1,2,3 and 4 elements. This is done by

```
reduce(lambda z,x:z+[y+[x]for y in z],o,[[]])

```

which returns

```
[[], ['Clyde'], ['Pinky'], ['Clyde', 'Pinky'], ['Inky'], ['Clyde', 'Inky'],
['Pinky', 'Inky'], ['Clyde', 'Pinky', 'Inky'], ['Blinky'], ['Clyde', 'Blinky'],
['Pinky', 'Blinky'], ['Clyde', 'Pinky', 'Blinky'], ['Inky', 'Blinky'],
['Clyde', 'Inky', 'Blinky'], ['Pinky', 'Inky', 'Blinky'],
['Clyde', 'Pinky', 'Inky', 'Blinky']]

```

and find the one which, in addition to the input list results in the complete list of ghosts.

Then it is checked if the string `'Pac-Man'` is part of the input and, in case it is, the whole list of ghosts is returned. If not, only the ones which are not part of the input are returned.

Notice that the list containing all ghost names (`o`) is sorted alphabetically and the same goes for the list built as (`sorted(l+x)`). This is due to the fact that in Python, `['a','b']==['b','a']` is evaluated as `False` whereas `['a','b']==['a','b']` is evaluated as `True`.

3 bytes can be saved if it is permitted to return the answer as a list of lists ( by removing the `[0]` at the end of the first list comprehension). But as I'm not sure it is a valid output I am counting them.
> 2 votes

# Answer
# Pascal (FPC), ~~204~~ 200 bytes

Two loops, using a binary to find which ghosts+pacman are present. Takes the arguments from the commandline. Thanks to @manatwork for saving some more bytes!

```
var a:array[1..4]of string=('Blinky','Inky','Pinky','Clyde');i,s:Byte;begin for i:=1to ParamCount do s:=1<<Pos(ParamStr(i)[4],'nykd-')or s;for i:=1to 4do if(1<<i and s=0)or(s>31)then WriteLn(a[i])end.

```

Try it online!

Ungolfed:

```
var
  a: array[1..4] of string = ('Blinky', 'Inky', 'Pinky', 'Clyde');
  i, s: byte;
begin
  for i:=1 to ParamCount do
    s := 1 << pos(ParamStr(i)[4], 'nykd-') or s; // fill bits by shifting, check for unique 4th char of names, '-' in 'pac-man', could also use the 3rd char
  for i:=1 to 4 do
    if (1 << i and s=0) or (s>31) then    // check if bits are on
      writeln(a[i]);
end.

```

# Old version using a set, ~~227~~ 209 bytes

Two loops, using a set to find which ghosts+pacman are present. Takes the arguments from the commandline.

```
var a:array[1..4]of string=('Blinky','Inky','Pinky','Clyde');i:byte;s:set of 1..5;begin for i:=1to ParamCount do s:=s+[pos(ParamStr(i)[4],'nykd-')];for i:=1to 4do if not(i in s)or(5in s)then writeln(a[i]);end.

```

Ungolfed:

```
var
  a: array[1..4] of string = ('Blinky', 'Inky', 'Pinky', 'Clyde');
  i: byte;
  s: set of 1..5;
begin
  for i:=1 to ParamCount do
    s := s + [pos(ParamStr(i)[4], 'nykd-')]; // fill set with indxs
  for i:=1 to 4 do
    if not(i in s) or (5 in s) then    // check indx not in set or pac-man is
      writeln(a[i]);
end.

```
> 2 votes

# Answer
# PHP program, 84 bytes

```
<?print_r(array_diff([Blinky,Inky,Pinky,Clyde],in_array('Pac-Man',$argv)?[]:$argv));

```
* takes arguments from command line, prints result as an array.
* filename must not be any of the ghosts or 'Pac-Man'!
* short breakdown: remove (if 'Pac-Man' is in arguments: nothing, else all arguments) from all ghosts; print result recursively

examples:

```
>php -d error_reporting=0 ghosts.php Clyde
Array
(
    [0] => Blinky
    [1] => Inky
    [2] => Pinky
)
>php -d error_reporting=0 ghosts.php Clyde Blinky
Array
(
    [0] => Inky
    [1] => Pinky
)
>php -d error_reporting=0 ghosts.php Pac-Man Clyde
Array
(
    [0] => Blinky
    [1] => Inky
    [2] => Pinky
    [3] => Clyde
)

```

**PHP function, 90 bytes**

```
function p($a){return array_diff([Blinky,Inky,Pinky,Clyde],in_array('Pac-Man',$a)?[]:$a);}

```

takes and returns an array, use empty array for empty input, no other falsy value!

**further thoughts**

* replace `in_array(...)` with `strstr(join($argv),'-')` to detect `-` instead of `Pac-Man` (-2)
* use `ereg('-',join($argv))` instead (another -2)
* program could lose another 6 bytes in PHP\<5.4 with `register_globals` on
* to make the program print a comma-separated list: replace `<?print_r(` with `<?=join(',',` (+2). You may want to add `;echo""` to the call for a line break
> 1 votes

# Answer
## Pyke, ~~45~~ ~~39~~ ~~38~~ ~~37~~ 32 bytes

```
.d膎㧫l4dc].^D`\-R{!*

```

Try it here!

```
.d膎㧫l4dc - dictionary_lookup('blinky inky pinky clyde').title().split()
].^ - xor(^, input)
D`\-R{!* - ^*("-" not in input)

```
> 1 votes

# Answer
## Lotus Notes @Formula language, ~~85~~ ~~84~~ ~~75~~ 74 characters

*-1 character by reversing the @If assignment*

*-9 Changed @Contains(i;"-") to @Like(i;"%-%") and removed @Trim (not needed if displayed using space as seperator)*

*-1 by removing the newline*

Create a form with two fields: i (Text,Editable,Multi-value) and o (Text,Computed,Multi-value). Enter the following formula in o:

```
l:="Inky":"Pinky":"Blinky":"Clyde";@If(@Like(i;"%-%");l;@Replace(l;i;""))

```

From Notes client, create a new document using the form, enter the name(s) in the i field and press F9 to refresh the document. Answer displayed in field o.

This takes advantage of the fact that @Like and @Replace can can both be used either on a string or on a list of strings.
> 1 votes

# Answer
## Batch, 141 bytes

```
@set g= Blinky Inky Pinky Clyde
@for %%a in (%*)do @if %%a==Pac-Man goto l
@for %%a in (%*)do call set g=%%g: %%a=%%
@l
@echo(%g:~1,-1%

```

(Subtract 6 bytes for `:~1,-1` if leading and trailing whitespace is acceptable.) Requires Pac-Man in title case but the ghosts are case insensitive.
> 1 votes

# Answer
# jq, 69 characters

```
("Blinky Inky Pinky Clyde"/" ")as $a|if inside($a)then$a-. else$a end

```

Input is JSON, output is JSON, conditional syntax is pain.

Sample run:

```
bash-4.3$ jq '("Blinky Inky Pinky Clyde"/" ")as $a|if inside($a)then$a-. else$a end' <<< '["Clyde"]'
[
  "Blinky",
  "Inky",
  "Pinky"
]

bash-4.3$ jq '("Blinky Inky Pinky Clyde"/" ")as $a|if inside($a)then$a-. else$a end' <<< '["Pac-Man","Clyde"]'
[
  "Blinky",
  "Inky",
  "Pinky",
  "Clyde"
]

```

On-line test:
> 1 votes

# Answer
**C# ~~135 bytes~~126 bytes**

```
string[] g{"Blinky","Inky","Pinky","Clyde"};Console.WriteLine(String.Join(",",i.Contains("Pac-Man")?g:g.Except(i).ToArray()));

```

(where i is a string array containing the input)

After looking at the other examples, I see that C# is rather a verbose language :)
> 1 votes

# Answer
# TSQL(sqlserver 2016), 114 bytes

**Golfed:**

```
DECLARE @ VARCHAR(99) = 'Blinky,Inky,Pinky,Clyde'

SELECT*FROM STRING_SPLIT('Blinky,Inky,Pinky,Clyde',',')EXCEPT SELECT*FROM STRING_SPLIT(@,','WHERE @ NOT LIKE'%-%'

```

**Ungolfed:**

```
DECLARE @ VARCHAR(99) = 'Blinky,Inky,Pinky,Clyde'

SELECT * FROM STRING_SPLIT('Blinky,Inky,Pinky,Clyde',',')
EXCEPT
SELECT * FROM STRING_SPLIT(@,',')
WHERE @ NOT LIKE'%-%'

```

**Fiddle**
> 1 votes

# Answer
# Japt, 38 bytes (Non-competing)

Takes input as an array of strings, outputs an array of strings

```
`B¦nky Inky Pky CÒè`¸kUø`Pac-M` ?N:U

```

Try it online
> 0 votes

# Answer
# 05AB1E, 27 bytes

```
…ê¥¦¨™Å#'y«.•S:-•ª™IDJ{нaиK

```

Try it online or verify all test cases.

**Explanation:**

```
…ê¥¦¨™Å           # Push dictionary string "blink ink pink"
                  #  STACK: "blink ink pink"
       #          # Split it on spaces
                  #  STACK: ["blink","ink","pink"]
        'y       '# Push "y"
                  #  STACK: ["blink","ink","pink"],"y"
          «       # Append it to each string in the list
                  #  STACK: ["blinky","inky","pinky"]
           .•S:-• # Push compressed string "clyde"
                  #  STACK: ["blinky","inky","pinky"],"clyde"
             ª    # Append it to the list
                  #  STACK: ["blinky","inky","pinky","clyde"]
              ™   # Titlecase each string
                  #  STACK: ["Blinky","Inky","Pinky","Clyde"]
I                 # Push the input-list
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"]
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"]
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[]
 D                # Duplicate it
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],["Pac-Man"]
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],["Pinky"]
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[],[]
  J               # Join the copy to a single string
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],"Pac-Man"
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],"Pinky"
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[],""
   {              # Sort its characters
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],"-MPaacn"
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],"Pikny"
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[],""
    н             # Pop and leave just its first character
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],"-"
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],"P"
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[],""
     a            # Check if this is a letter
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],0
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],1
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[],0
      и           # Repeat the input-list that many times
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"],[]
                  #  STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"]
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"],[]
       K          # Remove those strings from the earlier quartet-list
                  #  STACK1: ["Blinky","Inky","Pinky","Clyde"]
                  #  STACK2: ["Blinky","Inky","Clyde"]
                  #  STACK3: ["Blinky","Inky","Pinky","Clyde"]
                  # (after which the resulting list is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `…ê¥¦¨™Å` is `"blink ink pink"` and `.•S:-•` is `"clyde"`.
> 0 votes

---
Tags: code-golf, string
---


# Question
Title: Word stays a word after taking away a letter
*This is a repost of this challenge*

---

# Challenge

There is an old, popular riddle:

> Find an English word with 8 letters that, taken away one letter, creates a new valid word. Repeat that until there are no letters left.

Example solution:

```
starting
staring
string
sting
sing
sin
in
I

```

Your task is to write a program, which takes a dictionary and outputs the longest word, that still occurs in the dictionary after repeatedly taking away a letter.

# Rules

* All words will be lower case and contain only ASCII-letters
* If multiple valid words have the same length you can output any one of those
* The dictionary will never be empty
* If there isn't any solution in the dictionary, then you have to output nothing/return an empty list/a falsey value
* You're allowed to output a list representing the process of removing each letter (eg.`['this', 'his', 'is', 'i']`)
* Default Loopholes apply
* This is , so the shortest answer wins!

# Examples

```
In: ['this', 'hat', 'his', 'hi', 'is', 'i', 'a', 'at']
Out: this

In: ['pings', 'aid', 'ping', 'ad', 'i', 'in', 'a']
Out: aid

In: ['a', 'ab', 'bac']
Out: ab

In: ['a', 'aa', 'aaaa']
Out: aa

In: ['as', 'i', 'his', 'that', 'ping', 'pin', 'in', 'was', 'at', 'this', 'what', 'is', 'it', 'and', 'a', 'in', 'can', 'if', 'an', 'hand', 'land', 'act', 'ask', 'any', 'part', 'man', 'mean', 'many', 'has', 'stand', 'farm', 'eat', 'main', 'wind', 'boat', 'ran', 'heat', 'east', 'warm', 'fact', 'fast', 'rain', 'art', 'heart', 'am', 'arm', 'sit', 'train', 'sat', 'gas', 'least', 'fit', 'flat', 'cat', 'bit', 'coast', 'sand', 'beat', 'hit', 'party', 'wing', 'wash', 'bat', 'meat', 'suit', 'fat', 'meant', 'coat', 'band', 'win', 'seat', 'hat', 'salt']
Possible outputs:
1. stand (stand -> sand -> and -> an -> a)
2. heart (heart -> heat -> eat -> at -> a)
3. train (train -> rain -> ran -> an -> a)
4. least (least -> east -> eat -> at -> a)
5. coast (coast -> coat -> cat -> at -> a)
6. party (party -> part -> art -> at -> a)
7. meant (meant -> meat -> eat -> at -> a)

```

# Answer
# Jelly, 14 bytes

```
ḊÐḟ¹-Ƥf¥Ƈ@Ƭ⁸ẎṪ

```

A monadic Link that accepts a list of lists of characters and returns a list of characters or zero (falsey) if no solution is possible.

**Try it online!**

### How?

```
ḊÐḟ¹-Ƥf¥Ƈ@Ƭ⁸ẎṪ - Link: list of lists of characters (words), W
 Ðḟ            - filter out those for which:
Ḋ              -   dequeue (i.e. remove words of length > 1)
                 (let's call this list of single-character words S)
           ⁸   - with W as the right argument...
          Ƭ    - collect up input, I (initially S), while distinct applying:
         @     -   with swapped arguments - f(W, I):
        Ƈ      -     filter keep those (w in W) for which:
       ¥       -       last two links as a dyad - f(w, I):
     Ƥ         -         for overlapping outfixes (of w)...
    -          -         ...of size: -1 (i.e. outfixes of length one less)
   ¹           -         ...do: nothing
                         (i.e. get all potential sub-words of w)
      f        -         filter keep -> sub-words which are in I
                         (an empty list is falsey)
                   -> words in W which can be shorted to any of those in I
                 -> reachable word lists ordered by word-length plus an empty list
            Ẏ  - tighten -> list of all words reached
             Ṫ - tail -> (one of) the longest one(s) or 0 if empty

```

...that's some pretty serious Jelly right there I reckon.
> 6 votes

# Answer
# Python 3, ~~96~~ 95 bytes

Thanks to movatica for a byte saved!

```
f=lambda d,w='':max([f(d,c)for c in d if{w}&{c[:i]+c[i+1:]for i in range(len(c))}]+[w],key=len)

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 91 bytes

```
f=(a,p=o='',n)=>p[n]||a.map(w=>w!=p&p.match([...w,,].join`?`)==p&&f(a,w,-~n),o[n]?0:o=p)&&o

```

Try it online!

### How?

We start from the empty string and try to build the longest possible word from there. This is more efficient than taking each word and trying to reach the empty string because we'd need to keep track of the original word, or at least its length.

When looking for a word \\$w\\$ of \\$n+1\\$ characters which is a valid successor of a previous word \\$p\\$ of \\$n\\$ characters, it would be easier to do something like:

```
[...w].some((_,i)=>p==w.slice(0,i)+w.slice(i+1))

```

But this is quite verbose.

Instead, we look for a word \\$w\\$ which contains all the letters of \\$p\\$ in order but is not equal to \\$p\\$:

```
w!=p&p.match([...w,,].join`?`)==p

```

The problem is that \\$w\\$ may contain more than just one additional letter. For instance, we can go directly from `man` to `meant`. So we have to check its length afterwards, but we keep track of the current expected length in \\$n\\$ anyway to avoid the use of `.length` and this is still overall shorter.

### Commented

```
f = (                // f is a recursive function taking:
  a,                 //   a[] = input dictionary
  p =                //   p = previous word in the chain, initially empty
  o = '',            //   o = output
  n                  //   n = expected length of the previous word
) =>                 //
p[n] ||              // abort if p is too long
a.map(w =>           // otherwise, for each word w in a[]:
  w != p &           //   force the test to fail if w is equal to p
  p.match(           //   build a pattern consisting of:
    [...w,,].join`?` //     each letter of w followed by a '?'
  )                  //   if this regular expression applied to p
  == p               //   is matching p (which means that p can be obtained
  &&                 //   by taking some letters of w in order):
    f(a, w, -~n),    //     do a recursive call with p = w and n + 1
                     //   before the loop starts:
  o[n] ? 0           //     do nothing if the length of o is greater than n
       : o = p       //     otherwise, update o to p
)                    // end of map()
&& o                 // return the final output

```
> 4 votes

# Answer
# Retina, 45 bytes

```
N^$`
$.&
+Gml`.|(.*).(.*)(?=(?s).+^\1\2$)
0G`

```

Try it online! Explanation:

```
N^$`
$.&

```

Sort the list of words in descending order of length.

```
+Gml`.|(.*).(.*)(?=(?s).+^\1\2$)

```

Repeatedly delete words of two or more letters that cannot be reduced to another word in the list by the deletion of a letter.

```
0G`

```

Keep only the first (i.e. longest) (if any) word.
> 4 votes

# Answer
# Vyxal, 14 bytes

```
~₃≬£⁰'ẏ⋎¥↔;İft

```

Try it Online!
> 4 votes

# Answer
# Zsh, 98 bytes

```
A=($@)
f()for ((i=0;i++<$#w;))(w[i]=;((!#w||A[(I)$w]))&&f)&&break
for w;(($#w>$#a))&&f&&a=$w
<<<$a

```

Try it online!

```
A=($@)      # save the arguments so we don't have to pass them in the recursive calls

f() # { <- implicit
    for ((i=0;i++<$#w;))
        (   # enter a subshell, so changes to $w here
            # and $i in the recursive call won't affect their values here
            w[i]=
            ((!#w||A[(I)$w])) &&  # if $w is empty or is found in $A,
                f                 # recurse. If f exited truthy,
        ) && break                # then the subshell exits truthy, and we break
# } <- implicit

for w                             # for each word
   (($#w > $#a)) && f &&          # if it is the longest word found so far,
      a=$w                        # set it as our answer

<<<$a                             # output our answer

```
> 2 votes

# Answer
# Python3, 130 bytes:

```
lambda d:max([i for i in d if f(i,d)],key=len)
f=lambda x,d:len(x)==1 or any(f(T,d)for i in range(len(x))if(T:=x[:i]+x[i+1:])in d)

```

Try it online!
> 1 votes

# Answer
# , 43 bytes

```
0{](#~1*@#.(1=#&>)+]e."1(1<\.])&>)^:_@\:#&>

```

Try it online!

*-4 bytes thanks to Neil's clever idea*

My original approach was to construct an adjacency matrix and self multiply it to a fixed a point, and then use the final column as a mask on the sorted input.

But it turned that Neil's idea was slightly shorter.

In both approaches, we get to use `1<\.]` J's outfix adverb to produce all the possible strings with 1 character deleted.
> 1 votes

# Answer
# Charcoal, 26 bytes

```
⊞υωＦθ≔⁺υΦθ‹№υκ⊙κ№υΦκ⁻μξυ⊟υ

```

Try it online! Link is to verbose version of code. Explanation:

```
⊞υω

```

Start with a list of just the empty string.

```
Ｆθ

```

Loop enough times.

```
≔⁺υΦθ‹№υκ⊙κ№υΦκ⁻μξυ

```

Append all words that don't yet exist in the list but which do when one of their letters is removed to the list.

```
⊟υ

```

Output the last word from the list.

If the input was in ascending order of length then it would be only 20 bytes:

```
⊞υωＦθＦ⊙ι№υΦι⁻λν⊞υι⊟υ

```

Try it online! Link is to verbose version of code.
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
éæéʒ€gāQ}ʒü.LP}θ

```

Pretty slow for big input-lists.

Outputs the sequence of the longest word instead of just the longest word (e.g. `["a","ad","aid"]` instead of `aid`).

Try it online or verify the first two test cases.

**Explanation:**

```
é         # Sort the (implicit) input-list on length (smallest to largest)
 æ        # Pop and push the powerset of this list
  é       # Sort that by length as well
   ʒ      # Filter this list of lists by:
    €g    #  Get the length of each word in the list
      ā   #  Push a list in the range [1,list-length] (without popping the list itself)
       Q  #  Check if both lists are the same
   }ʒ     # After the first filter: filter again:
     ü    #  For each overlapping pair of words:
      .L  #   Calculate the Levenshtein distance
        P #  Product: check if all Levenshtein distances are 1
    }θ    # After the filter: pop and leave the last/longest list
          # (which is output implicitly as result)

```
> 1 votes

# Answer
# Haskell, 118 bytes

```
d#w=any(\y->y==[]||y`elem`d&&d#y)[take i w++drop(i+1)w|(i,c)<-zip[0..]w]
f d=snd$maximum$[(length x,x)|x<-filter(d#)d]
```

Attempt This Online!
> 1 votes

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


# Question
Title: Draw this fractal generated by applying Newton's method to cosh(x) - 1
I came across this picture the other day: (Credit to Josep M Batlle I Ferrer)

Your job is to generate this picture. This graph is generated by repeatedly applying newton's method to the graph of:

$$f(x)=\cosh(x)-1$$

In other words, repeatedly apply the following function to every point till the rectangular distance is less than some limit to a attractor:

$$g(x)=\frac{x \cdot \sinh(x) - \cosh(x) + 1}{\sinh(x)}$$

The process is described in psuedocode below:

```
let n be the maximum number of iterations
for every point (as a complex number) in the image:
    repeat n times:
        point = (point * sinh(point) - cosh(point) + 1) / sinh(point)

        if the rectangular distance between the point and any attractor is less than 0.01:
             break
        end if
    end repeat
    color the point in the image depending on the nearest attractor and the number of iterations required

```

The rectangular distance is defined as `max(abs(dx), abs(dy))`. We use rectangular distance instead of straight line distance so we get the wave shapes that make this graph so beautiful.

There is a attractor at `0+n*2i*PI` for any integer N. Thus at even increments of 2 PI in the imaginary direction.

# Rules

* Your graph must include the area from `[-0.75, -0.75 + PI]` to `[0.75, +0.75 + PI]`.
* Resolution over this needs to be at least 256 by 256. Either characters or pixels. If you decide to cover a larger area you need to increase the resolution in proportion.
* Use at least 20 iterations.
* Both adjacent iteration counts and adjacent attractors need to be drawn in distinct colors. You must use at least 3 different colors. Coloring should soley be based on the attractor and iteration count.
* If any point causes a division by 0 or another math error, you may choose to render anything at this point. This is considered undefined behavior.
* Displaying a image, saving a image, or drawing ASCII art are all acceptable, as long as the other rules are met. If you draw ASCII art characters need to be ANSI colored.
* Please include a screenshot of the result in your answer

This is code golf, shortest answer wins. ASCII art answers *do not* compete against graphical answers in the same language.

# Background info

# Answer
# Desmos, ~~401~~ ~~375~~ ~~357~~ 353 bytes

-26 bytes thanks to @aiden-chow

-18 bytes thanks to flexabrotnt#1409

```
H(u,v)=(u.xv.x-v.yu.y,u.xv.y+v.xu.y)
F(u,v)=(u.xv.x+u.yv.y,u.yv.x-u.xv.y)/(v.x²+v.y²)
E(z)=e^{z.x}(cos(z.y),sin(z.y))
C(z,k)=H((1/2,0),E(z)+kE(H((-1,0),z)))
N(z)=F(H(z,C(z,-1))-C(z,1)+(1,0),C(z,-1))
G(z)=max(z.x²,z.y²)
Y(z)=N(N(N(N(N(z)))))
Z(z)=Y(Y(Y(Y(z))))
l=[0...2]
O=hsv(l110,1,1)
P=Z((x,y))
X=round(P.y/(2π))
G((0,2Xπ)-P)<0.01\{\mod(X,3)=l\}

```

Try It On Desmos!

Before golfing
> 12 votes

# Answer
# Python + Pygame, ~~410~~ 392 bytes (Example Submission)

*-16 bytes thanks to wizzwizz4 and others*

```
from pygame import*
from cmath import*
w=256;s=Surface((w,w));f=lambda p:p-(cosh(p)-1)/sinh(p);g=lambda t:round(t.imag/pi/2)*pi*2j;h=lambda p:max(abs(p.real),abs(p.imag))>0.01
for x in range(w):
 for y in range(w):
  t=x/w-0.5+(y/w-0.5-pi)*1j
  for i in range(99):
   try:t=f(t);1/h(g(t)-t)
   except:break
  s.set_at((x,y),[0,[w-1,5,5],[9,w-1,9]][(round(t.imag/pi/2)+i)%3])
image.save(s,"f")

```

Result will be saved as a TGA file named `"f"`:
> 7 votes

# Answer
# Rust + Num ASCII Art - ~~420~~ 413 bytes

*-6 bytes thanks to @LF*

```
use{num::complex::*,std::f32::consts::*};(0..255).any(|y|(0..512).any(|x|if let Some(n)=(0..99).scan(Complex::new(x as f32/256.0-1.,y as f32/256.0-0.5+PI),|s,l|{*s=*s-(s.cosh()-1.)/s.sinh();Some((*s,l))}).filter(|s|s.0.re.abs().max(s.0.im-((s.0.im/(2.*PI)).round()*2.*PI).abs())<0.01).next(){print!("\x1b[{:0<2};{:0<2}m0",30+n.1%8,40+((n.0.im/PI/2. + 36.).round()%8.)as usize)}else{print!("0")}>())||print!("
")>());

```
> 7 votes

# Answer
## JavaScript (ES6), ~~271~~ ~~260~~ ~~253~~ 251 bytes

```
c=>{z=c.getContext`2d`;for(i=384;i--;)for(j=384;i--;)with(Math){x=i/256-.75;y=j/256-.75+PI;for(k=10;k<30>(x*x<1e-4&abs(y-2*PI*(v=round(y/2/PI)))<.01);k++)w=cosh(x)+cos(y),x-=sinh(x)/w,y-=sin(y)/w;z.fillStyle=`#0${(k+v%10)*3%10}9`;z.fillRect(i,j,1,1)}}

```

Takes as parameter a 384×384 canvas on which to draw the result. Demo, with whitespace for readability and animation:

```
f = async c => {
  z = c.getContext`2d`;
  for (i = 384; i--; ) {
    for (j = 384; j--; ) with (Math) {
      x = i / 256 - .75;
      y = j / 256 - .75 + PI;
      for (k = 10; k < 30 > (x * x < 1e-4 & abs(y - 2 * PI * (v = round(y / 2 / PI))) < .01); k++)
        w = cosh(x) + cos(y),
        x -= sinh(x) / w,
        y -= sin(y) / w;
      z.fillStyle = `#0${(k+v%10)*3%10}9`;
      z.fillRect(i, j, 1, 1);
    }
    await new Promise(resolve => requestAnimationFrame(resolve));
  }
};
f(c);
```

```
<canvas width=384 height=384 id=c>
```

Edit: Saved 11 bytes thanks to @Ausername. Saved 7 bytes thanks to @Steffan. Saved 2 bytes thanks to @Dingus.
> 5 votes

# Answer
# Pyxplot 0.8.4, <sup>~~190~~ ~~188~~</sup> 186 bytes

```
se nu c
su g(x,y){z=x+y*i
fo n=1to20{z=z-coth(z)+csch(z)
if(Re(z)**2<1e-4)*cos(Im(z))>cos(.01){ret ceil(Im(z)/pi-.5);}
}
}
se sa gr 1e3x1e3
se colm hsb c2:c1:1
p[-1:1][2:4]g(x,y):n w col

```

Conveniently for code golf, most commands in Pyxplot may be abbreviated zealously. By default (empty `.pyxplotrc` config file), output is written to `pyxplot.eps`.

If the text and axis labels produced by default must be removed, replace the last line with

```
se ax xy in
p[-1:1][2:4]g(x,y):n t''w col

```

at a cost of 15 bytes. Add `se s s` for a square aspect ratio.

Some mathematical simplifications are used. Firstly, we write \\$g\\$ as \\$g(z) = z-\coth(z)+\mathop{\rm csch}(z)\\$. Secondly, we note that \\$\max(\lvert\Delta x\rvert, \lvert\Delta y \rvert) \< t\\$ implies that both \\$\lvert\Delta x\rvert \< t\\$ and \\$\lvert\Delta y\rvert \< t\\$ and treat these two constraints separately:

* \\$\lvert\Delta x\rvert = \lvert x-0\rvert = \lvert x\rvert\\$, so the first constraint becomes \\$x^2\<t^2\\$, which is shorter in Pyxplot than \\$\lvert x\rvert \< t\\$ (which would be `abs(Re(z))<.01`).
* \\$\lvert\Delta y\rvert = \lvert y-2k\pi\rvert\\$ for some integer \\$k\\$. Observe that the attractors lie at points where the cosine function is maximal, i.e. \\$\cos(2k\pi)=1\\$. Thus the constraint on \\$y\\$ may be written as \\$\cos(\lvert y-2k\pi\rvert) \> \cos(t)\\$, which simplifies to \\$\cos(y) \> \cos(t)\\$ by the symmetry and periodicity of the cosine function.

For the plot, an HSB colourmap is used. At each point the hue is determined by the number of iterations (`n` in the code), automatically rescaled to span the range from 0 and 1 (i.e. the full range of hues). The saturation is determined by the value of \\$2k\\$ (the return value of `g(x,y)`) for the point's attractor, again rescaled to span the full range of saturations. The brightness is fixed at maximum.

An iteration limit of 20 is imposed. Red and orange hues become more predominant at the expense of green and blue as this limit is increased.

In theory, it is possible to omit `[-1:1][2:4]` in the last line of the code (saving 10 bytes), have Pyxplot apply its default axis ranges (\\$-10\le x,y\le 10\\$), and increase the grid resolution (`1e3x1e3`) to compensate. In practice, setting the resolution to `4e3x4e3` exhausted the available memory (16 GB RAM plus 20 GB swap) on my machine.

### Ungolfed code

```
set numerics complex
subroutine g(x, y) {
  z = x + y * i
  for n = 1 to 20 {
    z = z - coth(z) + csch(z)
    if Re(z)**2 < 1e-4 and cos(Im(z)) > cos(1e-2) {
      return ceil(Im(z) / pi - 0.5)
    }
  }
}
set samples grid 1e3 x 1e3
set colourmap hsb c2:c1:1
plot [-1:1] [2:4] g(x, y):n with colourmap

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 128 bytes

```
Image@Table[n=0;x+y*I//.z_/;Max@Abs@{Re@z,Mod[i=Im@z,Pi,n+=8t;-1]}>2t:>z-Coth@z+Csch@z;i~Hue~n,{y,-1+Pi,1+Pi,t=.005},{x,-1,1,t}]

```
> 2 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, graphical-output, fractal
---


title: Reconstruct an arithmetic sequence

text:
# Question
Title: Reconstruct an arithmetic sequence
Given a finite arithmetic sequence of positive integers with some terms removed from the middle, reconstruct the whole sequence.

## The task

Consider an arithmetic sequence: a list of positive integers in which the difference between any two successive elements is the same.

```
2 5 8 11 14 17

```

Now suppose one or more integers is removed from the sequence, subject to the following constraints:

* The integers removed will be consecutive terms of the sequence.
* The first and last integers in the sequence will not be removed.
* At least three integers will remain in the sequence.

For the above sequence, possible removals include:

```
2 5 8 14 17  (removed 11)
2 5 17       (removed 8 11 14)
2 14 17      (removed 5 8 11)

```

Your task: Given one of these partial sequences, reconstruct the original full sequence.

## Details

You may assume input is valid (has a solution) and is missing at least one term. All numbers in the sequence will be positive (\> 0) integers. The sequence may have a positive or negative difference between terms (i.e. it may be increasing or decreasing). It will not be a constant sequence (e.g. `5 5 5`).

Your solution may be a full program or a function. Any of the default input and output methods are acceptable.

Your input and output may be a string (with any reasonable delimiter), a list of strings, or a list of numbers. You may represent the numbers in whatever base is convenient for your language.

Please mention any unusual I/O methods/formats in your submission, so others will be able to test your code more easily.

## Test cases

```
In: 2 5 8 14 17
Out: 2 5 8 11 14 17
In: 2 5 17
Out: 2 5 8 11 14 17
In: 2 14 17
Out: 2 5 8 11 14 17
In: 21 9 6 3
Out: 21 18 15 12 9 6 3
In: 10 9 5
Out: 10 9 8 7 6 5
In: 1 10 91 100
Out: 1 10 19 28 37 46 55 64 73 82 91 100

```

---

This is ; the shortest answer in each language wins.

# Answer
# Haskell, 63 bytes

```
f(a:b:c)|s<-[a,b..last c],all(`elem`s)c=s
f a=r$f$r a
r=reverse

```

Try it online!

Basically works by trying to build the result from the front and, if that fails, from the back. This uses the fact that the first and last members of the input will always be correct, the fact that deleted members have to be consecutive, and the fact that there will always be at least three items in the input. All I have to do is assume that the second or second-to-last members are accurate and check if it works. Luckily Haskell has really beautiful syntax for creating arithmetic series.

EDIT: thanks to @xnor for pointing out a bug and providing a solution!
> 10 votes

# Answer
# 05AB1E, ~~9~~ 8 bytes

```
Ÿs¥¿Äô€н

```

Try it online!

**Explanation**

* Construct the range \[first, ..., last\] with a difference of +/-1
* Calculate deltas of the input
* Get the absolute value of the gcd of the deltas
* Split the full range in chunks of that size
* Get the first element of each chunk

Saved 1 byte using `gcd of deltas` instead of `min delta`, inspired by user202729
> 6 votes

# Answer
# Brachylog v2, 9 bytes

```
⊆.s₂ᵇ-ᵐ=∧

```

Try it online!

This is a function submission. The Brachylog interpreter can be made to evaluate a function as though it were a full program by giving it `Z` as a command line argument; in this case, the input is specified in the format, e.g., `[1, 2, 4]` and the output is returned in a similar format, e.g. `Z = [1, 2, 3, 4]`. (Of course, for a function submission, the input and output aren't in any format at all; they're just lists.)

This actually solves a harder problem than the one the OP asked for: it works out the shortest arithmetic sequence of integers containing the specified values in the specified order, regardless of whether the deletions are consecutive or not. Because it uses brute force, it can be very slow if many values are deleted.

## Explanation

The program has three main parts.

finds a supersequence of the input (i.e. a sequence that has the input as a subsequence). When there's more than one possible output from a Brachylog program, the output chosen is the first output in tiebreak order, and the tiebreak order is determined by the first command in the program that has an opinion on it; in this case,  specifies an order that favours short outputs over long ones. So the output we'll get will be the shortest supersequence of the input that obeys the restrictions in the rest of the program.

`.` is used to output the value it sees as input (i.e. the supersequence in this case), but also assert that a specific condition holds on it. In other words, we're outputting the shortest supersequence that obeys a specific condition (and ignoring any intermediate results used to see if it obeys the condition).

Finally, we have `s₂ᵇ-ᵐ` `=`, i.e. "all the deltas of the sequence are equal", the condition we're applying to the output. (The return value from this is a list of deltas, rather than the supersequence itself, which is why we need the `.` to ensure that the right thing is output.)

Brachylog is held back here by not having any builtins that can handle calculation of deltas, applying an operation to overlapping pairs from a list, or the like. Instead, we have to say what we mean explicitly: `s₂ᵇ` finds all () substrings (`s`) of length 2 () (the use of  is required to keep a link between unknowns in the substrings and in the supersequence; the more commonly used  would break this link). Then `-ᵐ` does a subtraction on each of these pairs to produce a delta. It's annoying to have to write out five bytes `s₂ᵇ-ᵐ` for something that most modern golfing languages have a builtin for, but that's the way that codegolf goes sometimes, I guess.
> 6 votes

# Answer
# Pyth, 11 bytes

```
%hS.+SQ}hQe

```

**Try it here!**

Thanks to Steven H. for saving a byte!

### Pyth, 12 bytes

```
%.aiF.+Q}hQe

```

**Try it here!**

### How it works

```
%.aiF.+Q}hQe ~ Full program.

     .+Q     ~ Get the deltas.
   iF        ~ Reduce by GCD.
 .a          ~ Absolute value.
%            ~ Modular. Get every nth element of...
        }    ~ The inclusive numeric range between...
         hQ  ~ The first element, and...
           e ~ The last element.

```
> 4 votes

# Answer
# Python 2, ~~104~~ ~~97~~ ~~89~~ ~~83~~ ~~71~~ ~~67~~ 60 bytes

*Thanks to Chas Brown for saving 4 bytes.<br>Thanks to ovs for saving 7 bytes.*

Input the list by arguments.

```
lambda a,b,*c:range(a,c[-1],min(b-a,c[0]-b,key=abs))+[c[-1]]

```

Try it online!

**Explanation:**

Since the removed are consecutive, it is enough to check the differences between two pairs of consecutive elements.
> 4 votes

# Answer
# Jelly, 8 bytes

```
ṂrṀmIg/$

```

Try it online!

Notes:

* Only work on some old version of Jelly. (this commit for example) (where `g` use `fractions.gcd`, which have the result sign the same as input sign, instead of `math.gcd`, which always return positive value).
* The TIO link above is Python 3 TIO link, the Python code consists of Jelly source code from the commit I mentioned above, with the exception of everything (3 files) packed into the same file (for TIO to run) and `dictionary.py` has been reduced to only some lines. Nevertheless `dictionary.py` is unrelated to this answer, as it does not use compressed string. (the `“...»` construct)

Explanation:

First, because a continuous segment is deleted and at least 3 elements remains, there are two consecutive numbers in the old list remain, and the deltas will all be multiples of the step. Therefore the `gcd` of the differences (`I`, increments) list will be the absolute value of the step.

Fortunately the `gcd` is signed (see note above)

So the program does:

```
ṂrṀ

```

An increasing integer range from the inimum to the aximum.

```
m

```

Modular, pick every n'th element.

```
Ig/$

```

Monadic (`$`) chain combine `I` (increments, differences) and `g/` (reduce `gcd` over elements of the list). If the increments are positive then the `gcd` will be positive and the returning list will be left-to-right (increasing), and vice-versa.
> 4 votes

# Answer
# JavaScript (ES6), ~~92~~ 90

**Edit** 2 bytes saved thx Arnauld

Easy, as it is enough to check the differences between the first two and the last two. But still unbelievably long.

```
s=>(e=(z=s.pop(a=s[0]))-s.pop(d=s[1]-a),[...Array((z-(a-=d=e*e>d*d?d:e))/d)].map(_=>a+=d))

```

*Less golfed*

```
s=>{
  a =s[0]
  b =s[1]
  z = s.pop()
  y = s.pop()
  d = b-a
  e = z-y
  d = e*e>d*d?d:e
  n = (z-a)/d+1
  return [...Array(n)].map((_,i) => a + i*d)
}

```

**Test**

```
var F=
s=>(e=(z=s.pop(a=s[0]))-s.pop(d=s[1]-a),[...Array((z-(a-=d=e*e>d*d?d:e))/d)].map(_=>a+=d))

var test=`In: 2 5 8 14 17 Out: 2 5 8 11 14 17
In: 2 5 17 Out: 2 5 8 11 14 17
In: 2 14 17 Out: 2 5 8 11 14 17
In: 21 9 6 3 Out: 21 18 15 12 9 6 3
In: 10 9 5 Out: 10 9 8 7 6 5
In: 1 10 91 100 Out: 1 10 19 28 37 46 55 64 73 82 91 100`.split`\n`
.map(r=>r.split`Out`.map(x=>x.match(/\d+/g)))

test.forEach(([i,k])=>{
  var o=F(i.slice(0))
  var ok = o+''==k
  console.log(ok?'OK':'KO',i+' => '+o)
})
```
> 3 votes

# Answer
# MATL, 13 bytes

```
1)0GdYkG0)3$:

```

Try it online!

Explanation:

```
Consider the example input [2 14 17]:
           # implicit input, STACK: [[2 14 17]]
1)         # push 1, index, STACK: [2]
0G         # push 0, duplicate input, STACK: [2, 0, [2 14 17]]
d          # take differences, STACK: [2, 0, [12, 3]]
Yk         # get value in [12, 3] nearest to 0, STACK: [2, 3]
G0)        # get last element in input, STACK: [2, 3, 17]
3$:        # 3-input :, computes 2:3:17, the range from 2 to 17 by 3
           # STACK: [[2 5 8 11 14 17]], implicit output.

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 50 bytes

```
Range[#&@@#,#[[-1]],#&@@Differences@#~SortBy~Abs]&

```

Try it online!
> 2 votes

# Answer
# Ruby, ~~65 62 55~~ 54 bytes

```
->l{a,*,b,c=l;[*a.step(c,[l[1]-a,c-b].min_by(&:abs))]}

```

Try it online!

-1 byte thanks to Justin Mariner
> 2 votes

# Answer
# Japt, ~~12~~ 10 bytes

```
ÌõUÎUäa rm

```

Try it

```
ÌõUÎUäa rm     :Implicit input of array U
Ì              :Last element
  UÎ           :First element
 õ             :Range [first,last] with step size
    Uä         :  Consecutive pairs of U
      a        :    Reduced by absolute difference
        r      :  Reduce by
         m     :    Minimum

```
> 1 votes

# Answer
# Haskell, ~~73~~ 69 bytes

```
f(h:t)=do(#)<-[(-),(+)];[h,h#minimum(abs<$>zipWith(-)t(h:t))..last t]

```

Try it online!
> 1 votes

# Answer
# , 49, 47 46 bytes

```
(0-[:<./2|@-/\]){.@[&]\({.<.{:)+[:i.{:(+*)@-{.

```

Inspired by Emigna's solution.

How it works:

```
 (0-[:<./2|@-/\]){.@[&]\({.<.{:)+[:i.{:(+*)@-{. - fork of 3 verbs

                        ({.<.{:)+[:i.{:(+*)@-{. - generates a list in the entire range of values
                                     {:     -{. - last minus first element
                                       (+*)@    - adds the signum of the difference
                                 [:i.           - makes a list
                       ({.<.{:)                 - the smallest of first and last elements
                               +                - adds the offset to the list (translates all elements according to the first one)

 (0-[:<./2|@-/\])                               - finds the step
         2|@-/\]                                - the absolute differences between all consecutive elements
    [:<./                                       - the smallest one
  0-                                            - negate (for splitting)

                 {.@[&]\                        - splits the list from the right verb into left verb's result sublists and takes their first elements

```

Try it online!
> 1 votes

# Answer
# Husk, 9 bytes

```
m←C▼Ẋ≠⁰…⁰

```

Try it online!

Thanks a lot to H.PWiz for halving the byte count, by pointing that applying  on a list rangifies it!...
> 1 votes

# Answer
# C# (.NET Core), 167+13=180 145+13=158 bytes

```
a=>{int x=a[1]-a[0],y=a[2]-a[1],d=x*x<y*y?x:y,s=Math.Abs((a[a.Length-1]-a[0])/d),i=0,j=a[0];var r=new int[s+1];for(;i<=s;j+=d)r[i++]=j;return r;}

```

Try it online!

+13 for `using System;`

Surprisingly, this challenge had more nuance that I initially anticipated.

### Acknowledgements

-22 bytes saved due to some neat simplifications from @DLosc.

### DeGolfed

```
a=>{
    int x = a[1]-a[0],        // difference between first and second numbers
        y = a[2]-a[1],        // difference between second to last and last numbers
        d = x*x < y*y? x : y, // smallest absolute value difference
        s = Math.Abs((a[a.Length-1] - a[0]) / d), // number of steps in the reconstructed sequence (not the number of elements)
        i = 0,                // step position
        j = a[0];             // next number in reconstructed sequence

    var r = new int[s+1];

    // reconstruct the sequence
    for(; i <= s; j+=d)
        r[i++]=j;

    return r;
}

```
> 1 votes

# Answer
# , 62 bytes

```
function(x)seq(x[1],tail(x,1),min(abs(d<-diff(x)))*sign(d[1]))

```

Try it online!
> 1 votes

# Answer
# Python 2, 147 bytes

```
from fractions import*
a=input()
b=[j-i for i,j in zip(a[:-1],a[1:])]
l=min(gcd(i,j)for i in b for j in b)
print list(range(a[0],a[-1]+l/abs(l),l))

```

Try it online!
> 0 votes

# Answer
# Python 2, 78 bytes

```
lambda a:range(a[0],a[-1],[min,max][a[0]>a[1]](a[1]-a[0],a[-1]-a[-2]))+[a[-1]]

```

Try it online!
> 0 votes

# Answer
# Jelly, 8 bytes

```
ṂrṀmILÞṪ

```

Try it online!
> 0 votes

# Answer
# dc, 64 bytes

```
?dsx[ksE0_1]sg[scdlcr-d2^vdK>gK0=g+sqz1<l]dslx[pdlE+dlx!=Z]dsZxp

```

Try it online!
> 0 votes

# Answer
# Vyxal, 7 bytes

```
ḣtṡ?¯ġḞ

```

Try it Online!
> 0 votes

---
Tags: code-golf, sequence, integer, subsequence
---