title: Calculating waves

text:
# Question
Title: Calculating waves
I've been scrolling around this site for a while, but just recently got really interested in actually trying out some of the challenges. I was intending to try my hand at some of the existing code-golf topics, but I didn't have Internet access for a while yesterday, and in the meantime, I thought up my own challenge.

Your task is to create a program or function that takes an array of Floats `a` and an integer `n`, then sets each value in `a` to the average of the two beside it, `n` times. When repeatedly used with increasing values of `n`, this generates a wave-like motion:

**Specifics:**

* If there happens to be only one item in `a`, or if `n` is 0 or less, the program should return the original array.
* Inputs and outputs can be in any format you desire, as long as they are visibly separated.

**For each step:**

* The first item in `a` should become the average of itself and the next item.
* The last item in `a` should become the average of itself and the previous item.
* Any other item in `a` should become the average of the previous item and the next item.
* Make sure you are calculating off the previous step's array and not the current one!

Test cases: **NOTE: Your inputs/outputs do not have to be in this format!**

```
[0, 0, 1, 0, 0], 1          -> [0, 0.5, 0, 0.5, 0]
[0, 0, 1, 0, 0], 2          -> [0.25, 0, 0.5, 0, 0.25]
[0, 0, 1, 0, 0], 0          -> [0, 0, 1, 0, 0]
[0, 0, 1, 0, 0], -39        -> [0, 0, 1, 0, 0]
[0, 16, 32, 16, 0], 1       -> [8, 16, 16, 16, 8]
[0, 1, 2, 3, 4, 5], 1       -> [0.5, 1, 2, 3, 4, 4.5]
[0, 64], 1                  -> [32, 32]
[0], 482                    -> [0]
[32, 32, 32, 16, 64, 16, 32, 32, 32], 4 -> [33, 27, 40, 22, 44, 22, 40, 27, 33]

```

This is , so shortest answer in bytes wins. The winner will be chosen in one week (on August 1). Good luck!

**Edit:** Congrats to the winner, @issacg, with a whopping **18 bytes!**

# Answer
> 11 votes
# Pyth, ~~46~~ 18 bytes

```
ucR2sV+hGGt+GeG.*Q

```

This code expects input in the form `iterations, [wave1, wave2, wave3 ...]`, as seen at the first link below.

Demonstration. Test Harness.

The program works by applying the code within the reduce (`u`) function to the input list, as many times as the number of iterations.

I will demonstrate the wave propagation function on the list `[0, 1, 2, 3, 4, 5]`, which is in `G`:

`+hGG` prepends `G`'s first element to `G`, forming `[0, 0, 1, 2, 3, 4, 5]`.

`t+GeG` appends `G`'s last element to `G` and removes its first element, forming `[1, 2, 3, 4, 5, 5]`.

`sV` first forms pairs from the lists, giving `[[0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 5]]` with the final element of the first list truncated away. Then, the pairs are summed via the `s` function, giving `[1, 2, 4, 6, 8, 9]`.

`cR2` uses floating point division to divide all of the numbers by 2, giving the desired result, `[0.5, 1.0, 2.0, 3.0, 4.0, 4.5]`.

# Answer
> 8 votes
# Snowman 1.0.0, 219 chars

```
{vg" "aS:10sB;aM0aa,AAg**-:|al|'NdE'0nRal@(%}{->:1*?{0AaG;:?{;bI:dUNiNwR'NdEwRaC;aM(~:?{(()1wR]0wRaC*))#'wRaC|*#|(()#aLNdEdUNdEwR]wR]aCwR*))#aC;:0wRdUaCwR*?{#aC;#bI:*#0aA'|aa|'!*+'(()#1aA*))#|,aa|'*`nA2nD;aM|*0*;bR|tSsP

```

With linebreaks for "readability":

```
{vg" "aS:10sB;aM0aa,AAg**-:|al|'NdE'0nRal@(%}{->:1*?{0AaG;:?{;bI:dUNiNwR'NdEwRaC;
aM(~:?{(()1wR]0wRaC*))#'wRaC|*#|(()#aLNdEdUNdEwR]wR]aCwR*))#aC;:0wRdUaCwR*?{#aC;#
bI:*#0aA'|aa|'!*+'(()#1aA*))#|,aa|'*`nA2nD;aM|*0*;bR|tSsP

```

Ungolfed / unminified version:

```
{vg" "aS:10sB;aM  // input space-separated list of numbers
0aa,AAg           // get first element and array of all-but-first elements
**                // discard original input and the 0

// execute the following (input[0]) times
-:
    |al|'NdE'0nR               // get range from (0..input.length-1]
    al@(%}{->:1*?{0AaG;:?{;bI  // chop off first element if any
    :dUNiNwR'NdEwRaC;aM        // map n -> [n-1 n+1]
    // if the input consisted of a single element, append [0 0]
    // otherwise prepend [0 1] and append [len-2 len-1]
    (~:?{(()1wR]0wRaC*))#'wRaC|*#|(()#aLNdEdUNdEwR]wR]aCwR*))#aC;
        :0wRdUaCwR*?{#aC;#bI
    // map indeces to avg(input[i1], input[i2])
    :*#0aA'|aa|'!*+'(()#1aA*))#|,aa|'*`nA2nD;aM
    // replace old input, reset permavar
    |*0*
;bR

|tSsP  // output result

```

Sample I/O format:

```
llama@llama:...Code/snowman/ppcg53799waves$ snowman waves.snowman
4 32 32 32 16 64 16 32 32 32
[33 27 40 22 44 22 40 27 33]

```

# Answer
> 5 votes
# Pyth - 25 24 bytes

Uses enumerate, reduce to do iterations.

```
u.ecs@L++hGGeG,khhk2GvzQ

```

Try it online here.

# Answer
> 5 votes
# Racket, ~~164~~ 145 bytes

```
(define(f a n)(if(< n 1)a(f(let([l(length a)][r list-ref])(for/list([i(in-range l)])(/(+(r a(max(- i 1)0))(r a(min(+ i 1)(- l 1))))2)))(- n 1))))

```

### Ungolfed

```
(define (f a n)
  (if (< n 1)
      a
      (f (let ([l (length a)] [r list-ref])
           (for/list ([i (in-range l)])
             (/ (+ (r a (max (- i 1) 0))
                   (r a (min (+ i 1) (- l 1))))
                2))) (- n 1))))

```

Note, you may need the `#lang racket` line to run this.

# Answer
> 4 votes
# R, 109 bytes

```
function(x,n){l=length(x);t=if(l>2)c(.5,0,.5)else if(l==2)c(.5,.5)else 1;for(i in 1:n)x=filter(x,t,c=T);c(x)}

```

This creates an unnamed function that accepts a vector and an integer and returns a vector. The approach here is to treat the input as a univariate time series and apply a linear convolution filter.

Ungolfed + explanation:

```
f <- function(x, n) {
    # Define filter coefficients
    t <- if (length(x) > 2)
        c(0.5, 0, 0.5)
    else if (length(x) == 2)
        c(0.5, 0.5)
    else
        1

    # Apply the filter n times
    for (i in 1:n) {
        # The circular option wraps the filter around the edges
        # of the series, otherwise the ends would be set to NA.
        x <- filter(x, t, circular = TRUE)
    }

    # Returned the modified input, stripped of the extraneous
    # properties that the filter function adds.
    c(x)
}

```

Examples:

```
> f(c(32, 32, 32, 16, 64, 16, 32, 32, 32), 4)
[1] 33 27 40 22 44 22 40 27 33

> f(0, 482)
[1] 0

> f(c(0, 64), 1)
[1] 32 32

```

# Answer
> 4 votes
# Haskell, 76 characters

The trick is to add the first number to the beginning of the list and the last one to the end of the list instead of dealing with the boundary conditions.

```
f a@(x:s)=(/2)<$>zipWith(+)(x:a)(s++[last s])
f x=x
a#n|n<1=a|n>0=f a#(n-1)

```

Tests:

```
λ: [0, 0, 1, 0, 0]#1
[0.0,0.5,0.0,0.5,0.0]
λ: [0, 0, 1, 0, 0]#2
[0.25,0.0,0.5,0.0,0.25]
λ: [0, 0, 1, 0, 0]#0
[0.0,0.0,1.0,0.0,0.0]
λ: [0, 0, 1, 0, 0]#(-39)
[0.0,0.0,1.0,0.0,0.0]
λ: [0, 16, 32, 16, 0]#1
[8.0,16.0,16.0,16.0,8.0]
λ: [0, 1, 2, 3, 4, 5]#1
[0.5,1.0,2.0,3.0,4.0,4.5]
λ: [0, 64]#1
[32.0,32.0]
λ: [0]#482
[0.0]
λ: [32, 32, 32, 16, 64, 16, 32, 32, 32]#4
[33.0,27.0,40.0,22.0,44.0,22.0,40.0,27.0,33.0]

```

# Answer
> 2 votes
# JavaScript (ES6), ~~153~~ ~~132~~ 67 chars

I come back to my first answer 6 months later and what do I do? Golf off 50%, that's what. ;)

```
s=(a,n)=>n<1?a:s(a.map((j,i)=>(a[i&&i-1]+a[a[i+1]+1?i+1:i])/2),n-1)

```

This version calls itself repeatedly until `n` is less than 1, decrementing `n` by 1 each time.

A non-recursive solution (~~151~~ ~~130~~ 78 chars):

```
(a,n)=>n<1?a:eval("while(n--)a=a.map((j,i)=>(a[i&&i-1]+a[a[i+1]+1?i+1:i])/2)")

```

## Ungolfed: (outdated)

### Recursive:

```
s = function (a, n) {
  if (n < 1)
    return a;
  b = [];
  l = a.length;
  x = y = 0;
  for(var i = 0; i < l; i++) {
    x = a[(i < 1) ? 0 : i-1];
    y = a[(i > l-2) ? i : i+1];
    b[i] = (x + y)/2;
  }
  if (n > 2)
    return b;
  return s(b,n-1);
}

```

### Non-recursive:

```
s = function (a, n) {
  if (n < 1)
    return a;
  b = [];
  l = a.length;
  x = y = 0;
  while(n-- > 0) {
    for(var i = 0; i < l; i++) {
      x = a[(i < 1) ? 0 : i-1];
      y = a[(i > l-2) ? i : i+1];
      b[i] = (x + y)/2;
      a = b.slice(0);   // setting a to a copy of b, for copyright reasons
    }
  return b;
}

```

# Answer
> 2 votes
# CJam, ~~23~~ 22 bytes

```
q~{_(@)@@+@@+.+.5f*}*`

```

Try it online

The input is in CJam list format, e.g. for the last example:

```
[32 32 32 16 64 16 32 32 32] 4

```

The output is also a CJam list:

```
[33.0 27.0 40.0 22.0 44.0 22.0 40.0 27.0 33.0]

```

The basic approach is that in each step, the vector is shifted one position to the left and one position to the right. Each of the two vectors is padded with the first/last element, and then the average of the two vectors is calculated.

Explanation:

```
q~    Get and interpret input.
{     Loop over repeat count.
  _     Copy list.
  (     Pop off left element.
  @     Get original list to top.
  )     Pop off right element.
  @@    Get first element and list with last element removed to top.
  +     Concatenate. This gives right-shifted list with first element repeated.
  @@    Get list with first element removed and last element to top.
  +     Concatenate. This gives left-shifted list with last element repeated.
  .+    Perform vector addition of two shifted lists.
  .5f*  Multiply sum by 0.5 to give average.
}*    End loop over repeat count.
`     Convert result array to string.

```

# Answer
> 2 votes
**Java, 181 bytes**

Here's the golfed version:

```
float[]g(float[]i,int n){float[]c=i.clone();int l=c.length,s=1;if(n>0&&l>1){c[0]=(i[0]+i[1])/2f;c[--l]=(i[l]+i[l-1])/2f;while(s<l)c[s]=(i[s-1]+i[++s])/2f;return g(c,n-1);}return i;}

```

Ungolfed:

```
float[] g(float[] i, int n) {
    float[] c = i.clone();
    int l = c.length,s=1;
    if(n>0&&l>1) {
        c[0] = (i[0]+i[1])/2f;
        c[--l] = (i[l]+i[l-1])/2f;
        while(s<l)
            c[s] = (i[s-1] + i[++s]) / 2f;
        return g(c, n-1);
    }
    return i;
}

```

I tried to shorten assignments and conditionals as much as possible with Java. Improvements are welcome, of course.

# Answer
> 1 votes
# Java, 203 bytes

Trying my first put with Java. Improvement tips are welcome:)

```
double[]f(double[]a,int n){int j,s,i=0;s=a.length-1;if(n<1||s<1)return a;double b[]=a;for(;i++<n;a=b.clone()){b[0]=.5*(a[0]+a[1]);b[s]=.5*(a[s]+a[s-1]);for(j=1;j<s;++j)b[j]=.5*(a[j-1]+a[j+1]);}return b;}

```

Pretty printed:

```
double[] g(double[] a, int n) {
  int j, s, i = 0;
  s = a.length - 1;
  if (n < 1 || s < 1)
     return a;
  double b[] = a;
  for (; i++ < n; a = b.clone()) {
     b[0] = .5 * (a[0] + a[1]);
     b[s] = .5 * (a[s] + a[s - 1]);
     for (j = 1; j < s; ++j)
        b[j] = .5 * (a[j - 1] + a[j + 1]);
  }
  return b;
}

```

# Answer
> 1 votes
# Python 2, 98 Bytes

Took the straightforward approach, used `exec` to get out of using a while loop. I think there's a better way of doing the logic to figure out special case positions, but this works for now. Input should be formatted like `[list], times`.

```
b,c=input()
k=~-len(b)
exec'b=[(b[x-(0<x<k)]+b[x+(x<k)-(x==k)])/2.for x in range(-~k)];'*c
print b

```

Ungolfed:

```
BASE,TIME = input()
TEMP = [0]*len(BASE)                               # Temporary array as to not modify base.
while TIME:
    for x in xrange(len(BASE)):
        if x == 0:
            TEMP[x] = (BASE[x]   + BASE[x+1])/2.0  # First element special case.
        elif x == len(BASE)-1:
            TEMP[x] = (BASE[x]   + BASE[x-1])/2.0  # Last element special case.
        else:
            TEMP[x] = (BASE[x-1] + BASE[x+1])/2.0  # Every other element.
    BASE = TEMP                                    # Set base to temporary array.
    TEMP = [0]*len(BASE)                           # Reset temporary array to 0s.
    TIME = TIME - 1
print BASE

```

# Answer
> 1 votes
# Mathematica, 81 bytes

I have a feeling it could be golfed more if I could figure out a better way to handle the positivity condition.

```
f[l_,_]:=l;f[l_,n_/;n>0]:=Nest[.5{1,0,1}~ListConvolve~ArrayPad[#,1,"Fixed"]&,l,n]

```

Worth noting: Mathematica offers lots of potential built-in solutions in its range of list-processing and filter functions, as well as `CellularAutomaton`. I chose `Nest[... ListConvolve ...]` because it was the easiest way to work out the kinks at the ends of the list, but other angles might prove shorter.

# Answer
> 0 votes
## Matlab , 109

```
function a=f(a,n)
if numel(a)>1&n>0
for k=1:n
a=[a(1)+a(2) conv(a,[1 0 1],'valid') a(end-1)+a(end)]/2;end
end

```

Examples:

```
>> f([0, 0, 1, 0, 0], 1)
ans =
         0    0.5000         0    0.5000         0

>> f([0, 0, 1, 0, 0], 2)
ans =
    0.2500         0    0.5000         0    0.2500

>> f([0, 0, 1, 0, 0], 0)
ans =
     0     0     1     0     0

>> f([0, 0, 1, 0, 0], -39)
ans =
     0     0     1     0     0

>> f([0], 482)
ans =
     0

>> f([], 10)
ans =
     []

```

# Answer
> 0 votes
# Scala, ~~195 characters (186 with lazy output, i.e. `Stream`)~~ 187 characters

```
(t:Seq[Float],n:Int)⇒t.size match{case 0|1⇒t;case 2⇒{val a=t.sum/2;Seq(a,a)};case i⇒(t/:(1 to n)){(s,_)⇒(s.take(2).sum/2)+:s.sliding(3).map(l=>(l(0)+l(2))/2).toList:+(s.drop(i-2).sum/2)}}

```

probably not optimal, mapping `sliding(3)` is very useful in this case.

### tests:

```
scala> (t:Seq[Float],n:Int)⇒t.size match{case 0|1⇒t;case 2⇒{val a=t.sum/2;Seq(a,a)};case i⇒(t/:(1 to n)){(s,_)⇒(s.take(2).sum/2)+:s.sliding(3).map(l=>(l(0)+l(2))/2).toList:+(s.drop(i-2).sum/2)}}
res0: (Seq[Float], Int) => List[Float] = <function2>

scala> res0(Seq(0, 0, 1, 0, 0), 1)
res1: Seq[Float] = List(0.0, 0.5, 0.0, 0.5, 0.0)

scala> res0(Seq(0, 0, 1, 0, 0), 2)
res2: Seq[Float] = List(0.25, 0.0, 0.5, 0.0, 0.25)

scala> res0(Seq(0, 0, 1, 0, 0), 0)
res3: Seq[Float] = List(0.0, 0.0, 1.0, 0.0, 0.0)

scala> res0(Seq(0, 0, 1, 0, 0), -39)
res4: Seq[Float] = List(0.0, 0.0, 1.0, 0.0, 0.0)

scala> res0(Seq(0, 16, 32, 16, 0), 1)
res5: Seq[Float] = List(8.0, 16.0, 16.0, 16.0, 8.0)

scala> res0(Seq(1, 2, 3, 4, 5), 1)
res6: Seq[Float] = List(1.5, 2.0, 3.0, 4.0, 4.5)

scala> res0(Seq(0,64), 1)
res7: Seq[Float] = List(32.0, 32.0)

scala> res0(Seq(0), 482)
res8: Seq[Float] = List(0.0)

scala> res0(Seq(32, 32, 32, 16, 64, 16, 32, 32, 32), 4)
res9: Seq[Float] = List(33.0, 27.0, 40.0, 22.0, 44.0, 22.0, 40.0, 27.0, 33.0)

```

# Answer
> 0 votes
# q (27 characters)

```
{avg x^/:1 -1 xprev\:x}/[;]

```

Examples

```
q)f:{avg x^/:1 -1 xprev\:x}/[;]
q)f[4;32 32 32 16 64 16 32 32 32]
33 27 40 22 44 22 40 27 33f
//1-length input
q)f[10;enlist 1]
,1f
//0-length input
q)f[10;`float$()]
`float$()

```

# Answer
> 0 votes
# R, 93 Bytes

As an unnamed function

```
function(a,n){l=length(a);while((n=n-1)>=0)a<-colMeans(rbind(c(a[-1],a[l]),c(a[1],a[-l])));a}

```

Expanded

```
function(a,n){
    l=length(a);             # get the length of the vector
    while((n=n-1)>=0)        # repeat n times
        a<-colMeans(         # do the column means and assign to a
          rbind(             # create an array
            c(a[-1],a[l]),   # shift the vector left and duplicate last
            c(a[1],a[-l])    # shift the vector right and duplicate first
          )
        );
    a                        # return the vector
}

```

Tests

```
> f=function(a,n){l=length(a);while((n=n-1)>=0)a<-colMeans(rbind(c(a[-1],a[l]),c(a[1],a[-l])));a}
> f(c(0, 0, 1, 0, 0), 1)
[1] 0.0 0.5 0.0 0.5 0.0
> f(c(0, 0, 1, 0, 0), 2)
[1] 0.25 0.00 0.50 0.00 0.25
> f(c(0, 0, 1, 0, 0), 0)
[1] 0 0 1 0 0
> f(c(0, 0, 1, 0, 0), -39)
[1] 0 0 1 0 0
> f(c(0, 16, 32, 16, 0), 1)
[1]  8 16 16 16  8
> f(c(0, 1, 2, 3, 4, 5), 1)
[1] 0.5 1.0 2.0 3.0 4.0 4.5
> f(c(0, 64), 1)
[1] 32 32
> f(c(0), 482)
[1] 0
> f(c(32, 32, 32, 16, 64, 16, 32, 32, 32),4)
[1] 33 27 40 22 44 22 40 27 33
>

```

# Answer
> 0 votes
# Japt, ~~39~~ 37 bytes

I just wanted to see how well my golfing language could hold up to my first challenge.

```
Vm0 o r_£ZgY©Y-1 +ZgY>Zl -2?Y:°Y)/2}U

```

Try it online!

```
Vm0 o r_£ZgY©Y-1 +ZgY>Zl -2?Y:°Y)/2}U
Vm0 o      // Generate the range of integers [0, max(V,0)).
r_     }U  // Reduce it with this function, with a starting value of U:
£          //  Return the argument, with each item X, index Y, and the full array Z mapped by this function:
ZgY©Y-1 +  //   Return (Z[max(Y-1,0)] plus
ZgY>Zl -2? //    Z[Y > Z.length-2?
Y:°Y)      //      Y:--Y],)
/2         //   divided by two.
           // Implicit: output last expression

```

# Answer
> 0 votes
# C++14, 158 bytes

```
#define D(a,b)d[i]=(c[a]+c[b])/2;
auto f(auto c,int n){while(n-->0&&c.size()>1){auto d{c};int i{};D(0,1)while(++i<c.size()-1)D(i-1,i+1)D(i,i-1)c=d;}return c;}

```

Requires input to be a container `value_type==double`, like `vector<double>`.

Ungolfed:

```
#define D(a,b) d[i] = (c[a]+c[b])/2;   //average
auto f(auto c, int n) {
  while(n-- > 0 && c.size() > 1) {     //breaks
    auto d{c};                         //copy container
    int i{};
    D(0,1)                             //left
    while(++i < c.size()-1)            //count up to right
      D(i-1,i+1)                       //interior
    D(i,i-1)                           //right
    c=d;                               //overwrite container
  }
  return c;
}

```

# Answer
> 0 votes
## Racket 223 bytes

```
(let p((l l)(m 0)(g list-ref))(cond[(> n m)(let*((j(length l))(k(for/list((i j))(cond[(= i 0)(/(+(g l 0)(g l 1))2)]
[(= i(- j 1))(/(+(g l(- j 2))(g l(- j 1)))2)][else(/(+(g l(+ i 1))(g l(- i 1)))2)]))))(p k(+ 1 m) g))][l]))

```

Ungolfed:

```
(define(f l n)
  (let loop ((l l)
             (m 0)
             (lr list-ref))
    (cond
      [(> n m)
       (let* ((j (length l))
              (k (for/list ((i j))
                   (cond
                     [(= i 0)       (/ (+ (lr l 0)
                                          (lr l 1))
                                       2)]
                     [(= i (- j 1)) (/ (+ (lr l (- j 2))
                                          (lr l (- j 1)))
                                        2)]
                     [else          (/ (+ (lr l (+ i 1))
                                          (lr l (- i 1)))
                                       2)])
                   )))
         (loop k
               (+ 1 m)
               lr))]
      [else l]
      )))

```

Testing:

```
(f '[32 32 32 16 64 16 32 32 32] 4)

```

Output:

```
'(33 27 40 22 44 22 40 27 33)

```

# Answer
> 0 votes
# Jelly, 14 bytes

```
.ịṚjṡ3 .ịⱮÆmµ¡

```

Try it online!

Full program.

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), ~~160~~ 144 bytes

```
float[]a(float[]b,int c)=>c>0&b.Length>1?a(b.Select((_,w)=>w<1?(b[w]+b[w+1])/2:w>b.Length-2?(b[w]+b[w-1])/2:(b[w-1]+b[w+1])/2).ToArray(),c-1):b;

```

Uses good ol' recursion.

Try it online!

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


# Question
Title: Monday Mini-Golf #2: Truncating long text
**Monday Mini-Golf:** A series of short challenges, posted (hopefully!) every Monday.

Many web applications (especially social media) automatically truncate long passages of text so they fit within the app's formatting. In this challenge, we're going to create an algorithm to automatically trim a passage of text to a certain length.

# Challenge

The goal of the challenge is to write a program or function that takes in two arguments:

* *T*, the text to truncate.
* *L*, the maximum length to return.

And returns *T*, truncated with the following logic:

* If the length of *T* is less than or equal to *L*, no truncation is needed. Return the original string.
* Truncate *T* to length *L*-2. If this contains no spaces or hyphens, return *T* truncated to exactly *L*-3 characters, followed by an ellipsis `...`.
* Otherwise, trim the end of the result up to the last space or hyphen. Add an ellipsis `...` and return the result.

# Details

* *T* and *L* may be taken in either order and any format.
* You may assume that 3 \< *L* \< 231.
* You may not use U+2026 Horizontal Ellipsis ; you must use three periods.
* The input will not start with a space or a hyphen.
* The input will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.)

# Test-cases

### Inputs:

```
"This is some very long text." 25
"This-is-some-long-hyphen-separated-text." 33
"Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers." 55
"abcdefghijklmnopqrstuvwxyz" 20
"a b c" 4
"Very long." 100

```

### Outputs:

```
"This is some very long..."
"This-is-some-long-hyphen..."
"Programming Puzzles & Code Golf is a question and..."
"abcdefghijklmnopq..."
"a..."
"Very long."

```

(Note that the quotes are just to specify that these are strings; they need not be included.)

# Scoring

This is , so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Oct 5. Good luck!~~

**Edit:** Congrats to your winner, @Jakube with Pyth again, with **25 bytes!**

# Answer
> 12 votes
# Pyth, 25 bytes

```
+WnzK<zeo}@zN" -"-Q2K"...

```

Try it online: Demonstration or Test Suite

### Explanation:

```
+WnzK<zeo}@zN" -"-Q2K"...  implicit: z = input string, Q = input number
        o        -Q2       order the indices N in [0, 1, ..., Q-3] by
         }@zN" -"            z[T] in " -"
                           (hyphen-indices get sorted to the back)
       e                   take the last such number
     <z                    reduce z to length ^
    K                      save this string to K
+WnzK               K"...  print (K + "...") if z != K else only K

```

# Answer
> 7 votes
# Perl, ~~69~~ ~~59~~ 52 bytes

51 bytes code + 1 byte command line. Assumes numerical input is allowed to be given with -i parameter.

```
s/.{$^I}\K.*//&&s/(^([^ -]*).|.*\K[ -].*)..$/$2.../

```

Usage:

```
echo "This-is-some-long-hyphen-separated-text." | perl -p -i"33" entry.pl

```

# Answer
> 7 votes
# JavaScript (ES6), ~~123~~ ~~78~~ ~~67~~ 61 bytes

I didn't expect to be able to cut this down so much, but it turns out the splice/replace combo is able to cover every case where truncation is needed.

```
(T,L)=>T[L]?T.slice(0,L-2).replace(/([ -][^ -]*|.)$/,'...'):T

```

First argument is the string, second is the length. Special thanks to edc65 for the length check optimization!

Here's the original code (123 bytes):

```
(T,L)=>(T.length>L?(S=T.slice(0,L)).slice(0,(m=Math.max(S.lastIndexOf` `,S.lastIndexOf`-`))<0?L-3:Math.min(L-3,m))+'...':T)

```

# Answer
> 7 votes
# Python 2, ~~78~~ 73 bytes

```
t,l=input()
u=t[:l-2]
print(t,u[:max(map(u.rfind,' -'))]+'...')[l<len(t)]

```

Input format follows the example input.

# Answer
> 5 votes
# TI-BASIC, 87 bytes

```
Prompt L,Str1
For(X,1,L
{inString(Str1," ",X),inString(Str1,"-",X
max(I,max(Ans*(Ans≤L-3->I
End
Str1
If L<length(Ans
sub(Ans,1,I+(L-3)not(I))+"...
Ans

```

TI-BASIC doesn't have many string manipulation commands, so we need to find the last index manually: if the string doesn't contain the string to search for, `inString(` returns 0. We search for hyphens and spaces starting at every position from 1 to `L`, and record the greatest number less than or equal to `L-3`. If that number `I` is still 0, we use `L-3` as the ending index instead.

Due to the calculator's limitations, the largest addressable index of a string is 9999; therefore, this will fail for larger strings.

I rely on the calculator's behavior of automatically initializing the variable `I` to 0, so delete `I` or clear your calculator's memory before running.

# Answer
> 3 votes
# Python 2, 105 bytes

```
def t(s,l):a=s[:l-2];return s[:max(a.rfind(' '),a.rfind('-'))]+'...'if' 'in a or'-'in a else a[:-1]+'...'

```

Called with

```
>>> print t("This is some very long text.", 25)
This is some very long...

```

# Answer
> 3 votes
# C# .NET, ~~187~~ 169 bytes

Hmm...

```
string f(string T,int L){if(T.Length<=L)return T;T=T.Substring(0,L-2);return T.Substring(0,T.Contains(" ")||T.Contains("-")?T.LastIndexOfAny(new[]{' ','-'}):L-3)+"...";}

```

# Answer
> 1 votes
# Groovy, 95 bytes

```
a={T,L->F=T.size()<=L?T:T[0..L-3]
m=F=~'(.*[- ])'
F==T?F:m?m[0][0].trim()+'...':F[0..-2]+'...'}

```

Pretty straightforward, can probably be golfed further

# Answer
> 1 votes
# CJam, 34 bytes

```
q~1$<_@={-2<_W%{" -"&}#~We|<'.3*}|

```

Try it online: Chrome | Firefox

# Answer
> 1 votes
**T-SQL,145 bytes**

```
create proc a(@t varchar(max),@l int)as if LEN(@t)<=@l return @t;set @t = LEFT(@t,@l-3) select LEFT(@t,LEN(@t)-CHARINDEX('-',REVERSE(@t)))+'...'

```

usage:

`exec a("This is some very long text.", 25)
 exec a("This-is-some-long-hyphen-separated-text.", 33)`

# Answer
> 1 votes
# Groovy, 56 bytes

Copied Kleyguerth's answer first, hence the same variable names...

Trim the string down by 2 chars, then most of the work is done by the regex, replace a dash or a space followed by any number of chars that are not a dash or a space at the end of the string with a "." OR replace any character at the end of the string if all the chars before it are neither a dash or a space with a ".". Harder to put into words than to write the regex...

```
a={T,L->T.size()<=L?T:T[0..L-3].replaceAll("([- ][^ -]*|(?<=[^- ]*).)\$",".")+".."}

```

Edit: Actually, can just remove the part of the string that matches the regex and add "..." at the end:

```
a={T,L->T.size()<=L?T:T[0..L-3]-~/[- ][^ -]*$|.$/+"..."}

```

# Answer
> 1 votes
# rs, 116

```
(\d+)$/(_)^^(\1)
___$/
\t
+\t(.)(.*) (_)(_*)$/\1\t\2 \4
\t(.*?)_+$/\1\t
\t( ?).+/\1
[- ][^- \t]*$/
(?<!\t)$/...
 \t/

```

At least it's shorter than C#...

Live demo and test cases.

# Answer
> 1 votes
# Ceylon ~~386~~ ~~333~~ ~~252~~ ~~230~~ ~~222~~ ~~216~~ ~~171~~ ~~153~~ ~~131~~ 111

```
String t(String s,Integer l)=>s.size<l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains)else l-3)]+"...";

```

Ungolfed Original:

```
String truncate(String text, Integer length) {
    if(text.size < length) {
        return text;
    }
    Boolean spacePredicate(Character char) {
        return char == ' ' || char == '-';
    }
    Integer? spaceIndex = text[0:length-2].lastIndexWhere(spacePredicate);
    if(exists spaceIndex) {
        return text[0:spaceIndex] + "...";
    }
    return text[0:length-3]+"...";
}

```

This is 386 bytes/characters. Some interesting features here:

The `x[y:z]` syntax is syntactic sugar for `x.measure(y, z)`, and returns a subrange of `x` starting at `y` with length `z` – for strings, this is a substring. (There is also `x[y..z]` syntax, which is a span from index y to z, both inclusive, as well as half-open spans `x[...z]` and `x[y...]`.)

`List.lastIndexWhere` takes a predicate (i.e. a function taking a list element and returning a boolean, i.e. here a `Callable<Boolean, [Character]>`), and gives the index of the last list element where the predicate is fulfilled (or null, if it's never fulfilled). As strings are lists, this works for strings too.

The result of this, `spaceIndex` is of type `Integer|Null`, or `Integer?` for short – i.e. it can either be an Integer or `null` (the only value of type `Null`). (The name `spaceIndex` comes from when I didn't realize that `-` was also special – I guess `breakIndex` would be better.)

With `exists spaceIndex` we can check if `spaceIndex` is non-null, and do something different then. (Inside this if-block the compiler knows that it is non-null ... without that it would have complained if I used `spaceIndex` to access the string.)

Instead of the local function `spacePredicate` we can also use an anonymous function

```
(Character char) => char == ' ' || char == '-'

```

This brings us to 333 characters:

```
String truncate(String text, Integer length) {
    if(text.size < length) {
        return text;
    }
    Integer? spaceIndex = text[0:length-2].lastIndexWhere(
        (Character char) => char == ' ' || char == '-');
    if(exists spaceIndex) {
        return text[0:spaceIndex] + "...";
    }
    return text[0:length-3]+"...";
}

```

Next optimization is to use shorter variable and function names, which brings us down by 81 bytes to 252:

```
String t(String s, Integer l) {
    if(s.size < l) {
        return s;
    }
    Integer? i = s[0:l-2].lastIndexWhere(
        (Character e) => e == ' ' || e == '-');
    if(exists i) {
        return s[0:i] + "...";
    }
    return s[0:l-3]+"...";
}

```

The predicate function actually doesn't need its argument type declared, that can be inferred by the compiler. Same for the type of `i` (where we still have to write `value` to mark it as a declaration). Now that declaration is short enough to fit on one line, bringing us down to 230:

```
String t(String s, Integer l) {
    if(s.size < l) {
        return s;
    }
    value i = s[0:l-2].lastIndexWhere((e) => e == ' ' || e == '-');
    if(exists i) {
        return s[0:i] + "...";
    }
    return s[0:l-3]+"...";
}

```

Instead of `e == ' ' || e == '-'` we can also write `e in [' ', '-']` (or `e in {' ', '-'}`, this is an iterable constructor instead of a tuple one). The `in` operator maps to the method Category.contains, which brings us to the idea that we can pass that tuple's `contains` method directly (it is a callable taking any object, so also accepting character), without the `(e) => ...` boilerplate (222 bytes):

```
String t(String s, Integer l) {
    if(s.size < l) {
        return s;
    }
    value i = s[0:l-2].lastIndexWhere([' ', '-'].contains);
    if(exists i) {
        return s[0:i] + "...";
    }
    return s[0:l-3]+"...";
}

```

Actually, another category containing the same two characters is the two-character string `" -"`. (In addition it also contains its substrings, but that doesn't hurt here). 216 bytes.

```
String t(String s, Integer l) {
    if(s.size < l) {
        return s;
    }
    value i = s[0:l-2].lastIndexWhere(" -".contains);
    if(exists i) {
        return s[0:i] + "...";
    }
    return s[0:l-3]+"...";
}

```

I guess we got the most out of this line, let's turn to the others ... the last two return statements have some similarity which we can exploit – they just differ in `i` vs. `l-3`, and are using `i` just when it is not null, otherwise `l-3`. Fortunately this is exactly what the `else` operator is made for!

```
String t(String s, Integer l) {
    if(s.size < l) {
        return s;
    }
    value i = s[0:l-2].lastIndexWhere(" -".contains);
    return s[0:(i else l-3)] + "...";
}

```

(The parentheses seem to be needed here, as `else` has a lower precedence than `[:]`.) This is 171 characters. Now `i` is used just once, so we can inline it, bringing us to 153 characters:

```
String t(String s, Integer l) {
    if(s.size < l) {
        return s;
    }
    return s[0:(s[0:l-2].lastIndexWhere(" -".contains) else l-3)] + "...";
}

```

We can also replace this `if-return-return` combination by a combination of the `then` and `else` operators in one `return`. (`then` returns is second operand when the first one is true, otherwise null, which then allows `else` to return its second operand.\`) 131 bytes (although some of the savings are the white spaces which we'll get rid off anyways):

```
String t(String s, Integer l) {
    return s.size < l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains) else l-3)] + "...";
}

```

A function which contains just one return with an expression can alternatively be written with the "fat arrow" notation, giving 123:

```
String t(String s, Integer l) =>
    s.size < l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains) else l-3)] + "...";

```

Removing the unneeded whitespace gives us the final 111 bytes:

`String t(String s,Integer l)=>s.size<l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains)else l-3)]+"...";`

As an addition, here is a function which prints the examples from the question (using the name `t` which is used after step two):

```
shared void testTruncate() {
    value testInputs = {
        ["This is some very long text.", 25],
        ["This-is-some-long-hyphen-separated-text.", 33],
        ["Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers.", 55],
        ["abcdefghijklmnopqrstuvwxyz", 20],
        ["a b c", 4],
        ["Very long.", 100]
    };
    for(input in testInputs) {
        print(t(*input));
    }
}

```

# Answer
> 1 votes
## C# (157):

Based on the **answer of Salah Alami**, but shorter. The ***string*** class derives from `IEnumerable<char>`, so instead of `T.Contains(" ")||T.Contains("-")`, I use `" -".Any(x=>T.Contains(x))`.

Solution:

```
string f(string T,int L){if(T.Length<=L)return T;T=T.Substring(0,L-2);return T.Substring(0," -".Any(T.Contains)?T.LastIndexOfAny(new[]{' ','-'}):L-3)+"...";}

```

Ungolfed:

```
string f (string T, int L)
{
    if (T.Length <= L)
        return T;

    T = T.Substring(0, L - 2);

    return T.Substring(0, " -".Any(T.Contains) ? T.LastIndexOfAny(new[]{' ', '-'}) : L - 3) + "...";
}

```

**Update:**

Saved 6 bytes thanks to the comment of SLuck49, using `Any(T.Contains)` instead of `Any(x=>T.Contains(x))`.

# Answer
> 1 votes
POSIX shell + GNU sed, 65 bytes

```
sed -re "s/(.{$1}).+/\1/;T;s/(.*)[- ]...*/\1.../;t;s/...$/.../;:"

```

This is a job made for sed! But I needed shell to get the length limit in (perhaps Perl would be better). The sed part expands out to a fairly simple sequence, with conditional jumps when we finish:

```
s/(.{$1}).+/\1/
T
s/(.*)[- ]...*/\1.../
t
s/...$/.../
:

```

# Answer
> 1 votes
# Mathematica 192 bytes

```
t=With[{r=StringTake[#,Min[#2-2,StringLength[#]]],p={"-",Whitespace},e="..."},
  Which[StringLength[#]<=#2,#,StringFreeQ[r,p],StringDrop[r,-1]<>e,
   True,StringTake[r,Max[StringPosition[r,p]]-1]<>e]]&

```

Called as

```
t["This is some very long text.", 25]

```

# Answer
> 1 votes
# \>\<\>, 74 bytes

```
l$-:1)?\~r05.
/?=0:~$<-1
\}:0=  ?\::"- "@=@=+?
>~"..."r\}
/!?     <
>ol?!;

```

This solution requires the string to be truncated and `L` to already be on the stack, in that order.

There's 7 wasted bytes caused by alignment issues, still trying to golf those out.

# Answer
> 1 votes
## GS2, 29 bytes

This program takes standard input. The first line is the string, and the second is the target length number.

```
2a 0e 56 3c 40 a0 74 20 22 22 04 5d 2e 2a 3f 5b
20 2d 5d 7c 2e 07 2e 2e 2e 9d 20 e4 35

```

GS2 code can be a bit hard to read sometimes. :) Here's some commentary.

```
2a         # lines - split input on newlines yielding a two element array
0e         # extract-array - pop array, push both elements
56         # read-num - convert length string to number
3c         # take - truncate the string to specified length
40         # dup - duplicate truncated string on stack
a0         # junk1 - push the last popped value, the un-truncated string
74         # ne - test for inequality
    20     # reverse string
    22 22  # tail tail - remove first two characters

    # regex replace first occurrence of ".*?[ -]|." with "..."
    04 5d 2e 2a 3f 5b 20 2d 5d 7c 2e 07 2e 2e 2e 9d

    20     # reverse string
e4         # block5 - make a block out of last 5 instructions
35         # when - conditionally execute block

```

# Answer
> 1 votes
# Jelly, 29 bytes

```
ḣṖṖe€⁾ -œṗƊṖȯ$Ẏḣ⁹_3¤”.⁺⁺ðL>¥¡

```

Try it online!

Full program.

# Answer
> 1 votes
# Clean, 89 bytes

```
import StdEnv
$n l|size l>n=l%(0,last[n:[i\\i<-[2..n]&c<-:l|c==' '||c=='-']]-3)+++"..."=l

```

Try it online!

As a function `$ :: Int String -> String`

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 117 bytes

```
a=>b=>a.Length>b?a.Substring(0,(" -".Any(x=>a.IndexOf(x,0,b-2)>-1)?a.LastIndexOfAny(new[]{' ','-'},b-2):b-3))+"...":a

```

Based off of @Abba's, which is based off of @Salah Alami's answer. Instead of using `Contains` and an unnecessary `Substring` call, it uses IndexOf to check if a hyphen or space exists in the truncated string.

Try it online!

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


title: Parse the Bookworm dictionary format

text:
# Question
Title: Parse the Bookworm dictionary format
I've recently been indulging myself in some nostalgia in the form of Bookworm Deluxe:

In case you haven't seen it before, it's a word game where the goal is to connect adjacent tiles to form words. In order to determine whether a string is a valid word, it checks it against its internal dictionary, which is stored in a compressed format that looks like this:

```
aa
2h
3ed
ing
s
2l
3iis
s
2rdvark
8s
4wolf
7ves

```

The rules for unpacking the dictionary are simple:

1. Read the number at the start of the line, and copy that many characters from the beginning of the previous word. (If there is no number, copy as many characters as you did last time.)
2. Append the following letters to the word.

So, our first word is `aa`, followed by `2h`, which means "copy the first two letters of `aa` and append `h`," forming `aah`. Then `3ed` becomes `aahed`, and since the next line doesn't have a number, we copy 3 characters again to form `aahing`. This process continues throughout the rest of the dictionary. The resulting words from the small sample input are:

```
aa
aah
aahed
aahing
aahs
aal
aaliis
aals
aardvark
aardvarks
aardwolf
aardwolves

```

Your challenge is to perform this unpacking in as few bytes as possible.

Each line of input will contain zero or more digits `0-9` followed by one or more lowercase letters `a-z`. You may take input and give output as either a list of strings, or as a single string with words separated by any character other than `0-9`/`a-z`.

Here is another small test case with a few edge cases not covered in the example:

```
abc cba 1de fg hi 0jkl mno abcdefghijk 10l
=> abc cba cde cfg chi jkl mno abcdefghijk abcdefghijl

```

You may also test your code on the full dictionary: input, output.

# Answer
# Vim, 57 bytes

```
:%s/\a/ &
:%norm +hkyiwjP
:g/\d/norm diw-@"yl+P
:%s/ //g

```

Try it online!
> 13 votes

# Answer
# JavaScript (ES6),  ~~66 62~~  61 bytes

```
a=>a.map(p=s=>a=a.slice([,x,y]=/(\d*)(.*)/.exec(s),p=x||p)+y)

```

Try it online!

### Commented

```
a =>                  // a[] = input, re-used to store the previous word
  a.map(p =           // initialize p to a non-numeric value
  s =>                // for each string s in a[]:
    a =               //   update a:
      a.slice(        //     extract the correct prefix from the previous word:
        [, x, y] =    //       load into x and y:
          /(\d*)(.*)/ //         the result of a regular expression which splits the new
          .exec(s),   //         entry into x = leading digits and y = trailing letters
                      //       this array is interpreted as 0 by slice()
        p = x || p    //       update p to x if x is not an empty string; otherwise leave
                      //       it unchanged; use this as the 2nd parameter of slice()
      )               //     end of slice()
      + y             //     append the new suffix
  )                   // end of map()

```
> 11 votes

# Answer
# brainfuck, 201 bytes

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

```

Try it online!

Requires a trailing newline at the end of the input. A version without this requirement is 6 bytes longer:

# brainfuck, 207 bytes

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

```

Try it online!

Both versions assume all numbers are strictly less than 255.

## Explanation

The tape is laid out as follows:

```
tempinputcopy 85 0 inputcopy number 1 a 1 a 1 r 1 d 0 w 0 o 0 l 0 f 0 ...

```

The "number" cell is equal to 0 if no digits are input, and n+1 if the number n is input. Input is taken at the cell marked "85".

```
,[                     take input and start main loop
 [                     start number input loop
  [-<+>>>+<<]          copy input to tempinputcopy and inputcopy
  >-[---<+>]           put the number 85 in the cell where input was taken
  <[[-<]>>]            test whether input is less than 85; ending position depends on result of comparison
                       (note that digits are 48 through 57 while letters are 97 through 122)
  <[-]>                clean up by zeroing out the cell that didn't already become zero
  >[                   if input was a digit:
   <<,>>               get next input character
   >[-[-<++++++++++>]] multiply current value by 10 and add to current input
   ++++                set number cell to 4 (as part of subtracting 47)
   <[->+<]             add input plus 10*number back to number cell
   -[----->-<]         subtract 51
  <]                   move to cell we would be at if input were a letter
 <]                    move to input cell; this is occupied iff input was a digit

                       part 2: update/output word

 >>>                   move to number cell
 [                     if occupied (number was input):
  [>>]+[-<<]>>         remove existing marker 1s and decrement number cell to true value
  [[>>]+[<<]>>-]       create the correct amount of marker 1s
 ]
 +[>>]<[-]             zero out cell containing next letter from previous word
 <[<<]>                return to inputcopy
 [->[>>]<+<[<<]>]      move input copy to next letter cell
 >[>.>]                output word so far
 +[                    do until newline is read:
  >[-]<                zero out letter cell
  ,.                   input and output next letter or newline
  [->+>+<<]            copy to letter cell and following cell
  >>----------         subtract 10 to compare to newline
 ]
 <[<<]>-               zero out number cell (which was 1 to make copy loop shorter)
 <<<,                  return to input cell and take input
]                      repeat until end of input

```
> 6 votes

# Answer
# Perl 6, ~~50~~ 48 bytes

*-2 bytes thanks to nwellnhof*

```
{my$l;.map:{$!=S[\d*]=substr $!,0,$l [R||]=~$/}}

```

Try it online!

A port of Arnauld's solution. Man, that `R||` trick was a rollercoaster from 'I think this could be possible', to 'nah, it's impossible', to 'kinda maybe possible' and finally 'aha!'

### Explanation:

```
{my$l;.map:{$!=S[\d*]=substr $!,0,$l [R||]=~$/}}
{                                              }  # Anonymous code block
 my$l;    # Declare the variable $l, which is used for the previous number
      .map:{                                  }  # Map the input list to
            $!=              # $! is used to save the previous word
               S[\d*]=       # Substitute the number for
                      substr $!,0    # A substring of the previous word
                                 ,              # With the length of
                                           ~$0     # The num if it exists
                                  $l [R||]=        # Otherwise the previous num

```

The `$l [R||]=~$/` part roughly translates to `$l= ~$/||+$l` but... it has the same amount of bytes `:(`. Originally, it saved bytes using an anonymous variable so the `my$l` was gone but that doesn't work since the scope is now the substitution, not the `map` codeblock. Oh well. Anyways, `R` is the reverse metaoperator, so it reverses the arguments of `||`, so the `$l` variable ends up being assigned the new number (`~$/`) if it exists, otherwise itself again.

It could be 47 bytes if Perl 6 didn't throw a kinda redundant compiler error for `=~`.
> 5 votes

# Answer
# Ruby, ~~49~~ ~~45~~ 43 bytes

```
$0=$_=$0[/.{0#{p=$_[/\d+/]||p}}/]+$_[/\D+/]

```

Try it online!

### Explanation

```
$0=                                         #Previous word, assign the value of
   $_=                                      #Current word, assign the value of
      $0[/.{0#{              }}/]           #Starting substring of $0 of length p which is
               p=$_[/\d+/]||p               #defined as a number in the start of $_ if any
                                 +$_[/\D+/] #Plus any remaining non-digits in $_

```
> 5 votes

# Answer
# C (gcc), ~~65~~ ~~57~~ ~~55~~ 53 bytes

```
n;b[9];c=b;f(){scanf("%d",&n);gets(c+n)&&f(puts(c));}

```

Try it online!

### Explanation:

```
n;                  /* `n` stores the shared prefix length, implicitly 0 */

b[9];               /* int[] buffer we read into, we need 12+1 bytes for the
                       largest words, this buffer is 9*4=36 bytes */

c=b;                /* if we use `b` in pointer arithmetic it would be an int*,
                       but we want to address individual bytes, so we need to
                       store the address as an integer. */

f() {               /* the unpacking function */

    scanf("%d",&n); /* read the common prefix length, if scanf fails because no
                       new prefix length is given then `n`s value will remain
                       the same, which is exactly what we want!  :-) */

    gets(c+n)       /* read the suffix part, the first `n` characters are the
                       common prefix */

        &&          /* short-circuit, so if the gets fails the next part is not
                       executed */

    f(puts(c));     /* print the word that was extracted and call `f`
                       recursively to handle the next word */
}

```
> 5 votes

# Answer
## Python 3.6+, ~~172~~ ~~195~~ ~~156~~ ~~123~~ ~~122~~ ~~121~~ 104 bytes

```
import re
def f(l,n=0,w=""):
 for s in l:t=re.match("\d*",s)[0];n=int(t or n);w=w[:n]+s[len(t):];yield w

```

Try it online!

### Explanation

I caved, and used Regular Expressions. This saved at least 17 bytes. :

```
t=re.match("\d*",s)[0]

```

When the string doesn't begin with a digit at all, the length of this string will be `0`. This means that:

```
n=int(t or n)

```

will be `n` if `t` is empty, and `int(t)` otherwise.

```
w=w[:n]+s[len(t):]

```

removes the number that the regular expression found from `s` (if there's no number found, it'll remove `0` characters, leaving `s` untruncated) and replaces all but the first `n` characters of the previous word with the current word fragment; and:

```
yield w

```

outputs the current word.
> 4 votes

# Answer
## Haskell, ~~82~~ 81 bytes

```
tail.map concat.scanl p["",""]
p[n,l]a|[(i,r)]<-reads a=[take i$n++l,r]|1<2=[n,a]

```

Takes and returns a list of strings.

Try it online!

```
        scanl p["",""]        -- fold function 'p' into the input list starting with
                              -- a list of two empty strings and collect the
                              -- intermediate results in a list
  p [n,l] a                   -- 1st string of the list 'n' is the part taken form the last word
                              -- 2nd string of the list 'l' is the part from the current line
                              -- 'a' is the code from the next line
     |[(i,r)]<-reads a        -- if 'a' can be parsed as an integer 'i' and a string 'r'
       =[take i$n++l,r]       -- go on with the first 'i' chars from the last line (-> 'n' and 'l' concatenated) and the new ending 'r'
     |1<2                     -- if parsing is not possible
       =[n,a]                 -- go on with the previous beginning of the word 'n' and the new end 'a'
                              -- e.g. [         "aa",     "2h",      "3ed",       "ing"       ]
                              -- ->   [["",""],["","aa"],["aa","h"],["aah","ed"],["aah","ing"]]
  map concat                  -- concatenate each sublist
tail                          -- drop first element. 'scanl' saves the initial value in the list of intermediate results.

```

Edit: -1 byte thanks to @Nitrodon.
> 4 votes

# Answer
# Japt, ~~19~~ ~~18~~ 17 bytes

Initially inspired by Arnauld's JS solution.

```
;£=¯V=XkB ªV +XoB

```

Try it

```
                      :Implicit input of string array U
 £                    :Map each X
   ¯                  :  Slice U to index
      Xk              :    Remove from X
;       B             :     The lowercase alphabet (leaving only the digits or an empty string, which is falsey)
          ªV          :    Logical OR with V (initially 0)
    V=                :    Assign the result to V for the next iteration
             +        :  Append
              Xo      :  Remove everything from X, except
;               B     :   The lowercase alphabet
  =                   :  Reassign the resulting string to U for the next iteration

```
> 3 votes

# Answer
# Jelly, 16 bytes

```
⁹fØDVo©®⁸ḣ;ḟØDµ\

```

Try it online!

### How it works

```
⁹fØDVo©®⁸ḣ;ḟØDµ\  Main link. Argument: A (array of strings)

              µ\  Cumulatively reduce A by the link to the left.
⁹                     Yield the right argument.
  ØD                  Yield "0123456789".
 f                    Filter; keep only digits.
    V                 Eval the result. An empty string yields 0.
     o©               Perform logical OR and copy the result to the register.
       ®              Yield the value in the register (initially 0).
        ⁸ḣ            Head; keep that many character of the left argument.
          ;           Concatenate the result and the right argument.
            ØD        Yield "0123456789".
           ḟ          Filterfalse; keep only non-digits.

```
> 2 votes

# Answer
# Groovy, 74 bytes

```
{w="";d=0;it.replaceAll(/(\d*)(.+)/){d=(it[1]?:d)as int;w=w[0..<d]+it[2]}}

```

Try it online!

### Explanation:

```
{                                                                        }  Closure, sole argument = it
 w="";d=0;                                                                  Initialize variables
          it.replaceAll(/(\d*)(.+)/){                                   }   Replace every line (since this matches every line) and implicitly return. Loop variable is again it
                                     d=(it[1]?:d)as int;                    If a number is matched, set d to the number as an integer, else keep the value
                                                        w=w[0..<d]+it[2]    Set w to the first d characters of w, plus the matched string

```
> 2 votes

# Answer
# Python 2, 118 bytes

```
import re
n=0
l=input()
o=l.pop(0)
print o
for i in l:(N,x),=re.findall('(\d*)(.+)',i);n=int(N or n);o=o[:n]+x;print o

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 69 bytes

```
+`((\d+).*¶)(\D)
$1$2$3
\d+
$*
+m`^((.)*(.).*¶(?<-2>.)*)(?(2)$)1
$1$3

```

Try it online! Link includes harder test cases. Explanation:

```
+`((\d+).*¶)(\D)
$1$2$3

```

For all lines that begin with letters, copy the number from the previous line, looping until all lines begin with a number.

```
\d+
$*

```

Convert the number to unary.

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

```

Use balancing groups to replace all `1`s with the corresponding letter from the previous line. (This turns out to be slightly golfier than replacing all runs of `1`s.)
> 1 votes

# Answer
# Red, 143 bytes

```
func[b][a: charset[#"a"-#"z"]u: b/1 n: 0 foreach c b[parse c[copy m to a
p: copy s to end(if p<> c[n: do m]print u: rejoin[copy/part u n s])]]]

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-p`, ~~45~~ 41 bytes

```
s:\d*:substr($p,0,$l=$&+$l*/^\D/):e;$p=$_

```

Try it online!

Explanation:

```
s:\d*:substr($p,0,$l=$&+$l*/^\D/):e;$p=$_ Full program, implicit input
s:   :                           :e;      Replace
  \d*                                       Any number of digits
      substr($p,0,              )           By a prefix of $p (previous result or "")
                  $l=  +                      With a length (assigned to $l) of the sum
                     $&                         of the matched digits
                          *                     and the product
                        $l                        of $l (previous length or 0)
                           /^\D/                  and whether there is no number in the beginning (1 or 0)
                                                (product is $l if no number)
                                    $p=$_ Assign output to $p
                                          Implicit output

```
> 1 votes

# Answer
# Java (JDK), 150 bytes

```
a->{String p="",s[];for(int n=0,i=0;i<a.length;a[i]=p=p.substring(0,n=s.length<1?n:new Short(s[0]))+a[i++].replaceAll("\\d",""))s=a[i].split("\\D+");}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~20~~ ~~19~~ ~~17~~ 16 bytes

```
õUvyþDdi£U}Xyá«=

```

Try it online or verify all test cases.

**Explanation:**

```
õ               # Push an empty string ""
 U              # Pop and store it in variable `X`
v               # Loop `y` over the (implicit) input-list:
 yþ             #  Push `y`, and leave only the digits (let's call it `n`)
   Ddi  }       #  If it's a non-negative integer (thus NOT an empty string ""):
      £         #   Pop and push the first `n` characters of the string
       U        #   Pop and store it in variable `X`
         X      #  Push variable `X`
          yá    #  Push `y`, and leave only the letters
            «   #  Merge them together
             =  #  Print it with trailing newline (without popping)

```
> 1 votes

# Answer
# Scala, 226 129 102 bytes

Thanks @ASCII-only for their work here (and for the Groovy answer).

```
s=>{var(w,d,r)=("",0,"(\\d*)(.+)".r)
s map(_ match{case r(a,b)=>{if(a>"")d=a.toInt
w=w.take(d)+b}
w})}

```

Try it online!
> 1 votes

# Answer
# Jelly, 27 bytes

```
f€ȯ@\V,ɗḟ€ɗØDZẎḊṖḣ2/Ż;"f€Øa

```

Try it online!
> 0 votes

# Answer
# Groovy, ~~103~~ 99 bytes

```
{w=it[0];d=0;it.collect{m=it=~/(\d+)(.+)/;i=m.find()?{d=m[0][1] as int;m[0][2]}():it;w=w[0..<d]+i}}

```

Try it online!
> 0 votes

# Answer
# Common Lisp, 181 bytes

```
(do(w(p 0))((not(setf g(read-line t()))))(multiple-value-bind(a b)(parse-integer g :junk-allowed t)(setf p(or a p)w(concatenate'string(subseq w 0 p)(subseq g b)))(format t"~a~%"w)))

```

Try it online!

Ungolfed:

```
(do (w (p 0))   ; w previous word, p previous integer prefix (initialized to 0)
    ((not (setf g (read-line t ()))))   ; read a line into new variable g
                                        ; and if null terminate:
  (multiple-value-bind (a b)            ; let a, b the current integer prefix
      (parse-integer g :junk-allowed t) ; and the position after the prefix
    (setf p (or a p)                    ; set p to a (if nil (no numeric prefix) to 0)
          w (concatenate 'string        ; set w to the concatenation of prefix
             (subseq w 0 p)             ; characters from the previous word
             (subseq g b)))             ; and the rest of the current line
    (format t"~a~%"w)))                 ; print the current word

```

As usual, the long identifers of Common Lisp make it non particularly suitable for PPCG.
> 0 votes

# Answer
# Python 2, ~~101~~ ~~100~~ 99 bytes

```
import re
s=n='0'
for t in input():(m,w),=re.findall('(\d*)(.+)',t);n=m or n;s=s[:int(n)]+w;print s

```

Try it online!
> 0 votes

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

```
a=>{int l=0,m,n;var p="";return a.Select(s=>{for(m=n=0;s[m]<58;n=n*10+s[m++]-48);return p=p.Substring(0,l=m>0?n:l)+s.Substring(m);});}

```

Try it online!

-9 bytes thanks to @ASCIIOnly!

Less golfed...

```
// a is an input list of strings
a=>{
  // l: last prefix length
  // m: current number of digits
  // n: current prefix length
  int l=0,m,n;
  // previous word
  var p="";
  // run a LINQ select against the input
  // s is the current word
  return a.Select(s=>{
    // nibble digits from start of the
    // current word to build up the
    // current prefix length
    for(m=n=0;
      s[m]<58;
      n=n*10+s[m++]-48);
    // append the prefix from the
    // previous word to the current
    // word and capture values
    // for the next iteration
    return
      p=p.Substring(0,l=m>0?n:l)+
      s.Substring(m);
  });
}

```
> 0 votes

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


title: All the digisibles

text:
# Question
Title: All the digisibles
A natural number (written in the decimal base) is qualified as **digisible** if and only if it fulfills the following 3 conditions:

1. none of its digits is zero,
2. all the digits that compose it are different,
3. the number is divisible by all the digits that compose it.

The challenge is to output all the digisibles (there are 548 digisibles).

## Examples

```
1         --> the smallest digisible
24        --> is digisible
2789136   --> is digisible
2978136   --> is digisible
2983176   --> is digisible
3298176   --> is digisible
3678192   --> is digisible
3867192   --> is digisible
3928176   --> is digisible
6387192   --> is digisible
7829136   --> is digisible
7836192   --> is digisible
7892136   --> is digisible
7892136   --> is digisible
9867312   --> the biggest digisible

1653724   --> is not digisible
1753924   --> is not digisible
23        --> is not digisible
2489167   --> is not digisible
5368192   --> is not digisible
60        --> is not digisible
7845931   --> is not digisible
8964237   --> is not digisible
9129      --> is not digisible

```

## Input

No input.

## Output

The list (or set) of all digisibles. The output does not have to be sorted.

## Complete output

```
1
2
3
4
5
6
7
8
9
12
15
24
36
48
124
126
128
132
135
162
168
175
184
216
248
264
312
315
324
384
396
412
432
612
624
648
672
728
735
784
816
824
864
936
1236
1248
1296
1326
1362
1368
1395
1632
1692
1764
1824
1926
1935
1962
2136
2184
2196
2316
2364
2436
2916
3126
3162
3168
3195
3216
3264
3276
3492
3612
3624
3648
3816
3864
3915
3924
4128
4172
4236
4368
4392
4632
4872
4896
4932
4968
6132
6192
6312
6324
6384
6432
6912
6984
8136
8496
8736
9126
9135
9162
9216
9315
9324
9432
9612
9648
9864
12384
12648
12768
12864
13248
13824
13896
13968
14328
14728
14832
16248
16824
17248
18264
18432
18624
18936
19368
21384
21648
21784
21864
23184
24168
24816
26184
27384
28416
29736
31248
31824
31896
31968
32184
34128
36792
37128
37296
37926
38472
39168
39816
41328
41832
42168
42816
43128
43176
46128
46872
48216
48312
61248
61824
62184
64128
68712
72184
73164
73248
73416
73962
78624
79128
79632
81264
81432
81624
81936
82416
84216
84312
84672
87192
89136
89712
91368
91476
91728
92736
93168
93816
98136
123648
123864
123984
124368
126384
129384
132648
132864
132984
134928
136248
136824
138264
138624
139248
139824
142368
143928
146328
146832
148392
148632
149328
149832
162384
163248
163824
164328
164832
167328
167832
168432
172368
183264
183624
184392
184632
186432
189432
192384
193248
193824
194328
194832
198432
213648
213864
213984
214368
216384
218736
219384
231648
231864
231984
234168
234816
236184
238416
239184
241368
243168
243768
243816
247968
248136
248976
261384
263184
273168
281736
283416
284136
291384
293184
297864
312648
312864
312984
314928
316248
316824
318264
318624
319248
319824
321648
321864
321984
324168
324816
326184
328416
329184
341928
342168
342816
346128
348192
348216
348912
349128
361248
361824
361872
362184
364128
364728
367248
376824
381264
381624
382416
384192
384216
384912
391248
391824
392184
394128
412368
413928
416328
416832
418392
418632
419328
419832
421368
423168
423816
427896
428136
428736
431928
432168
432768
432816
436128
438192
438216
438912
439128
461328
461832
463128
468312
469728
478296
478632
481392
481632
482136
483192
483216
483672
483912
486312
489312
491328
491832
493128
498312
612384
613248
613824
613872
614328
614832
618432
621384
623184
623784
627984
631248
631824
632184
634128
634872
641328
641832
643128
648312
671328
671832
681432
684312
689472
732648
732816
742896
746928
762384
768432
783216
789264
796824
813264
813624
814392
814632
816432
819432
823416
824136
824376
831264
831624
832416
834192
834216
834912
836472
841392
841632
842136
843192
843216
843912
846312
849312
861432
864312
873264
891432
894312
897624
912384
913248
913824
914328
914832
918432
921384
923184
927864
931248
931824
932184
934128
941328
941832
943128
948312
976248
978264
981432
984312
1289736
1293768
1369872
1372896
1376928
1382976
1679328
1679832
1687392
1738296
1823976
1863792
1876392
1923768
1936872
1982736
2137968
2138976
2189376
2317896
2789136
2793168
2819376
2831976
2931768
2937816
2978136
2983176
3186792
3187296
3196872
3271968
3297168
3298176
3619728
3678192
3712968
3768912
3796128
3816792
3817296
3867192
3869712
3927168
3928176
6139728
6379128
6387192
6389712
6391728
6719328
6719832
6731928
6893712
6913872
6971328
6971832
7168392
7198632
7231896
7291368
7329168
7361928
7392168
7398216
7613928
7639128
7829136
7836192
7839216
7861392
7863912
7891632
7892136
7916328
7916832
7921368
8123976
8163792
8176392
8219736
8312976
8367912
8617392
8731296
8796312
8912736
8973216
9163728
9176328
9176832
9182376
9231768
9237816
9278136
9283176
9617328
9617832
9678312
9718632
9723168
9781632
9782136
9812376
9867312

```

## Rules

* The output can be given in any convenient format.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Haskell, 83 bytes

-1 byte thanks to @Laikoni, -13 bytes thanks to @H.PWiz!

```
f=[n|n<-[1..10^7],x<-[show n],and[d>'0'&&n`mod`read[d]<1|d<-x],[a|a<-x,b<-x,a==b]==x]

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~28~~ 23 bytes

```
ΦＥＸχ⁷Ｉι∧Πι¬Φι∨⁻μ⌕ιλ﹪κＩλ

```

Try it online! for numbers of up to five digits (too slow for larger numbers). Explanation:

```
   χ                    Predefined variable 10
  Ｘ                     Raised to power
    ⁷                   Literal 7
 Ｅ                      Map over implicit range
      ι                 Current value
     Ｉ                  Cast to string
Φ                       Filter over list of strings
         ι              Current string
        Π               Digital product (is nonzero)
       ∧                Logical And
          ¬             Logical Not
            ι           Current string
           Φ            Filter over digits as characters
               μ         Inner index
              ⁻          Minus
                ⌕        First position of
                  λ      Current character in
                 ι       Current string
             ∨          Logical Or
                    κ   Outer index
                   ﹪    Modulo
                      λ Current character
                     Ｉ  Cast to integer

```
> 1 votes

# Answer
# Python 3, 132 bytes

```
for i in range(1,int(1e7)):
 if '0' not in str(i) and len(set(str(i)))==len(str(i)) and not any([i%int(j) for j in str(i)]):print(i)

```

Try it online!
> 1 votes

---
Tags: code-golf, math, kolmogorov-complexity, arithmetic
---


title: Monday Mini-Golf #3: Anagram distance

text:
# Question
Title: Monday Mini-Golf #3: Anagram distance
**Monday Mini-Golf:** A series of short challenges, posted (hopefully!) every Monday.
(Sorry this one's a little late.)

I'm sure most of you folks have heard of Levenshtein distance, an algorithm for calculating the distance between two strings. Well, this challenge is about implementing a similar algorithm of my own invention\*, called **anagram distance**. The main difference is that the order of the characters doesn't matter; instead, only the characters that are unique to one string or the other are measured.

# Challenge

The goal of the challenge is to write a program or function that takes in two strings and returns the anagram distance between them. The main way to do this is to use the following logic:

1. Convert both strings to lowercase and (optionally) sort each one's characters alphabetically.
2. While the strings contain at least one equal character, remove the first instance of this character from each string.
3. Add the lengths of the remaining strings and return/output the result.

## Example

If the inputs are:

```
Hello, world!
Code golf!

```

Then, lowercased and sorted, these become: (by JS's default sort; note the leading spaces)

```
 !,dehllloorw
 !cdefgloo

```

Removing all of the characters that are in both strings, we end up with:

```
,hllrw
cfg

```

Thus, the anagram distance between the original two strings = 6 + 3 = 9.

# Details

* The strings may be taken in any sensible format.
* The strings will consist only of printable ASCII.
* The strings themselves will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.)
* You need not use this exact algorithm, as long as the results are the same.

# Test-cases

**Input 1:**

```
Hello, world!
Code golf!

```

**Output 1:**

```
9

```

**Input 2:**

```
12345 This is some text.
.txet emos si sihT 54321

```

**Output 2:**

```
0

```

**Input 3:**

```
All unique characters here!
Bdfgjkmopvwxyz?

```

**Output 3:**

```
42

```

**Input 4:**

```
This is not exactly like Levenshtein distance,
but you'll notice it is quite similar.

```

**Output 4:**

```
30

```

**Input 5:**

```
all lowercase.
ALL UPPERCASE!

```

**Output 5:**

```
8

```

# Scoring

This is , so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Oct 12. Good luck!~~

**Edit:** Congrats to the winner, @isaacg, using Pyth (again) for an astounding **12 bytes!**

\*If this algorithm has been used elsewhere and/or given another name, please let me know! I wasn't able to find it with a 20-minute search.

# Answer
# Pyth, 12 bytes

```
ls.-M.prR0.z

```

Test suite

The operation in question is equivalent to Pyth's bagwise subtraction operator, `.-`, applied in both directions. You could call it bagwise xor, I suppose.

The solution is:

`.z`: get input as list of 2 strings.

`rR0`: convert both to lowercase.

`.p`: Form all permutations, i.e. normal and reversed.

`.-M`: Map the `.-` operation over each ordering.

`s`: Concatenate the results.

`l`: Print the length.
> 13 votes

# Answer
# JavaScript (ES7), 92 bytes

Defines an anonymous function.

To test, run the snippet below. You can edit the code and click 'Test' to compare its output with the original. (Leave a comment if you find an improvement!) Input is like `"Hello, world!", "Code golf!"` in the input box.

Thanks to @ETHproductions for saving 6 bytes!

```
(a,b)=>[for(v of a[t="toLowerCase"]())if((b=b[t]())==(b=b.replace(v,"")))v][l="length"]+b[l]
```

```
<!--                               Try the test suite below!                              --><strong id="bytecount" style="display:inline; font-size:32px; font-family:Helvetica"></strong><strong id="bytediff" style="display:inline; margin-left:10px; font-size:32px; font-family:Helvetica; color:lightgray"></strong><br><br><pre style="margin:0">Code:</pre><textarea id="textbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><pre style="margin:0">Input:</pre><textarea id="inputbox" style="margin-top:5px; margin-bottom:5px"></textarea><br><button id="testbtn">Test!</button><button id="resetbtn">Reset</button><br><p><strong id="origheader" style="font-family:Helvetica; display:none">Original Code Output:</strong><p><div id="origoutput" style="margin-left:15px"></div><p><strong id="newheader" style="font-family:Helvetica; display:none">New Code Output:</strong><p><div id="newoutput" style="margin-left:15px"></div><script type="text/javascript" id="golfsnippet">var bytecount=document.getElementById("bytecount");var bytediff=document.getElementById("bytediff");var textbox=document.getElementById("textbox");var inputbox=document.getElementById("inputbox");var testbtn=document.getElementById("testbtn");var resetbtn=document.getElementById("resetbtn");var origheader=document.getElementById("origheader");var newheader=document.getElementById("newheader");var origoutput=document.getElementById("origoutput");var newoutput=document.getElementById("newoutput");textbox.style.width=inputbox.style.width=window.innerWidth-50+"px";var _originalCode=null;function getOriginalCode(){if(_originalCode!=null)return _originalCode;var allScripts=document.getElementsByTagName("script");for(var i=0;i<allScripts.length;i++){var script=allScripts[i];if(script.id!="golfsnippet"){originalCode=script.textContent.trim();return originalCode}}}function getNewCode(){return textbox.value.trim()}function getInput(){try{var inputText=inputbox.value.trim();var input=eval("["+inputText+"]");return input}catch(e){return null}}function setTextbox(s){textbox.value=s;onTextboxChange()}function setOutput(output,s){output.innerHTML=s}function addOutput(output,data){output.innerHTML+='<pre style="background-color:'+(data.type=="err"?"lightcoral":"lightgray")+'">'+escape(data.content)+"</pre>"}function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}function onTextboxChange(){var newLength=getByteCount(getNewCode());var oldLength=getByteCount(getOriginalCode());bytecount.innerHTML=newLength+" bytes";var diff=newLength-oldLength;if(diff>0){bytediff.innerHTML="(+"+diff+")";bytediff.style.color="lightcoral"}else if(diff<0){bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgreen"}else{bytediff.innerHTML="("+diff+")";bytediff.style.color="lightgray"}}function onTestBtn(evt){origheader.style.display="inline";newheader.style.display="inline";setOutput(newoutput,"");setOutput(origoutput,"");var input=getInput();if(input===null){addOutput(origoutput,{type:"err",content:"Input is malformed. Using no input."});addOutput(newoutput,{type:"err",content:"Input is malformed. Using no input."});input=[]}doInterpret(getNewCode(),input,function(data){addOutput(newoutput,data)});doInterpret(getOriginalCode(),input,function(data){addOutput(origoutput,data)});evt.stopPropagation();return false}function onResetBtn(evt){setTextbox(getOriginalCode());origheader.style.display="none";newheader.style.display="none";setOutput(origoutput,"");setOutput(newoutput,"")}function escape(s){return s.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}window.alert=function(){};window.prompt=function(){};function doInterpret(code,input,cb){var workerCode=interpret.toString()+";function stdout(s){ self.postMessage( {'type': 'out', 'content': s} ); }"+" function stderr(s){ self.postMessage( {'type': 'err', 'content': s} ); }"+" function kill(){ self.close(); }"+" self.addEventListener('message', function(msg){ interpret(msg.data.code, msg.data.input); });";var interpreter=new Worker(URL.createObjectURL(new Blob([workerCode])));interpreter.addEventListener("message",function(msg){cb(msg.data)});interpreter.postMessage({"code":code,"input":input});setTimeout(function(){interpreter.terminate()},1E4)}setTimeout(function(){getOriginalCode();textbox.addEventListener("input",onTextboxChange);testbtn.addEventListener("click",onTestBtn);resetbtn.addEventListener("click",onResetBtn);setTextbox(getOriginalCode())},100);function interpret(code,input){window={};alert=function(s){stdout(s)};window.alert=alert;console.log=alert;prompt=function(s){if(input.length<1)stderr("not enough input");else{var nextInput=input[0];input=input.slice(1);return nextInput.toString()}};window.prompt=prompt;(function(){try{var evalResult=eval(code);if(typeof evalResult=="function"){var callResult=evalResult.apply(this,input);if(typeof callResult!="undefined")stdout(callResult)}}catch(e){stderr(e.message)}})()};</script>
```

More about the test suite

**How it works**

```
//Define function w/ paramters a, b
(a,b)=>
     //lowercase a
     //for each character v in a:
     [for(v of a[t="toLowerCase"]())
          //lowercase b
          //remove the first instance of v in b
          //if b before removal equals b after removal (if nothing was removed):
          if((b=b[t]())==(b=b.replace(v,"")))
               //keep v in the array of a's values to keep
               v]
     //get the length of the computed array
     [l="length"]
     //add b's length
     +b[l]
     //implicitly return the sum

```
> 8 votes

# Answer
# CJam, ~~23~~ 19 bytes

```
2{'¡,lelfe=}*.-:z:+

```

Try it online in the CJam interpreter.

### How it works

```
2{         }*        Do the following twice:
  '¡,                  Push the string of the first 161 Unicode charcters.
     lel               Read a line from STDIN and convert it to lowercase.
        fe=            Count the number of occurrences of each of the 160
                       characters in the lowercased line.
             .-      Vectorized subtraction; push the differences of the
                     occurrences of all 161 characters.
               :z    Apply absolute value to each difference.
                 :+  Push the sum of all results.

```
> 5 votes

# Answer
# Ruby, 62

```
#!ruby -naF|
gets
p$F.count{|c|!$_.sub!(/#{Regexp.escape c}/i){}}+~/$/

```

There has to be a better way.

Edit: 57 chars thanks to iamnotmaynard investigating a path I was too lazy to.

```
#!ruby -naF|
gets.upcase!
p$F.count{|c|!$_.sub!(c.upcase){}}+~/$/

```
> 4 votes

# Answer
# Python, ~~90~~ ~~87~~ ~~81~~ ~~80~~ 79 bytes

```
lambda a,b,s=str.lower:sum(abs(s(a).count(c)-s(b).count(c)))for c in{*s(a+b)}))

```

Python \<3.5 version, 80 bytes

```
lambda a,b,s=str.lower:sum(abs(s(a).count(c)-s(b).count(c))for c in set(s(a+b)))

```

### Explanation

For each character in a or b, count up the number of occurrences in each string, and add the (positive) difference.

Edit: Re-read rules, realized anonymous functions are acceptable, improved answer by getting rid of raw\_input. First golf, please be gentle!

Thanks to sp3000 for the improvement of redefining str.lower and making me realize print was unnecessary. Also spaces. Still learning.

Using python \>=3.5, there's a shorter way of defining sets, so a byte can be saved over previous versions.
> 4 votes

# Answer
# Retina, ~~40~~ 20 bytes

*20 bytes saved thanks to Martin Büttner.*

Place each line in its own file and replace the `\n` with a literal newline.

```
+i`(.)(.*\n.*)\1
$2
.

```
> 3 votes

# Answer
# pb, 648 bytes

```
^w[B!0]{t[B]vb[T]^>}vb[-1]w[X!0]{<t[64]w[T!0]{w[B!0]{b[B-1]v}^[Y]t[T-1]}}w[B!-1]{w[B=0]{b[27]}t[26]w[T!0]{w[B!0]{b[B-1]v}^[Y]t[T-1]}>}b[0]w[X!0]{<w[B!0]{b[1]v}^[Y]w[B=0]{b[32]}w[B=1]{b[0]}}^w[B!0]{t[B]vb[B+T]^>}vb[1]<w[B!9]{t[B]b[0]vv<[X]w[B!0]{>}b[T]^^<[X]w[B!0]{>}<}b[0]<w[X!-1]{t[B]vb[1]^w[B!1]{>}vvw[X!-1]{w[B=T]{b[0]<[X]^w[B!1]{>}^b[0]vt[2]}<}^[Y]vw[B!1]{>}b[0]^<}t[0]w[B!1]{w[B!0]{t[T+1]b[0]}>}b[0]vvw[X!-1]{w[B!0]{t[T+1]b[0]}<}>b[11]^b[T]w[B!0]{vw[B!11]{>}t[B]b[0]>b[T]<[X]^t[B]b[0]vw[B!11]{>}<w[T!0]{t[T-1]b[B+1]w[B=11]{b[0]^<[X]b[B+1]vw[B!11]{>}<}}^<[X]}vw[B!11]{b[B+48]>}b[0]<w[B!0]{w[B!0]{>}<t[B]^^<[X]w[B!0]{>}b[T]<[X]vvw[B!0]{>}<b[0]<}

```

Takes input with a tab character separating the two strings.

This one was a doozy. Actually implementing the algorithm wasn't the hard part, that came relatively easily. But I had to do two things that are difficult to do in pb: Case insensitivity and itoa. I happened to have a program for converting to lowercase just lying around (itself 211 bytes long) and everything else was tacked onto the end to do the work for this challenge specifically.

You can watch this program run on YouTube! There are a couple things you should keep in mind if you do:

* This version of the program is slightly modified, weighing in at 650 bytes. The only difference is that 255 is used as a flag value instead of -1, because trying to print `chr(-1)` crashes the interpreter when running in watch mode.
* The input in that video is `Hello, world!` and `Code golf.`. This is slightly different than one of the example inputs in the challenge; I used it because it was short but modified it so the correct output would be 10 instead of 9. This is just to show off that the number is printed correctly even if it's multiple digits, which is hard in pb.
* The interpreter is awful, and it shows here. Notably, the tab character throws off the spacing so things aren't lined up for large portions of the video, whenever a byte is set to 10 it shows a line break even though the language still considers it to be one "line", and the fact that it just moves the cursor to the start instead of clearing the screen means that there are occasionally a number of characters in the video that aren't even really there, they just never went away from when they were there. There are some protections against this in pbi but the fact that `chr(10)` isn't handled properly makes them largely useless here. All that being said, I think it's almost kind of beautiful to watch. It's a huge mess of horrible code interpreting other horrible code, pieces of it breaking down in front of your eyes, and yet everything works just enough to get the right answer. It looks like garbage is being printed but if you watch closely enough with knowledge of the source you can make out what it's doing and why at any point. I feel like Cypher when I watch this video: `I... I don’t even see the code. All I see is blonde, brunette, red-head.`

Without further ado, here's the code ungolfed.

```
### UNTIL FURTHER NOTICE, ALL CODE YOU SEE HERE   ###
### IS JUST A SIMPLE LOWERCASE PROGRAM. ALL INPUT ###
### IS PRINTED UNALTERED UNLESS ITS ASCII CODE IS ###
### IN [65, 90], IN WHICH CASE IT IS PRINTED WITH ###
### 32 ADDED TO IT.                               ###

^w[B!0]{t[B]vb[T]^>}    # Copy entire input to Y=0
                        # (If the program ended here, it would be cat!)
vb[-1]                  # Leave a flag at the end of the copy (important later)

# Next, this program will set each of those bytes to 0 or 32, then add the input again.
# A byte needs to be set to 32 iff it's in [65, 90].
# pb can't test > or <, only == and !=.
# A workaround:

# Set each byte to max((byte - 64), 0)

w[X!0]{<        # For each byte:
    t[64]         # Set T to 64 as a loop variable
    w[T!0]{       # While T != 0:
        w[B!0]{     # While the current byte not 0:
            b[B-1]v   # Subtract one from the current cell, then go down one
                      # (guaranteed to be 0 and kill the loop)
        }
        ^[Y]        # Brush is at Y=0 or Y=1 and needs to be at Y=0.
                    # ^[Y] always brings brush to Y=0
        t[T-1]      # T--
    }
}

# Bytes that are currently 0 need to be 0.
# Bytes that are currently in [27, inf) need to be 0.
# Bytes in [1, 26] need to be 32.

# Set bytes that are equal to 0 to 27
# The only groups that have to be worried about are >26 and =<26.

# Then set each byte to max((byte - 26), 0)

w[B!-1]{         # Until we hit the flag:
    w[B=0]{b[27]}   # Set any 0 bytes to 27
    t[26]           # T as loop variable again
    w[T!0]{         # While T != 0:
        w[B!0]{       # While the current byte not 0:
            b[B-1]v     # Subtract one from the current cell, then go down one
                        # (guaranteed to be 0 and kill the loop)
        }
        ^[Y]          # Brush is at Y=0 or Y=1 and needs to be at Y=0.
                      # ^[Y] always brings brush to Y=0
        t[T-1]        # T--
    }
>}
b[0]              # Clear the flag

# Set bytes that are equal to 0 to 32
# All others to 0

w[X!0]{<          # For each byte:
    w[B!0]{       # While the current byte not 0:
        b[1]v       # Set it to 1, then go down one
                    # (guaranteed to be 0 and kill the loop)
    }
    ^[Y]          # Back to Y=0 no matter what
    w[B=0]{b[32]} # Set 0 bytes to 32
    w[B=1]{b[0]}  # Set 1 bytes to 0
}

# Any byte that had a capital letter is now 32. All others are 0.
# Add the original values to the current values to finish.

^w[B!0]{          # For each byte OF ORIGINAL INPUT:
    t[B]vb[B+T]^>   # Add it to the space below
}

### ABOVE IS THE ENTIRE LOWERCASE PROGRAM. THE    ###
### REST OF THE CODE IMPLEMENTS THE ALGORITHM.    ###

vb[1]            # Leave a flag after the end, guaranteed to be further right
                 # than anything else

<w[B!9]{         # Starting from the end, until hitting a tab:
    t[B]b[0]        # Store the last byte and erase it
    vv<[X]          # Go down two columns and all the way to the left
    w[B!0]{>}       # Go right until reaching an empty space
    b[T]            # Print the stored byte
    ^^<[X]w[B!0]{>} # Go back to the end of the first line
    <
}

b[0]              # Erase the tab
<w[X!-1]{         # For each byte in the first line:
    t[B]            # Store that byte
    vb[1]           # Mark that byte to be found later
    ^w[B!1]{>}      # Find the flag at the end
    vvw[X!-1]{      # For everything in the other line:
        w[B=T]{       # If the current byte is the same as the saved byte:
            b[0]        # Set it to 0
            <[X]^       # Go to the beginning of line 2
            w[B!1]{>}   # Find the marker for where the program is working in line 1
            ^b[0]v      # Set that byte that the program is working on to 0
            t[2]        # Stay on line 2 and start looking for a 2 (will never appear)
                        # (If this block was entered, it basically breaks the outer loop.)
        }
        <
    }
    ^[Y]v           # Ensure that the brush is on Y=1
    w[B!1]{>}       # Find the marker for where the program is working in line 1
    b[0]^<          # Erase the marker and start working on the next byte
}

t[0]              # Set T to 0. It's going to be used for counting the remaining bytes.

w[B!1]{           # Until hitting the flag at the very right:
    w[B!0]{         # If the current byte is not 0:
        t[T+1]        # Add 1 to T
        b[0]          # Set the current byte to 0
    }
    >
}
b[0]              # Clear the flag

vvw[X!-1]{        # Same as above, but for Y=2
    w[B!0]{
        t[T+1]
        b[0]
    }
    <
}

# T now contains the number that needs to be printed!!
# Now, to print out a number in decimal...

>b[11]            # A flag that shows the end of the number
                  # (so 0 digits aren't confused for other empty spaces on the canvas)
^b[T]             # The number to be converted to digits
w[B!0]{           # While the number to be converted is not 0:
    vw[B!11]{>}     # Go to the flag
    t[B]b[0]>b[T]   # Move it right
    <[X]^t[B]b[0]   # Store the number to be converted to digits to T and clear its space on the canvas
    vw[B!11]{>}<    # Go to the left of the flag
    w[T!0]{         # While T is not 0:
        t[T-1]        # T--
        b[B+1]        # B++
        w[B=11]{      # If B is 10:
            b[0]        # Set it back to 0
            ^<[X]b[B+1]   # Add 1 to a counter to be converted after
            vw[B!11]{>}<  # Go back to continue converting T
        }
    }
^<[X]}

vw[B!11]{         # Add 48 to all digits to get correct ASCII value
    b[B+48]>
}

b[0]              # Clear the flag value, 0s now appear as 48 instead of 0 so it is unnecessary

<w[B!0]{          # While there are digits on Y=2:
    w[B!0]{>}<      # Go to the last one
    t[B]            # Save it to T
    ^^<[X]          # Go to (0, 0)
    w[B!0]{>}       # Go right until finding an empty space
    b[T]            # Print the digit in T
    <[X]vvw[B!0]{>} # Go to the end of Y=2
    <b[0]           # Erase it
    <               # Repeat until finished. :)
}

```
> 2 votes

# Answer
# C++ 199 bytes

Uses an array to store the count of each character in the first string, minis the count in the second string. Next it finds the sum of the absolute values of the elements of the array: this is the distance.

Golfed:

```
#define L(c) c<91&c>64?c+32:c
int d(char*a,char*b){int l[128];int i=128,s=0;for(;i-->0;)l[i]=0;for(;a[++i];)l[L(a[i])]++;for(i=-1;b[++i];)l[L(b[i])]--;for(i=0;++i<128;)s+=i[l]>0?i[l]:-i[l];return s;}

```

Ungolfed:

```
#define L(c) (c<='Z' && c>='A' ? c+'a'-'A':c)
//convert to lower case
int dist(char a[],char b[]){
  int l[128];
  int i = 128, s = 0;

  for(;i-->0;)
    l[i]=0;

  for(;a[++i]!='\0';)
    l[L(a[i])]++;

  for(i=-1;b[++i]!='\0';)
    l[L(b[i])]--;

  for(i=0;++i<128;)
    s+=i[l]>0?i[l]:-i[l];

  return s;
}

```
> 2 votes

# Answer
# PowerShell, 79 bytes

```
param($a,$b)$a=[char[]]$a.ToLower();$b=[char[]]$b.ToLower();(diff $a $b).Length

```

Almost the exact same code as my answer on Anagram Code Golf ... but ... I'm getting some weird behavior if I just snip off the `-eq0` from that answer, so I wound up needing to explicitly `.ToLower()` and recast outside of the `param` declaration.+

Explanation also (mostly) copied from that answer -- Takes the two string inputs, makes them lowercase, and re-casts them as char-arrays. The `diff` function (an alias for `Compare-Object`) takes the two arrays and returns items that are different between the two. We leverage that by re-casting the return as an array with `()`, and then checking its length.

+For example, I was getting bogus results with `param([char[]]$a,[char[]]$b)(diff $a $b).length` on the `all lowercase.`/`ALL UPPERCASE!` test. If I manually separated out the arrays (e.g., ran `(diff ('a','l','l'...`), it worked fine, but would fail every time there were capital/lowercase overlap with the casting. Everything I can read on the documentation states that `diff` is case-insensitive by default, so ... *shrug???*
> 1 votes

# Answer
# Bash, ~~68~~ 67 bytes

```
f()(fold -w1<<<"$1"|sort)
diff -i <(f "$1") <(f "$2")|grep -c ^.\

```

I *think* this works. Note the trailing space on the second line.

### Test cases

```
$ ./anagram "Hello, world!" "Code golf!"
9
$ ./anagram "12345 This is some text." ".txet emos si sihT 54321"
0
$ ./anagram "All unique characters here!" "Bdfgjkmopvwxyz?"
42
$ ./anagram "This is not exactly like Levenshtein distance," "but you'll notice it is quite similar."
30
$ ./anagram "all lowercase." "ALL UPPERCASE!"
8

```
> 1 votes

# Answer
**Perl, ~~52~~ 46 bytes + 3 switches (a,F,n) = ~~55~~ 49 bytes**

```
# 49 bytes (prefix 'x' to all characters so that values() could be removed)
perl -naF -E 'END{$c+=abs for%a;say$c}$a{x.lc}+=2*$.-3 for@F'

# 55 bytes
perl -naF -E 'END{$c+=abs for values%a;say$c}$a{+lc}+=2*$.-3 for@F'

```

Takes input from STDIN with the input strings in their own lines, terminated by EOF.

Switches:

```
-aF splits each input line into characters and stores this into @F
-n  loop over all input lines
-E  Execute the script from the next arg

```

Code:

```
# %a is the hash counting the occurances of the lowercase characters
# $. has the line number. Thus, 2*$.-3 is -1 for line 1 and +1 for line 2
$a{+lc}+=2*$.-3 for @F

# In the end (assuming 2 lines have been read), sum up the absolute values
# from the hash %a. Note that if a character occured more times in string 1
# its value be negative, if more in string 2 then positive, otherwise 0.
END {
    $c+=abs for values %a;
    say $c
}

```
> 1 votes

# Answer
# Bash + GNU utils, 53

```
S(){ sed 's/./\L&\n/g'|sort;};S>1;S|comm -3 1 -|wc -l

```

`sed` transforms to lowercase and splits the string into lines for `sort`. Since we need to do this twice I put it into a function. `comm3 -3` filters out the relevant lines and `wc -l` produces the number.

Input is via `STDIN`; since two commands read sequentially, you have to send `EOF` (Ctrl-D) twice, between the strings and at the end. Overwrites file `1`, if present.
> 1 votes

# Answer
# Matlab, 91 bytes

```
function r=f(s,t)
s=lower(s);t=lower(t);u=unique([s t]);r=sum(abs(histc(s,u)-histc(t,u)));

```

Try it online.

This works as follows:

1. Converts the strings to lower case.
2. Finds the **unique characters** of the two strings together. That is, determines all characters that ever appear in the strings.
3. Computes the **histogram** of each string. That is, for each string finds how many times each of the characters obtained in step 2 appears.
4. **Subtracts** the histograms and takes the absolute value of the differences. This represents how many times a character appears in one string **more** than in the other.
5. The result is the sum of those absolute differences.
> 1 votes

# Answer
# Jelly, 6 bytes

```
Œlœ^/L

```

Try it online!
> 1 votes

# Answer
# F#, ~~134~~ 126 bytes

```
let g=Seq.countBy Char.ToLower>>List.ofSeq
let f a b=g a@g b|>Seq.groupBy fst|>Seq.sumBy(snd>>Seq.map snd>>Seq.reduce(-)>>abs)

```

**Explanation**:

1. Count the number of times each (lowercased) character appears in `a` and `b` separately.
2. Group the counts together by their common character
3. Reduce each group with the `-` operator, which has the following effect:

* If only one value is found (i.e. the character appeared in only one input), that value is returned.
    * If two values are found (i.e. the character appeared in both inputs) subtract the second value from the first.
4. Sum the absolute value of the values from the previous step.
> 0 votes

# Answer
# Scala, 134 81 bytes

Thanks @ASCII-only for their work.

```
(s,t)=>{var k::l::_=List(s,t)map(_.toLowerCase.toBuffer)
((k--l)++(l--k)).length}

```

Try it online!
> 0 votes

---
Tags: code-golf, string, edit-distance
---


title: Invert png image

text:
# Question
Title: Invert png image
Create program or function that takes file name as an argument or reads it from standard input, and completes the following task:

1. Read image from a png file (name given as argument).
2. Reverse colors in that image, so that for example dark green (0, 75, 30) would become (255, 180, 225) (because 255-0=255, 255-75=180 and 255-30=225). You should not change alpha channel value.
3. Output that image to a file called `a.png` (in png format), or show it in GUI window.

This is . Standard loopholes apply.

# Answer
> 29 votes
# ImageMagick `display -fx`, 3 7 18 24 bytes

```
1-u

```

The ImageMagick tool `display` with the `fx` parameter can apply the above program to a png given as the parameter and display the results on screen.

Check out my post on meta about ImageMagick as a programming language. I wrote a prime tester over there as a proof of concept.

Re byte counting, `display -fx code filename` is equivalent to `perl -e code filename`, where we traditionally count just `code` for length.

# Answer
> 21 votes
## Pyth, ~~16~~ ~~15~~ 13 bytes

```
.w-LLL255'z\a

```

Outputs to `a.png`.

```
          z    read input
         '     read as RGB triples from file
   LLL         map over rows, then triples, then individual values...
  -   255      ...subtract from 255
.w         \a  write as image to a.png

```

Thanks to Jakube for 2 bytes!

# Answer
> 18 votes
# MATL, 10 bytes

```
255iYi-IYG

```

There are five different subformats of PNG, depending on how color is encoded. None of them seems to be more "optional" than the others. I chose the most flexible one, `Truecolor`, in which each pixel can have an arbitrary color. The above code also supports `Truecolor with alpha`, ignoring the alpha channel.

To know the color subformat of a PNG file: look for the byte sequence `[73 72 68 82]` near the beginning of the file; and the *tenth* byte from there will have one of the five values in the table linked above.

### How the code works

Pretty straightforward:

```
255    % push 255 to the stack
i      % input filename with extension '.png'
Yi     % read contents of that file as (truecolor) image
-      % subtract
IYG    % show image

```

### Example

I couldn't resist seeing myself inverted, so I downloaded this image (which is in subformat `Truecolor with alpha`), ran the code (second line is user input)

```
>> matl 255iYi-IYG
> 'C:\Users\Luis\Desktop\me.png'

```

and got

# Answer
> 17 votes
# Java, 295

```
import javax.imageio.*;class V{public static void main(String[]a)throws
Exception{java.awt.image.BufferedImage m=ImageIO.read(new
java.io.File(a[0]));for(int
x=m.getWidth(),y;x-->0;)for(y=m.getHeight();y-->0;)m.setRGB(x,y,m.getRGB(x,y)^-1>>>8);ImageIO.write(m,"png",new
java.io.File("a.png"));}}

```

# Answer
> 4 votes
# R, 124 bytes

```
p=png::readPNG(readline());p[,,-4]=1-p[,,-4];png("a.png",h=nrow(p),w=ncol(p));par(mar=rep(0,4));plot(as.raster(p));dev.off()

```

Reads in file name through stdin (`readline()`).

```
p=png::readPNG(readline()) #Reads in png as an RGBA array on range [0,1]
p[,,-4]=1-p[,,-4] #Takes the opposite value except on alpha layer
png("a.png",h=nrow(p),w=ncol(p)) #Prepares output png of same size as input
par(mar=rep(0,4)) #Makes the png take the full space of the figure region
plot(as.raster(p)) #Transforms p as a raster so that it can be plotted as is.
dev.off() #Closes the plotting device.

```

Example Input/Output using the first png I found on this computer :)

# Answer
> 3 votes
# CSS, 19 Bytes

```
*{filter:invert(1)}

```

http://output.jsbin.com/suqayudoyu

# Answer
> 2 votes
# Tcl, 176 bytes

```
foreach r [[image c photo -file {*}$argv] d] {set x {}
foreach c $r {lappend x [format #%06X [expr "0xFFFFFF-0x[string ra $c 1 end]"]]}
lappend y $x}
image1 p $y
image1 w a.png

```

Loads the PNG via the `photo` image type, gets the image data, converting each row and color by subtracting from #FFFFFF, then writes the file back to disk (as "a.png").

For best results, use TrueColor PNGs, since Tk will try to use the same color resolution as the source image data.

To see the image without sampling problems, add

```
pack [label .i -image image1]

```

to the end. (Obviously, this is longer than the disk-save option.)

# Answer
> 2 votes
## Mathematica, 140 bytes

```
Export["a.png",SetAlphaChannel[ColorCombine[Most@#],Last@#]&@MapAt[Image[1-ImageData@#]&,ColorSeparate[Import[#],{"R","G","B","A"}],{;;3}]]&

```

# Answer
> 2 votes
# cmd + IrfanView, 19 characters

```
i_view32 %1 /invert

```

Just the expensive alternative of Sparr's answer.

# Answer
> 2 votes
# Julia, ~~94~~ 79 bytes

```
using FileIO
save(ARGS[1],map(x->typeof(x)(1-x.r,1-x.g,1-x.b,1),load(ARGS[1])))

```

This is a full program that takes a file name as a command line argument and overwrites the given file with the inverted image. It requires that the `FileIO` and `Image` package be installed. The latter doesn't need to be imported though.

Call the program from the command line like `julia filename.jl /path/to/image.png`.

Ungolfed:

```
using FileIO # required for reading and writing image files

# Load the given image into a matrix where each element is an RGBA value
a = load(ARGS[1])

# Construct a new image matrix as the inverse of `a` by, for each element
# `x` in `a`, constructing a new RGBA value as 1 - the RGB portions of
# `x`, but with an alpha of 1 to avoid transparency.
b = map(x -> typeof(x)(1 - x.r, 1 - x.g, 1 - x.b, 1), a)

# Save the image using the same filename
save(ARGS[1], b)

```

Example:

# Answer
> 1 votes
## Python + PIL, 85 bytes

```
from PIL import Image
lambda a:Image.eval(Image.open(a),lambda x:255-x).save('a.png')

```

This defines an anonymous function that takes a filename as a string and saves the resultant image to `a.png`.

Test run:

# Answer
> 1 votes
# C + stb\_image + stb\_image\_write, ~~175~~ 162 bytes (or +72=~~247~~ 234)

My first submission on this site ever.

```
#include"stb_image.h"
#include"stb_image_write.h"
x,y,c,i;f(char*d){d=stbi_load(d,&x,&y,&c,i=0);for(;i<x*y*c;i++)d[i]=255-d[i];stbi_write_png("a.png",x,y,c,d,0);}

```

---

Could probably shave off a few bytes. Needs `stb_*` implementation to either be in a separate library, or at the start of this file with:

```
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION

```

I didn't include it in the count because it's essentially part of the library (esp. if it's compiled separately). +72 bytes to add that if required, however.

---

### Update 1:

Realized only a function (as opposed to an entire program) is acceptable, shaving off 15 bytes. The ***old*** implementation (which is an entire program), for reference:

```
x,y,i;main(int c,char**d){*d=stbi_load(d[1],&x,&y,&c,0);for(;i<x*y*c;i++)i[*d]=255-i[*d];stbi_write_png("a.png",x,y,c,*d,0);}

```

# Answer
> 1 votes
# Java, ~~300~~ 298 bytes

```
import javax.swing.*;void c(String f)throws Exception{java.awt.image.BufferedImage r=javax.imageio.ImageIO.read(new java.io.File(f));for(int i=0;i++<r.getWidth();)for(int j=0;j++<r.getHeight();)r.setRGB(i,j,(0xFFFFFF-r.getRGB(i,j))|0xFF000000);JOptionPane.showMessageDialog(null,new ImageIcon(r));}

```

# Answer
> 1 votes
# MATLAB / Octave, 31 bytes

**Code:**

```
imshow(imcomplement(imread(x)))

```

**Example:**

```
imshow(imcomplement(imread('balloons.png')))

```

**Explanation:**

Read the image, `x`, from a graphics file, complement the image, and then display the image.

# Answer
> 0 votes
## FFmpeg, 10 bytes

Edit: Taking a cue from @Sparr's answer

```
-vf negate

```

(the above when passed to ffplay alongwith the image name, will display the negated image)

---

```
ffplay %1 -vf negate

```

The above is saved as a batch file.

# Answer
> 0 votes
# Racket 282 bytes

```
(λ(fname)(let*((i(make-object bitmap% fname))(w(send i get-width))(h(send i get-height))(pixels(make-bytes(* w h 4)))(i2(make-object bitmap% w h)))
(send i get-argb-pixels 0 0 w h pixels)(send i2 set-argb-pixels 0 0 w h(list->bytes(map(lambda(x)(- 255 x))(bytes->list pixels))))i2))

```

More readable form:

```
(define(f fname)
  (let*(
        (i (make-object bitmap% fname))
        (w (send i get-width))
        (h (send i get-height))
        (pixels (make-bytes(* w h 4)))
        (i2 (make-object bitmap% w h)))
    (send i get-argb-pixels 0 0 w h pixels)
    (send i2 set-argb-pixels 0 0 w h
          (list->bytes
           (map
            (lambda(x) (- 255 x))
            (bytes->list pixels))))
    i2))

```

Usage:

```
(f "myimg.png")

```

# Answer
> 0 votes
## Golang, 311 bytes

```
package main
import("image"
."image/png"
."image/color"
."os")
func main(){f,_:=Open(Args[1])
i,_:=Decode(f)
q:=i.Bounds()
n:=image.NewRGBA(q)
s:=q.Size()
for x:=0;x<s.X;x++{for y:=0;y<s.Y;y++{r,g,b,a:=i.At(x,y).RGBA()
n.Set(x,y,RGBA{byte(255-r),byte(255-g),byte(255-b),byte(a)})}}
o,_:=Create("o")
Encode(o,n)}

```

### ungolfed

```
package main
import(
    "image"
    "image/png"
    "image/color"
    "os"
)

func main(){
    // open a png image.
    f, _ := os.Open(Args[1])

    // decode the png image to a positive image object(PIO).
    p, _ := png.Decode(f)

    // get a rectangle from the PIO.
    q := p.Bounds()

    // create a negative image object(NIO).
    n := image.NewRGBA(q)

    // get the size of the PIO.
    s := q.Size()

    // invert the PIO.
    for x := 0; x < s.X; x++ {
        for y := 0; y < s.Y; y++ {
            // fetch the value of a pixel from the POI.
            r, g, b, a := p.At(x, y).RGBA()

            // set the value of an inverted pixel to the NIO.
            // Note: byte is an alias for uint8 in Golang.
            n.Set(x, y, color.RGBA{uint8(255-r), uint8(255-g), uint8(255-b), uint8(a)})
        }
    }

    // create an output file.
    o, _ := os.Create("out.png")

    // output a png image from the NIO.
    png.Encode(o, n)
}

```

# Answer
> 0 votes
# Python 2 \+ OpenCV, 55 bytes

```
import cv2
cv2.imwrite('a.png',255-cv2.imread(input()))

```

The OpenCV library uses NumPy arrays to read, process, and write images. Below is an example of this script inverting an image found on mozilla.org.

All channels, including the alpha channel, will be inverted. This is problematic for images that have transparency. But as @Mego pointed out, support for the alpha channel is optional.

Below is an 82 byte commented version that property handles the alpha channel.

```
import cv2                # import OpenCV library
i=cv2.imread(input(),-1)  # image file name is specified from stdin
                          # read with the IMREAD_UNCHANGED option
                          # to preserve transparency
i[:,:,:3]=255-i[:,:,:3]   # invert R,G,B channels
cv2.imwrite('a.png',i)    # output to a file named a.png

```

As shown below, this properly handles inverting the Firefox logo while preserving the transparent background.

---
Tags: code-golf, graphical-output, image-processing
---