# Question
Title: Digital River (Shortest And Fastest Solution)
This is my first question, so I hope it goes well.

## Background:

It's not the rivers that you might be thinking about. The question revolves around the concept of digital rivers. A digital river is a sequence of numbers where the number following `n` is `n` plus the sum of its digits.

**Explanation:**

12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives 12360. similarly 145 is followed by 155. If the first number of a digital river is `M` we will call it river `M`.

For e.g: River 480 is the sequence beginning {480,492,507,519....}, and river 483 is the sequence beginning {483,498,519,....}. Normal streams and rivers can meet, and the same is true for digital rivers. This happens when two digital rivers share some of the same values.

**Example:**

River 480 meets river 483 at 519. River 480 meets river 507 at 507 and never meets river 481. Every digital river will eventually meet river 1, river 3 or river 9.

Write a program that can determine for a given integer `n` the value where river `n` first meets one of these three rivers.

## Input

The input may contain multiple test cases. Each test case occupies a separate line and contains an integer `n` (`1 <= n <= 16384`). A test case with value of `0` for `n` terminates the input and this test case must not be processed.

## Output

For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then on a separate line output the line "first meets river x at y". Here y is the lowest value where river `n` first meets river `x` (x = 1 or 3 or 9). If river `n` meets river `x` at `y` for more than one value of `x`, output the lowest value. Print a blank line between two consecutive test cases.

## Test case

**Input:**

```
86
12345
0

```

**Output:**

```
Case #1

first meets river 1 at 101

Case #2

first meets river 3 at 12423

```

## Scoring:

The fastest algorithm wins. In case of tie. The one with shorter code will win.

Thanks to **mbomb007** for pointing out my error.

p.s: I want to have the fastest solution rather than the smallest one. I also have a solution of mine which is slow. For that look here.

## Note:

I will be using this for code testing. And performance checking.

# Answer
# C, 320 ~~294~~ bytes

Compile with -std=c99

```
#include<stdio.h>
int s(int i){for(int j=i;j;j/=10)i+=j%10;return i;}int main(){int c=0,i;while(scanf("%d",&i)){c++;if(!i)continue;int j,o[]={1,3,9},p[]={1,3,9};Q:for(j=0;j<3;j++){if(o[j]==i)goto D;else if(o[j]<i){o[j]=s(o[j]);goto Q;}}i=s(i);goto Q;D:printf("Case #%d\n\nfirst meets river %d at %d\n\n",c,p[j],o[j]);}}

```

Ungolfed:

```
#include <stdio.h>

int s(int i)
{
    for(int j = i; j; j /= 10)
        i += j % 10;
    return i;
}

int main()
{
    int c = 0, i;
    while(scanf("%d", &i))
    {
        c++;
        if(!i)
            continue;
        int j,o[]={1,3,9},p[]={1,3,9};
        Q: for(j = 0; j < 3; j++)
        {
            if(o[j] == i)
                goto D;
            else if(o[j] < i)
            {
                o[j] = s(o[j]);
                goto Q;
            }
        }
        i = s(i);
        goto Q;
        D: printf("Case #%d\n\nfirst meets river %d at %d\n\n", c, p[j], o[j]);
    }
}

```

Try it out!

Essentially, the "target" rivers are increased until they're greater than the river we're testing against, and afterwards the test river is increased. This is repeated until the test river is equal to some other river.

~~I'm not reading parameters from the command line in this program, and I'm not sure if you're supposed to.~~ Now you can pass parameters to STDIN. You can terminate by passing a non-numeric input.

Also darn, beaten by half an hour.
> 3 votes

# Answer
# JavaScript (ES6)

This is a quite fast answer using a quite slow language. Really, executing time should not be a problem using any language with hash tables. All my tests under 100 ms.

Anonymous method with the list of test case as input parameter.

```
F=cases=>{
  var t0 = +new Date
  var result = 0
  var spots = []
  var top=[,1,3,,9]
  var rivers=[,1,3,1,9,1,3,1]
  cases.forEach((n,i)=>{
    var found = result = spots[n]
    for (;!found;)
    {
      found = top.some((v,i)=>{
        for(;spots[v] |= i, v<n; top[i] = v)
          [...v+''].forEach(d=>v-=-d)
        return result = v-n ? 0 : i;
      }) || (
        [...n+''].forEach(d=>n-=-d),
        result = spots[n]
      )
    }
    console.log(`Case #${i+1}\nfirst meets river ${rivers[result]} at ${n}`)
  })
  return 'Time (ms) ' + (new Date-t0)
}

console.log(F([86, 12345, 123, 456, 789, 16384]))
```
> 3 votes

# Answer
# Java 7, ~~519~~ 505 bytes

```
import java.util.*;String c(int i){if(i<=0)return"";ArrayList<Long>r=f(1),s=f(3),t=f(9),x=f(i);String z="first meets river ";for(int j=0;j<r.size();j++){long u=r.get(j),v=s.get(j),w=t.get(j);if(x.contains(u))return z+1+" at "+u;if(x.contains(v))return z+3+" at "+v;if(x.contains(w))return z+9+" at "+w;}return"";}ArrayList f(long i){ArrayList<Long>l=new ArrayList();l.add(i);for(long j=0,x;j<9e4;j++){x=l.get(l.size()-1);for(char c:(x+"").toCharArray())x+=new Long(c+"");l.add(x);if(x>16383)return l;}return l;}

```

Yes, it's long, ugly and can without a doubt be completely changed to code-golf it more.. I'm both distracted and tired, so perhaps I should just delete it again..
It was a pretty hard challenge to be honest.. But at least you have your first answer.. ;) (Which might even be longer than your original ungolfed C++ program.. xD)

**Ungolfed & test cases:**

Try it here.

```
import java.util.*;
class M{
  static String c(int i){
    if(i <= 0){
      return "";
    }
    ArrayList<Long> r = f(1),
                    s = f(3),
                    t = f(9),
                    x = f(i);
    String z = "first meets river ",
           y = " at ";
    for(int j = 0; j < r.size(); j++){
      long u = r.get(j),
           v = s.get(j),
           w = t.get(j);
      if(x.contains(u)){
        return z+1+y+u;
      }
      if(x.contains(v)){
        return z+3+y+v;
      }
      if(x.contains(w)){
        return z+9+y+w;
      }
    }
    return "";
  }

  static ArrayList f(long i){
    ArrayList<Long> l = new ArrayList();
    l.add(i);
    for(long j = 0, x; j < 9e4; j++){
      x = l.get(l.size() - 1);
      for(char c : (x + "").toCharArray()){
        x += new Long(c+"");
      }
      l.add(x);
      if(x > 16383){
        return l;
      }
    }
    return l;
  }

  public static void main(String[] a){
    System.out.println(c(86));
    System.out.println(c(12345));
    System.out.println(c(0));
  }
}

```

**Output:**

```
first meets river 1 at 101
first meets river 3 at 12423
(empty output)

```
> 1 votes

# Answer
# Scala, 774 bytes

Fiddle: http://scalafiddle.net/console/4ec96ef90786e0f2d9f7b61b5ab0209b

I don't feel like golfing it. It finds a solution to the posed problem within 50ms

Usage may not be exactly what you want:

`scala river.scala`

Now you can continuously input numbers followed by an enter. And terminate the program with 0. The result will be printed as soon as you hit enter.

```
io.Source.stdin.getLines.map(_.toInt)
  .takeWhile(_ != 0)
  .map(stream(_).takeWhile(_ < 16383))
  .zipWithIndex
  .map { cur =>
    Seq(1, 3, 9).map { i =>
      val s = stream(i).takeWhile(_ < 16383)
      (cur._2+1, i, s.intersect(cur._1).headOption)
    }
  }.foreach { opts =>
    val options = opts.filterNot(_._3.isEmpty)

    if(options.isEmpty) {
      println("No result")
    } else {
      val opt = options(0)
      println(s"Case #${opt._1}\n\nfirst meets ${opt._2} at ${opt._3.get}\n\n")
    }
  }

def stream(i:Int): Stream[Int] = {
  def sub: Int => Stream[Int] = {
    i => i #:: sub(a(i))
  }
  sub(i)
}

def a(i:Int): Int = i + i.toString.map{_.asDigit}.sum

```
> 1 votes

# Answer
## C, 228 ~~283~~ ~~300~~ bytes

This is a mod of Yakov's code to take advantage of the river patterns. This makes it ~3x faster. Also, unsigned integers avoid the `cltod` penalty on 64-bit machines, so it's a few bytes longer but fractionally faster.

```
#define sum(z) for(y=z;y;y/=10)z+=y%10;
n,x;main(){unsigned i,j,y;while(scanf("%d",&i)){if(i){j=x=1+!(i%3)*2+!(i%9)*6;do{while(j<i)sum(j)}while(j^i&&({sum(i)i;}));printf("Case #%u\n\nfirst meets river %u at %u\n\n",++n,x,i);}}}

```

Ungolfed:

```
#define sum(z) for(y=z;y;y/=10)z+=y%10;
n, x;
main() {
    unsigned i, j, y;
    while(scanf("%d", &i)) {
        if(i){
            j = x = 1 + !(i%3)*2 + !(i%9)*6;
            do{
                while (j < i) sum(j)
            }
            while(j^i&&({sum(i)i;}));
            printf("Case #%u\n\nfirst meets river %u at %u\n\n", ++n, x, i);
        }
    }
}

```

**Explanation:**

```
j = x = 1 + !(i%3)*2 + !(i%9)*6;

```

This selects the correct river. River 1 meets every other river, so we use this as the fall-back case. If 3 is the greatest common divisor of the test river, we select river 3 (`1 + !(i%3)*2`). If 9 is the greatest common divisor of the test river, we override the previous values and select river 9.

Why does this work? River 9 goes 9, 18, 27, 36, etc. This steps by a multiple of 9 each time thus it will always be the shortest route to a sister river. River 3 will step by a multiple of 3 each time: 3, 6, 12, 15, 21, etc. While rivers that are a multiple of 9 are *also* a multiple of 3, we choose them as river 9 first, leaving only the multiples of 3. The remainder will meet river 1 first: 1, 2, 4, 8, 16, 23, 28, etc.

Once we have selected our correct river, we step the two rivers until they meet.
> 1 votes

# Answer
# Python 3, 144 bytes

```
r,a,b,c,i={int(input())},{1},{3},{9},1
while i:
  for x in r,a,b,c:t=max(x);x|={sum(int(c)for c in str(t))+t}
  if r&(a|b|c):i=print(*r&(a|b|c))

```
> 1 votes

# Answer
# C

Very simple, it just looks that long because I unrolled all the 3 rivers. It first generates the 3 rivers up to `RIVER_LENGTH` (which I hope is big enough), and then for each step on `N` it does a binary search on all three streams to see if it is in any of them. This works because the streams are already sorted, so we can do the contains check in `log(n)` time.

```
#include <stdio.h>

#define RIVER_LENGTH 10000

int main() {
    int num_cases;
    scanf("%d", &num_cases);
    int cases[num_cases];
    int N;
    int s1[RIVER_LENGTH] = {1};
    int s3[RIVER_LENGTH] = {3};
    int s9[RIVER_LENGTH] = {9};
    int i;
    int temp;

    for (i = 1; i < RIVER_LENGTH; i++) {
        s1[i] = temp = s1[i-1];
        while (temp) {
            s1[i] += temp % 10;
            temp /= 10;
        }
    }

    for (i = 1; i < RIVER_LENGTH; i++) {
        s3[i] = temp = s3[i-1];
        while (temp) {
            s3[i] += temp % 10;
            temp /= 10;
        }
    }

    for (i = 1; i < RIVER_LENGTH; i++) {
        s9[i] = temp = s9[i-1];
        while (temp) {
            s9[i] += temp % 10;
            temp /= 10;
        }
    }

    int start;
    int end;
    int pivot;

    for (i=1; i <= num_cases; i++) {
        scanf("%d", &cases[i]);
    }

    for (i=1; i <= num_cases; i++) {
        printf("Case #%d\n\n", i);
        N = cases[i];

        while (1) {

            temp = N;
            while (temp) {
                N += temp % 10;
                temp /= 10;
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s1[pivot] == N) {
                    printf("first meets river 1 at %d\n\n", N);
                    goto case_done;
                } else if (N < s1[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s3[pivot] == N) {
                    printf("first meets river 3 at %d\n\n", N);
                    goto case_done;
                } else if (N < s3[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }

            start = 0;
            end = RIVER_LENGTH;
            pivot = 1;

            while (end != start && pivot != RIVER_LENGTH - 1) {
                pivot = start + ((end - start) >> 1);
                if (s9[pivot] == N) {
                    printf("first meets river 9 at %d\n\n", N);
                    goto case_done;
                } else if (N < s9[pivot]){
                    end = pivot;
                } else {
                    start = pivot+1;
                }
            }
        }

        case_done:;

    }
}

```

It takes a number for the number of cases first, instead of using `0` to delimit the end of the inputs, because you know, C. This is just for convenience and doesn't really affect anything, so I hope its okay.
> 0 votes

---
Tags: code-golf, sequence, fastest-algorithm
---


title: Order of Mia Sets

text:
# Question
Title: Order of Mia Sets
The dice game Mia introduces a very non-trivial order of sets of size two:

```
{3,1} < {3,2} < {4,1} < {4,2} < {4,3} < {5,1} < {5,4} < {6,1} < {6,5} < {1,1} < {2,2} < {6,6} < {1,2}

```

In general, the order within a tuple does not matter `{x,y}={y,x}`, `{1,2}` is greater than anything else, Pairs are greater than non-pairs and the numeric value decides in case of a tie.

Now suppose you want to use `n` dice. Also, the dices have `m` faces.

Example:

* `{1,5,3,4} < {1,2,6,3}` since 5431 \< 6321
* `{1,2,3,5} < {1,1,5,6} < {1,1,5,5}, {1,1,6,6} < {1,1,1,3} < {2,2,2,3} < {1,1,1,1} < {1,2,3,4}`
* **`{2,2,5} < {1,1,6}`** since both sets have each one pair and 611 \> 522

In a nutshell, `{1, ..., n}` is greater than anything else. Let `p > q`, then p-of-a-kind is greater than q-of-a-kind. In case of a tie, the second(, third, ...)-longest of-a-kind wins. Finally, if no decision could be made yet, the greatest numerical value wins. The numerical value of a set is the largest integer you can build from the available numbers in the set, using concatenation. Example:

* `{2,5,4,3}` becomes 5432
* `{4,11,3,4}` becomes B443 (\>6-faced dice are allowed, B=11)

Your task is to write the smallest possible program (i.e. function) in the language of your choice, that, given two containers (list, array, set, ...) returns whether the first or the second one wins.

Note: you can assume that the two containers have the same length and contain only positive integers, but nothing else. Especially they may be not sorted. The return value could be anything, e.g. {-1, 0, 1} for {first wins, tie, second wins}.

# Answer
# Jelly, 16 bytes

```
ṢŒrUṢṚZ
Ṣ⁼J;ÇµÐṀ

```

Takes a list of lists each of which represents a roll (so can be more than two if wanted) and returns a list of the winner(s).

**Try it online!** ...alternatively here is a version which sorts the rolls from weakest to strongest instead.

### How?

```
Ṣ⁼J;ÇµÐṀ - Main link: list of list of dice rolls, L
     µÐṀ - filter keep maximal (i.e. sort L by the previous link as a key and keep maximums)
         -                                            e.g. [5,3,1,3]
Ṣ        -     sort roll                                   [1,3,3,5]
  J      -     range(length(roll))                         [1,2,3,4]
 ⁼       -     equal? [1,2,3,...n] beats everything        0
    Ç    -     call last link as a monad with input roll   [[2,1,1],[3,5,1]]
   ;     -     concatenate                                 [0,[2,1,1],[3,5,1]]

ṢŒrUṢṚZ - Link 1, rest of sort key: dice rolls        e.g. [5,3,1,3]
Ṣ       - sort the roll                                    [1,3,3,5]
 Œr     - run length encode                                [[1,1],[3,2],[5,1]]
   U    - upend (reverse each)                             [[1,1],[2,3],[1,5]]
    Ṣ   - sort                                             [[1,1],[1,5],[2,3]]
     Ṛ  - reverse                                          [[2,3],[1,5],[1,1]]
      Z - transpose                                        [[2,1,1],[3,5,1]]
        -     ...this is a list of: 1) the group sizes descending; and
                 2) the face values of each group, descending across equal group sizes

```
> 2 votes

# Answer
## JavaScript (ES6), 162 bytes

```
(a,b,g=a=>a.map(n=>e[n]=e[n]+1||1,e=[1])&&[[...e].every(n=>n==1),...e.filter(i=x=>x).sort(h=(a,b)=>b-a),...a.sort(h)],c=g(a),d=g(b))=>d.map((n,i)=>n-c[i]).find(i)

```

Explanation: Takes two arrays as parameters. `g` converts each array into a list of counts. The list is then checked to see whether it corresponds to a set `1..n`. The counts are sorted and the sorted values are concatenated. The two results are then compared. The return value is a positive integer if the second array wins and a negative integer if the first array wins, otherwise the falsy JavaScript value `undefined` is returned.
> 2 votes

# Answer
# Julia (489 Bytes)

```
function a(x,y)l=length;g=collect;s=sort;m=maximum;r=repmat;function b(z)w=sum(r(z,1,m(z)).==r(g(1:m(z))',l(z),1),1);u=zeros(m(w));map(i->if i>0 u[i]+=1;end,w);return u end;function c(x,y)if l(x)>l(y)return-1 elseif l(x)<l(y)return 1 else for i=l(x):-1:1 if x[i]>y[i] return-1 elseif x[i]<y[i] return 1 end end;return 0;end end;x=s(x);y=s(y);if x==y return 0;elseif x==g(1:l(x));return-1 elseif y==g(1:l(y))return 1 else d=c(b(x),b(y));if d==0 return c(x,y);else return d;end end end

```

Readable:

```
  1 function a(ds1, ds2)
  2     function countNOfAKind(ds)
  3         # return array. n-th value is number of occurences of n-of-a-kind.
  4         # e.g. findNOfAKind([1, 1, 1, 2, 2, 3, 3]) == [0, 2, 1]
  5         ps = sum(repmat(ds, 1, maximum(ds)) .== repmat(collect(1:maximum(ds))', length(ds), 1), 1);
  6         ls = zeros(maximum(ps));
  7         map(i -> if i>0 ls[i] += 1 end, ps);
  8         return ls
  9     end
 10
 11     function cmpLex(ds1, ds2)
 12         # compare ds1, ds2 reverse-lexicographically, i.e. compare last distinct value.
 13         if length(ds1) > length(ds2)
 14             return -1
 15         elseif length(ds1) < length(ds2)
 16             return 1
 17         else
 18             for i = length(ds1):-1:1
 19                 if ds1[i] > ds2[i]
 20                     return -1
 21                 elseif ds1[i] < ds2[i]
 22                     return 1
 23                 end
 24             end
 25             return 0;
 26         end
 27     end
 28
 29     ds1=sort(ds1);
 30     ds2=sort(ds2);
 31     if ds1 == ds2
 32         return 0;
 33     elseif ds1 == collect(1:length(ds1))
 34         return -1
 35     elseif ds2 == collect(1:length(ds2))
 36         return 1
 37     else
 38         d = cmpLex(countNOfAKind(ds1), countNOfAKind(ds2))
 39         if d == 0
 40             return cmpLex(ds1, ds2);
 41         else
 42             return d;
 43         end
 44     end
 45 end

```
> 0 votes

# Answer
# PHP 333 Bytes

I assume that there are fewer dices then faces for the highest value as street beginning with 1

I make a little more. Input is an array with more then two values. Output is the sorted array.

```
<? $m=$_GET[m];foreach($m as$k=>$v){rsort($v);$m[$k]=$v;}function t($a,$b){if($a==$r=range($x=count($a),1))return 1;elseif($b==$r)return-1;$c=array_pad(array_values(array_count_values($a)),$x,0);$d=array_pad(array_values(array_count_values($b)),$x,0);rsort($c);rsort($d);if($e=$c<=>$d)return$e;return$a<=>$b;}usort($m,t);print_r($m);

```

## Breakdown

```
$m=$_GET["m"]; # Array as Input
foreach($m as$k=>$v){
    rsort($v); # reverse sort of an item
    $m[$k]=$v; # replace the sort item
}
function t($a,$b){ #sorting algorithm
    if($a==$r=range($x=count($a),1))return 1; # $a is highest value
    elseif($b==$r)return-1; # $b is highest value
    $c=array_pad(array_values(array_count_values($a)),$x,0);
# prepare check multiple values for fist value
    $d=array_pad(array_values(array_count_values($b)),$x,0);
# prepare check multiple values for second value
    rsort($c);
    rsort($d);
    if($e=$c<=>$d)return$e; # compare first and second multiples
    return$a<=>$b; # compare dices
}
usort($m,"t"); # start sort
print_r($m); #print sorted array from low to high

```
> 0 votes

---
Tags: code-golf, sequence
---


title: Anagram Quines (Robbers' Thread)

text:
# Question
Title: Anagram Quines (Robbers' Thread)
*This is a challenge the Cops' Thread can be found here*

Your challenge, as robbers is to take outputs from the cops' thread and find anagrams of the output that when run as a program output the original output provided.

The winner will be the person with the most valid cracks on this question.

## Rules

* You may not crack answers marked as safe with a provided program.
* If a cop provides a language that the intended solution is in you must crack it in that particular language, if they choose not to you may crack it in any competing language.
* Standard rules for Quines apply.
* Cracks must not be perfect Quines. i.e. they must not output their exact source but a reordering of it (the order is provided by the cop).

# Answer
# Unspecified language (CJam), 254 bytes, DJMcMayhem

```
0000000: 3235 362c 583e 3130 2d5b 445d 2f41 612a  256,X>10-[D]/Aa*
0000010: 3a63 6523 0102 0304 0506 0708 090b 0c0e  :ce#............
0000020: 0f10 1112 1314 1516 1718 191a 1b1c 1d1e  ................
0000030: 1f20 2122 2425 2627 2829 2b2e 3334 3738  . !"$%&'()+.3478
0000040: 393b 3c3d 3f40 4243 4546 4748 494a 4b4c  9;<=?@BCEFGHIJKL
0000050: 4d4e 4f50 5152 5354 5556 5759 5a5c 5e5f  MNOPQRSTUVWYZ\^_
0000060: 6062 6466 6768 696a 6b6c 6d6e 6f70 7172  `bdfghijklmnopqr
0000070: 7374 7576 7778 797a 7b7c 7d7e 7f80 8182  stuvwxyz{|}~....
0000080: 8384 8586 8788 898a 8b8c 8d8e 8f90 9192  ................
0000090: 9394 9596 9798 999a 9b9c 9d9e 9fa0 a1a2  ................
00000a0: a3a4 a5a6 a7a8 a9aa abac adae afb0 b1b2  ................
00000b0: b3b4 b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2  ................
00000c0: c3c4 c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2  ................
00000d0: d3d4 d5d6 d7d8 d9da dbdc ddde dfe0 e1e2  ................
00000e0: e3e4 e5e6 e7e8 e9ea ebec edee eff0 f1f2  ................
00000f0: f3f4 f5f6 f7f8 f9fa fbfc fdfe ff0a       ..............

```

Try it online!

### How it works

```
256,                Push the range [0 ... 255].
    X>              Remove the first item (0).
      10-           Remove 10 (0x0a).
         [D]/       Split at occurrences of 13 (0x0d).
             Aa*    Join, separating by 10 (0x0a).
                :c  Cast all integers to character.
                e#  Begins a comment, terminated by the linefeed at the very end.

```
> 5 votes

# Answer
# Brain-Flak, Riley

```
()((((((()()()){}){}){})()){}{}){({}[()][((((((()()()()()){}){}){})()))]{})}{}((()()()){}()){({}[()][((((((()()()){}){}()){({}[()])}{})()()))]{})}{}((((()()()()){}){}()){}){({}[()][((((((((()()()()()){}){}){}())){}{})()()))]{})}{}

```

Try it online!

# Explanation

This was a bit easier than I had expected.

I wrote 3 separate loops to print each type of brace:

```
(((((()()()){}){}){})()){}{}){({}[()][((((((()()()()()){}){}){})()))]{})}{}
((()()()){}()){({}[()][((((((()()()){}){}()){({}[()])}{})()()))]{})}{}
((((()()()()){}){}()){}){({}[()][((((((((()()()()()){}){}){}())){}{})()()))]{})}{}

```

I used standard Mini-Flak technique to avoid using `<...>` monad and to be honest I never really felt the need to use the `<>` nilad.

This must have been extremely similar to what Riley did in the first place because when I was done I had an extra `()` left over. This is not a problem because `()` is essentially a no-op at the top level so I stuck it at the front of my program.
> 5 votes

# Answer
## Haskell, 107 bytes, Laikoni

```
main=print$id=<<['|':[d]>>[d|i<-"$$'''',--..:<<<<====>>[[[[]]]]addddddiiiiiimnnprt|||",i==d]|d<-id['$'..]]

```

Plus a trailing newline.

Try it online! (needs a few seconds to run, because it loops through all unicode characters).

The program has an `id` (right before `['$'..]`) which is not needed for the program logic, but somehow I have to spend the `i` and `d`.
> 4 votes

# Answer
# Python, 96 bytes, Agargara

```
f= 'B7ofx)wdr0o{1{6{{r){1x0sD00qF1{{24}wr2wlo)y))xm2'; print''.join([r+chr(ord(r)-9)for r in f])

```

Try it online!

Once I noticed that some characters repeated in pairs, it was just a matter of finding a suitable ascii map between characters.
> 4 votes

# Answer
# Pyth, 32 bytes, Rod

```
J+"J+J=JJ 1-2#pTN%"N #%2J=T-1pJJ

```

Try it online!

I don't really know Pyth that well, but I started with printing the required output and went from there.

```
 +"J+J=JJ 1-2#pTN%"N             # Add a '"' to the string in quotes
J                                # Assign result of above step to J
                     #           # Start an infinite loop
                      %2J=T-1    # Loops one iteration, then breaks
                                 # (I have no idea why this works)
                             pJ  # Explicitly print J
                               J # Implicitly print J

```
> 3 votes

# Answer
# CJam, 46 bytes, Business Cat

```
93]_:c58]99]95]93]e__:c36]95]95]101]101]e_$_:c

```

Try it online!

```
93]                                             # Push [93] onto the stack
   _                                            # Copy
    :c                                          # Push ascii char 93 ']'
      58 99 95 93                               # Push these numbers...
        ]  ]  ]  ]                              # Push entire stack as array
                  e__                           # Flatten and copy
                     :c                         # Map ascii values to all elements
                       36]95]95]101]101]        # Same as above
                                        e_      # Flatten
                                          $     # Sort
                                           _    # Copy, implicitly print
                                            :c  # Map ascii values to all elements
                                                # Implicitly print

```
> 2 votes

# Answer
# Octave, 91 bytes, drolex

```
a=['111111111123666667eeegggkkknnszEEGn};:;:'];
disp(['a=[''',a,'''];',10,[a-10,']);']]);dd

```

Try it online!

Very similar to the python solution in that it abuses ascii values to print the characters it needs.
> 2 votes

---
Tags: code-golf, quine, cops-and-robbers, permutations
---


title: Convert λ-expressions to SK-expressions

text:
# Question
Title: Convert λ-expressions to SK-expressions
The λ-calculus, or lambda calculus, is a logical system based on anonymous functions. For example, this a λ-expression:

```
λf.(λx.xx)(λx.f(xx))

```

However, for the purposes of this challenge, we'll simplify the notation:

* Change `λ` to `\` (to make it easier to type): `\f.(\x.xx)(\x.f(xx))`
* The `.` in lambda headers is unnecessary, so we can drop it: `\f(\xxx)(\xf(xx))`
* Use the Unlambda-style prefix notation with ``` for application rather than writing the two functions together (for a full explanation of how to do this, see Convert between Lambda Calculus Notations): `\f`\x`xx\x`f`xx`
* This is the most complicated substitution. Replace each variable with a number in brackets based on how deeply nested the variable is relative to the lambda header it belongs to (i.e. use 0-based De Bruijn indexing). For example, in `\xx` (the identity function), the `x` in the body would be replaced with `[0]`, because it belongs to the first (0-based) header encountered when traversing the expression from the variable to the end; `\x\y``\x`xxxy` would be converted into `\x\y``\x`[0][0][1][0]`. We can now drop the variables in the headers, leaving `\\``\`[0][0][1][0]`.

Combinatory logic is basically a Turing Tarpit made out of the λ-calculus (Well, actually, it came first, but that's irrelevant here.)

"Combinatory logic can be viewed as a variant of the lambda calculus, in which lambda expressions (representing functional abstraction) are replaced by a limited set of combinators, primitive functions from which bound variables are absent."<sup>1</sup>

The most common type of combinatory logic is the SK combinator calculus, which uses the following primitives:

```
K = λx.λy.x
S = λx.λy.λz.xz(yz)

```

Sometimes a combinator `I = λx.x` is added, but it is redundant, as `SKK` (or indeed `SKx` for any `x`) is equivalent to `I`.

All you need is K, S, and application to be able to encode any expression in the λ-calculus. As an example, here's a translation from the function `λf.(λx.xx)(λx.f(xx))` to combinatory logic:

```
λf.(λx.xx)(λx.f(xx)) = S(K(λx.xx))(λf.λx.f(xx))
λx.f(xx) = S(Kf)(S(SKK)(SKK))
λf.λx.f(xx) = λf.S(Kf)(S(SKK)(SKK))
λf.S(Sf)(S(SKK)(SKK)) = S(λf.S(Sf))(K(S(SKK)(SKK)))
λf.S(Sf) = S(KS)S
λf.λx.f(xx) = S(S(KS)S)(K(S(SKK)(SKK)))
λx.xx = S(SKK)(SKK)
λf.(λx.xx)(λx.f(xx)) = S(K(S(SKK)(SKK)))(S(S(KS)S)(K(S(SKK)(SKK))))

```

Since we are using the prefix notation, this is ````S`K``S``SKK``SKK``S``S`KSS`K``SKK``.

1 Source: Wikipedia

## The Challenge

By now, you've probably guessed what is: Write a program that takes a valid λ-expression (in the notation described above) as input and outputs (or returns) the same function, rewritten in SK-combinator calculus. Note that there are an infinite number of ways to rewrite this; you only need to output one of the infinite ways.

This is , so the shortest valid submission (measured in bytes) wins.

## Test Cases

Each test case shows one possible output. The expression on top is the equivalent λ-calculus expression.

λx.x:
\[0]                        -> ``SKK
λx.xx:
\`[0][0]                    -> ```SKK``SKK
λx.λy.y:
\\[0]                       -> `SK
λx.λy.x:
\\[1]                       -> K
λx.λy.λz.xz(yz):
\\\``[2][0]`[1][0]          -> S
λw.w(λx.λy.λz.xz(yz))(λx.λy.x):
\``[0]\\[1]\\\``[2][0]`[1][0] -> ``S``SI`KS`KK
</code></pre>

# Answer
> 9 votes
## Haskell, ~~251 237 222~~ 214 bytes

15 bytes saved thanks to @Ørjan\_Johansen (also see his TIO links in the remarks)!

8 more bytes saved thanks to @nimi!

```
data E=S|K|E:>E|V Int
p(h:s)|h>'_',(u,a)<-p s,(v,b)<-p u=(v,a:>b)|h>'['=a<$>p s|[(n,_:t)]<-reads s=(t,V n)
a(e:>f)=S:>a e:>a f
a(V 0)=S:>K:>K
a(V n)=K:>V(n-1)
a x=K:>x
o(e:>f)='`':o e++o f
o S="S"
o K="K"
f=o.snd.p

```

`p` parses the input, returning the remaining unparsed part in the first component of the resulting pair. The first character of its argument must be a backtick, a backslash or an opening bracket. The pattern guards of `p` check these cases in this order. In the first case, denoting an application, two more expressions are parsed and combined to an element of the `E` data type with the infix constructor `:>`. In the lambda case, the following expression is parsed and immediately given to the `a` function. Otherwise it is a variable, we get its number with the `reads` function (which returns a list) and drop the closing bracket by pattern matching with `(_:t)`.

The `a` function does the quite well known bracket abstraction. To abstract an application, we abstract the two subexpressions and use the `S` combinator to distribute the argument to both. This is always correct, but with more code we could do much better by handling special cases in order to get shorter expressions. Abstracting the current variable gives `I` or, when we don't have that, `SKK`. Usually the remaining cases can just add a `K` to the front, but when using this notation we have to renumber the variables as the inner lambda is abstracted.

`o` turns the result to a string for output. `f` is the complete function.

As in many languages, backslash is an escape character, so it has to be given twice in a string literal:

```
*Main> f "\\[0]"
"``SKK"
*Main> f "\\`[0][0]"
"``S``SKK``SKK"
*Main> f "\\\\[0]"
"``S``S`KS`KK`KK"
*Main> f "\\\\[1]"
"``S`KK``SKK"
*Main> f "\\\\\\``[2][0]`[1][0]"
"``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S`KK`KK``S`KK``SKK``S``S`KS``S``S`KS``S`KK`KS``S`KK`KK``S`KK`KK``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S`KK`KK``S``S`KS`KK`KK``S``S`KS``S``S`KS``S`KK`KS``S`KK`KK``S`KK`KK"

```

---
Tags: code-golf, string, functional-programming, lambda-calculus, combinatory-logic
---


title: Generate an ASCII Padovan Spiral

text:
# Question
Title: Generate an ASCII Padovan Spiral
This is the ASCII version of this challenge. The initial post was separated per request by Martin Ender

## Introduction

Similar to the Fibonacci Sequence, the Padovan Sequence (OEIS A000931) is a sequence of numbers that is produced by adding previous terms in the sequence. The initial values are defined as:

```
P(0) = P(1) = P(2) = 1

```

The 0th, 1st, and 2nd terms are all 1. The recurrence relation is stated below:

```
P(n) = P(n - 2) + P(n - 3)

```

Thus, it yields the following sequence:

```
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, 351, ...

```

Using these numbers as side lengths of equilateral triangles yields a nice spiral when you place them all together, much like the Fibonacci Spiral:

Image courtesy of Wikipedia

---

## Task

Your task is to write a program that recreates this spiral by ASCII art, with input corresponding to which term. Since a triangle of side length 1 (1 character) is impossible to represent nicely in ASCII, the side lengths have been dilated by a factor of 2. Thus, the triangle of side length 1 is actually represented like so:

```
 /\
/__\

```

So, for example, if the input was 5 (the 5th term), the output should be:

```
   /\
  /  \
 /    \
/______\
\      /\
 \    /__\
  \  /\  /
   \/__\/

```

The first 5 terms were 1, 1, 1, 2, 2, so the triangle had side lengths 2, 2, 2, 4, 4 due to dilation. Another example for input 8:

```
     __________
   /\          /\
  /  \        /  \
 /    \      /    \
/______\    /      \
\      /\  /        \
 \    /__\/          \
  \  /\  /            \
   \/__\/______________\
    \                  /
     \                /
      \              /
       \            /
        \          /
         \        /
          \      /
           \    /
            \  /
             \/

```

## Rules

* You must print the result, and input must be an integer corresponding to term number
* Trailing and leading newlines are allowed, trailing spaces after lines are allowed also
* Your submission must be able to handle at least up to the 10th term (9)
* Your submission must be a full program or function that takes input and prints the result
* Rotations of the output are allowed, in 60 degree multiples, but the size of the triangles must remain the same, along with the representation
* Going counter-clockwise is also allowed
* Standard loopholes are forbidden

You may assume that input will be \>0 and that correct format of input will be given.

## Scoring

This is , so the shortest code in bytes wins. Happy New Years everyone!

# Answer
# Befunge, ~~871~~ ~~836~~ 798 bytes

```
&00p45*:10p20p030p240p050p060p9010gp9110gp1910gp1-91+10gpv
<v-g03+g06*2g041g055_v#!:%6:p06p05+p04g05g06:g04<p*54+292<
->10g:1\g3+:70p110gv >:5- #v_550g:01-\2*40g+1-30g
/\110:\-g03:\1:g055 _v#!-4:<vp01:-1g01-g03-1\-
^1<v07+1:g07< p08p < >:1-#v_550g:01-\40g+60g+1-30g-50g>v
 _0>p80gp:5-|v1\+66\:p\0\9:$<:p02:+1g02-g03+g06-\g04\1:<
0v|-g00:+1$$<>\p907^>p:!7v>3-#v_550g:30g+:30p1\0\-
1>10g+::0\g3-:70p\0^^07<v<>50#<g::30g+:30p-1-01-\
v >\$0gg> :1+10gg1- #v_^>0g10gg*+\:!2*-70g2+10gv>:#->#,"_"$#1_:1#<p
+1+g03$_^#`gg011+3:+3<g07\+*2+*`0:-\gg01+5g07:g<>1#,-#*:#8>#4_$#:^#
>55+,p30g40p10gg10g1>#v_
#v:#p0$#8_:$#<g!#@_0^ >
 >>:180gg`>>#|_:2+80gg:!v
3+^g\0p08:<vgg08+2::+3<$_100p1-v>g,\80gg+\80gp:2+90g:!01p\80gp
!#^_80g:1+^>\180gg`+!#^_20g80g`
5*g10!g09p04-1-\0\+g04:gg08:p09<^3`0:gg08+1:::$$_1#!-#\\:,#\<g

```

Try it online!

As is often the case with Befunge, the trick is coming up with an algorithm that allows us to render the pattern from top to bottom, since it's just not feasible to render it into memory first with the limited space available.

The way this works is by first building up a simple data structure representing the edges needed to draw the spiral. The second stage then parses that structure from top to bottom, rendering the edge fragments required for each line of output.

Using this technique, we can support up to n=15 in the reference implementation before we start having overflow issue in the 8-bit memory cells. Interpreters with a larger cell size should be able to support up to n=25 before running out of the memory.
> 15 votes

# Answer
# go, 768 bytes

```
func 卷(n int){
    数:=0
    p:=[]int{1,1,1}
    for i:=3;i<n;i++ {p=append(p,p[i-2]+p[i-3])}
    宽:=p[len(p)-1]*10+10
    素:=make([]int,宽*宽)
    for 数=range 素 {素[数]=32}
    for i:=0;i<数;i+=宽 {素[i]=10}
    态:=[]int{1,1,宽/2,宽/2,92}
    表:=[70]int{}
    s:="SRSQTSPQQ!QOQP~QQQQQQSQR~ORQR!OPOPTSQRQ$QPPQNQPPPXQQQQQQRRQXQRRRNOQPQ$"
    for i:=range s {表[i]=int(s[i])-33-48}
    表[49],表[59]=48,48
    for i:=0;i<4*n;i++ {
        梴:=p[i/4]*2
        if 态[1]==0 {梴=梴*2-2}
        for k:=0;k<梴;k++ {
            址:=(态[2]+态[3]*宽)%len(素)
            if 素[址]==32 {素[址]=态[4]}
            态[2]+=态[0]
            态[3]+=态[1]
        }
        数=((态[0]+1)*2+态[1]+1)*5
        if i%4>2 {数+=35}
        for k:=0;k<5;k++ {态[k]+=表[数+k]}
    }
    for i:=0;i<宽*宽;i++ {fmt.Printf("%c",rune(素[i]))}
}

```

This is of course not optimal, but it's not a bad start. I know it's probably a bit simple for the golfing standards, but it was fun and I hope it's not minded if I leave some notes to future self.

How it works

Basically I simulate a 'drawing turtle' like in LOGO on an ASCII pixel grid, but the turtle can only do these three commands:

```
rt   - right turn, turn 120 degrees right (1/3 of a Turn)
rth  - right turn half, turn  60 degrees right (1/6 of a Turn)
fd n - forward, go forward n steps, drawing a trail of _, /, or \

```

Now for each triangle, I go like this, where P is 2x the nth Padovan number:

```
fd P
rt
fd P
rt
fd P
rt
fd P
rth

```

The fourth 'fd' means I am re-tracing the first side of each triangle. This helps get back to a nice starting point for the next triangle. The half-right-turn makes sure that the next triangle will be in the proper orientation.

---

To golf the turtle I store 5 state variables in array 态 : x position, y position, x velocity, y velocity, and 'drawing rune'. At each animation frame, x+= x velocity, y += y velocity, and the rune is drawn.

Then I set up table 表 which tells how to actually perform the turn. The turn code is tricky because of the way ASCII art works. It is not a straightforward movement like on a pixel display. The direction of the turtle, determined by x and y velocity, determine the changes necessary to get the turn to look proper.

To turn, it looks at the current x and y velocity, and combines them into an index.

```
xv = x velocity, yv = y velocity.
i.e. a turtle facing down and to the right has
xv of 1, and yv of 1. It can only face 6
different directions. Formula is (xv+1)*2+yv+1

xv  yv    index
-1  -1    0
-1   0    1
-1   1    2
 1  -1    4
 1   0    5
 1   1    6

```

This index is used to lookup a set of 5 values in table 表. Those 5 values in table 表 are then added to each of the 5 variables in state 态. The turtle is then effectively turned, and ready for the next 'fd'.

For rth, half the right turn, there is a separate section of the 表 table. It is offset by 7\*5, or 35, entries from the first table in 表.

Lastly I did some simple encoding of the table's integers into an ascii string.

I know I could 'save bytes' by removing the Hanzi but like I said, this is not optimal and there is more golfing possible... I will remove them when there is no other possible optimization. Those Hanzi actually have meaning loosely based on their actual meaning, and even though I don't know Chinese, it helps me think about the program.

```
数  index number
宽  screen width
素  pixel data
梴  length of side of triangle
态  current state
址  address of pixel
表  state transition table

```

To test the code you will need full golang file, with this header

```
package main
import "fmt"

```

and this footer

```
func main ()  {
    for i := 0; i<15; i++ {
       卷(i)
    }
}

```

thanks
> 1 votes

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


# Question
Title: Find the original string, without the repetition without the repetition in the middle
Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice *couple of words twice* in succession.

To make sure *make sure* other people are not bothered by this, your task is to write a program that resolves this problem!

# Task

Given an input string (if it matters for your language, you may assume ASCII-only input that does not contain linefeeds.) `str`, that contains somewhere in its middle a substring that occurs twice in immediate succession, return the string with one instance of this substring removed.

In the case of multiple possibilities, return the shortest answer possible (that is, pick the longest consecutive repeating substring and remove that one).

In the case of multiple, equally-long consecutive repeating substrings, remove the first (that is, the first one encountered when reading through the string from front to back) one.

You may assume that the input is correct (i.e. always contains a consecutive repeating substring), which might help to golf it down.

---

# Examples

1. Input: `hello hello world` -\> Output: `hello world`.
2. Input: `foofoo` -\> Output: `foo`. (So: Yes, the string might only consist of the repeating part twice).
3. Input: `aaaaa` -\> Output: `aaa`, as the longest repeating consecutive substring is here `aa`.
4. Input: `Slartibartfast` -\> This is not a valid input, as it does not contain a consecutive repeating substring, so you do not need to handle this case.
5. Input: `the few the bar` -\> This is another invalid input, since the repeating part should immediately follow the original part. In this case, `the` and `the` are separated by something else in-between, so this input is invalid.
6. Input: `ababcbc` -\> Output: `abcbc`. The two possible longest consecutive repeating substrings are `ab` and `bc`. As `ab` is encountered earlier in the string, this one is the correct answer.
7. Input: `Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo`. Output: `Buffalo buffalo buffalo buffalo Buffalo buffalo`. (The performed replacement should be case-sensitive).
8. Input: `Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice couple of words twice in succession.` -\> Output: `Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice in succession.`. Only the longest consecutive repeating substring is removed.

---

Your code should be as short as possible, since this is , so the shortest answer in bytes wins. Good luck!

# Answer
> 9 votes
## Retina, ~~35~~ 33 bytes

Byte count assumes ISO 8859-1 encoding.

```
(?=(.+)(\1.*))
$2¶$`
O$#`
$.&
G1`

```

Try it online!

### Explanation

Since regex engines look for matches from left to right, it's not trivial to find the longest match regardless of position. It can be done with .NET's balancing groups, but the result is rather unpleasantly long:

```
1`((.)+)\1(?<=(?!.*((?>(?<-2>.)+).+)\3)^.*)
$1

```

So I figured I'd try to avoid that by making use of some other Retina features.

```
(?=(.+)(\1.*))
$2¶$`

```

We start by essentially applying *all* possible substitutions, one on each line. To do this, we match the position in front of a match (instead of the match itself), to allow for overlapping matches. This is done by putting the real regex into a lookahead. That lookahead then captures the remaining except the duplicate we want to remove in group 2. We write back group 2 (deleting the duplicate), a linefeed, and then then the entire input up to the match, which gives us basically a fresh line to be substituted.

At the end we'll have one line for each match, with the corresponding duplicate removed. At the end there'll also be the full input again without any substitutions done.

Now that we have all the possible substitutions, we want the shortest result (which corresponds to the longest removed repetition).

```
O$#`
$.&

```

So we first sort the lines by length.

```
G1`

```

And then we only keep the first line.

# Answer
> 8 votes
# Perl 6, 40 bytes

```
{.subst: m:ex/(.*))>$0/.max(*.chars),''}

```

Try it

```
{
  .subst:             # substitute

    m                 # match
    :exhaustive
    /
      ( .* )          # any number of chars

      )>              # don't include the following in what is returned

      $0              # the first match again
    /.max( *.chars ), # find the first longest submatch

    ''                # substitute it with nothing
}

```

# Answer
> 7 votes
# Jelly, ~~22~~ 19 bytes

-2 bytes thanks to Dennis (avoid an argument reversal, remove subtly redundant increment)

```
ẋ2³wȧ+¥J
ẆÇ€LÐṀḢṬœp

```

**Try it online!**

Full program (a bug has been found with `ÐṀ` not acting with the correct arity over dyads, which will be fixed soon; although I'm not sure it can make for shorter code here).

### How?

Finds the first of the longest slices of the input such that a repetition exists in the input and removes it from the input.

```
ẋ2³wȧ+¥J - Link 1, removal indices for given slice if valid, else 0: slice, x
ẋ2       - repeat x twice, say y
  ³      - program input: s
   w     - index of first occurrence of y in s (1-based) or 0, say i
       J - range(length(x)): [1,2,3,...,length(x)]
      ¥  - last two links as a dyad
    ȧ    -     and (non-vectorising)
     +   -     addition: [1+i,2+i,3+i,...,length(x)+i] or 0
         - note: no need to decrement these since the last index will be the 1st index
         - of the repetition (thanks to Dennis for spotting that!)

ẆÇ€LÐṀḢṬœp - Main link: string, s
Ẇ          - all sublists of s (order is short to long, left to right, e.g. a,b,c,ab,bc,abc)
 Ç€        - call the last link (1) as a monad for €ach
    ÐṀ     - filter by maximal
   L       -     length
      Ḣ    - head: get the first (and hence left-most) one
       Ṭ   - untruth: make a list with 1s at the indexes given and 0s elsewhere
        œp - partition s at truthy indexes of that, throwing away the borders
           - implicit print

```

# Answer
> 6 votes
## JavaScript (ES6), ~~81~~ 74 bytes

```
f=
s=>s.replace(/(?=(.+)\1)/g,(_,m)=>r=m[r.length]?m:r,r='')&&s.replace(r,'')
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

Edit: Saved 7 bytes by stealing @Arnauld's `m[r.length]` trick.

# Answer
> 6 votes
# Haskell, 101 bytes

Main function is `f`, it takes and returns a `String`.

```
l=length
a=splitAt
f s|i<-[0..l s-1]=[p++t|n<-i,(p,(r,t))<-fmap(a$l s-n).(`a`s)<$>i,r==take(l r)t]!!0

```

Try it online!

When I started this, I imported `Data.List` and used `maximum`, `tails`, `inits` and `isPrefixOf`. *Somehow* that got turned into this. But I still only managed to shave off 11 bytes...

# Notes

* `splitAt`/`a` splits a string at a given index.
* `s` is the input string.
* `i` is the list of numbers `[0 .. length s - 1]`, the `-1` is to work around that `splitAt` splits at the end if given a too large index.
* `n` is `length s` minus the current length goal for the repeated part, it's chosen that way so we don't have to use two number lists and/or the verbose decreasing list syntax.
* `p`,`r`, and `t` are a threeway split of `s`, with `r` the intended repeated part. The `fmap` there uses the `(,) String` `Functor` to avoid a variable for an intermediate split.
* `!!0` selects the first element of the list of matches.

# Answer
> 5 votes
# PowerShell, 87 bytes

```
param($s)([regex](([regex]'(.+)\1'|% *hes $s|sort L*)[-1]|% Gr*|% V*)[1])|% Re* $s '' 1

```

Try it online! (all test cases)

## Explanation

Starting from the inside basically, we run `Matches` with the `(.+)\1` regex, to return all match objects for the specified string. The regex matches any sequence of characters that is followed by itself.

Then the resulting match objects are piped into `sort` to be sorted by their `Length` property (shortened to wildcard). This results in an array of matches sorted by length, ascending, so index with `[-1]` to get the last element (the longest). That match's value is the match though, not the group, so it includes the repetition, so we retrieve the Group object (`|% Gr*`) and then the value of that (`|% V*`) to get the largest repeated string. Thing is the group object is actually an array because group 0 is always the match, but I want the actual group (1), so the resulting value is actually value**s**, hence indexing to get the second element `[1]`. This value is casted to a regex object itself and then the `Replace` method is called against the original string, replacing with nothing, and only the first match is replaced (`|% Re* $s '' 1`).

# Answer
> 5 votes
# Jelly, ~~23~~ 21 bytes

```
ṚẆUẋ€2ẇÐf¹ṪðLHḶ+w@Ṭœp

```

*Thanks to @JonathanAllan for his `Ṭœp` idea which saved 2 bytes.*

Try it online!

# Answer
> 4 votes
# Mathematica, ~~63~~ ~~60~~ 59 bytes

<sup>*4 bytes saved due to Martin Ender.*</sup>

```
#&@@StringReplaceList[#,a__~~a__->a]~SortBy~{StringLength}&

```

Anonymous function. Takes a string as input and returns a string as output.

# Answer
> 3 votes
## JavaScript (ES6), 70 bytes

```
s=>s.replace(s.match(/(.+)(?=\1)/g).reduce((p,c)=>c[p.length]?c:p),'')

```

### Test cases

```
let f =

s=>s.replace(s.match(/(.+)(?=\1)/g).reduce((p,c)=>c[p.length]?c:p),'')

console.log(f("hello hello world"))
console.log(f("foofoo"))
console.log(f("aaaaa"))
console.log(f("ababcbc"))
console.log(f("Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice couple of words twice in succession."))
```

# Answer
> 2 votes
This should be a comment, but I don't have enough reputations to comment. I just want to tell @Neil that his code can be reduced to 77 bytes. You don't need to use forward assertion in regex. Here is reduced version:

```
s=>s.replace(/(.+)\1/g,(_,m)=>(n=m.length)>l&&(l=n,r=m),l=0)&&s.replace(r,'')

```

# Answer
> 0 votes
## C#, 169 bytes

```
(s)=>{var x="";for(int i=0;i<s.Length-2;i++){for(int l=1;l<=(s.Length-i)/2;l++){var y=s.Substring(i,l);if(s.Contains(y+y)&l>x.Length)x=y;}}return s.Replace(x+x,x);}

```

### Explanation

```
(s) => {                // Anonymous function declaration
    var x = "";         // String to store the longest repeating substring found
    for (int i = 0; i < s.Length - 2; i++) {               // Loop through the input string
        for (int l = 1; l <= (s.Length - i) / 2; l++) {    // Loop through all possible substring lengths
            var y = s.Substring(i, l);
            if (s.Contains(y + y) & l > x.Length) x = y;   // Check if the substring repeats and is longer than any previously found
        }
    }
    return s.Replace(x + x, x);    // Perform the replacement
}

```

This is the brute-force approach: try every possible substring until we find the longest repeating substring. Undoubtedly Regex is more efficient, but dealing with Regex in C# tends to be quite verbose.

# Answer
> 0 votes
# PHP, ~~84~~ 82 bytes

Note: uses IBM-850 encoding.

```
for($l=strlen($argn);--$l&&!$r=preg_filter("#(.{0$l})\g-1#",~█╬,$argn,1););echo$r;

```

Run like this:

```
echo 'hello hello world' | php -nR 'for($l=strlen($argn);--$l&&!$r=preg_filter("#(.{0$l})\g-1#",~█╬,$argn,1););echo$r;';echo
> hello world

```

# Explanation

```
for(
  $l=strlen($argn);   # Set $l to input length.
  --$l   &&           # Decrement $l each iteration until it becomes 0.
  !$r=preg_filter(    # Stop looping when preg_filter has a result
                      # (meaning a successful replace).
    "#(.{0$l})\g-1#", # Find any character, $l times (so the longest
                      # match is tried first), repeated twice.
    ~█╬,              # Replace with $1: first capture group, removing the
                      # duplicate.
    $argn,
    1                 # Only replace 1 match.
  );
);
echo$r;               # Print the result of the (only) successful
                      # search/replace, if any.

```

# Tweaks

* Saved 2 bytes because there is no minimum length of the repeated substring

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


title: Numbers that are palindromes in N bases

text:
# Question
Title: Numbers that are palindromes in N bases
Given an non-negative integer \\$n \ge 0\\$, output forever the sequence of integers \\$x\_i \ge 3\\$ that are palindromes in exactly \\$n\\$ different bases \\$b\\$, where the base can be \\$2 \le b le x\_i-2\\$.

This is basically the inverse of OEIS A126071, where you output which indices in that sequence have the value \\$n\\$. It's a bit different, because I changed it so you ignore bases \\$b = x\_i-1, \\: x\_i, \\: x\_i+1\\$, since the results for those bases are always the same (the values are always palindromes or always not). Also, the offset is different.

\\$x\_i\\$ is restricted to numbers \\$\ge 3\\$ so that the first term of the result for each \\$n\\$ is A037183.

Note that the output format is flexible, but the numbers should be delimited in a nice way.

**Examples:**

```
n   seq
0   3 4 6 11 19 47 53 79 103 137 139 149 163 167 ...
1   5 7 8 9 12 13 14 22 23 25 29 35 37 39 41 43 49 ...
2   10 15 16 17 18 20 27 30 31 32 33 34 38 44 ...
3   21 24 26 28 42 45 46 50 51 54 55 56 57 64 66 68 70 ...
4   36 40 48 52 63 65 85 88 90 92 98 121 128 132 136 138 ...
5   60 72 78 84 96 104 105 108 112 114 135 140 156 162 164 ...
10  252 400 420 432 510 546 600 648 784 800 810 816 819 828 858 882 910 912 1040 1056 ...

```

So for \\$n=0\\$, you get the output of this challenge (starting at \\$3\\$), because you get numbers that are palindromes in `n=0` bases.

For \\$n=1\\$, \\$5\\$ is a palindrome in base \\$2\\$, and that's the only base \\$2 \le b \le (5-2)\\$ that it's a palindrome in. \\$7\\$ is a palindrome in base \\$2\\$, and that's the only base \\$2 \le b \le (7-2)\\$ that it's a palindrome in. Etc.

---

Iff your language does not support infinite output, you may take another integer `z` as input and output the first `z` elements of the sequence, or all elements less than `z`. Whichever you prefer. Please state which you used in your answer if this is the case.

Related

# Answer
# Jelly,  ~~18~~  15 bytes

-1 thanks to caird coinheringaahing.

```
ṄµbḊŒḂ€S’⁼³µ¡‘ß

```

**Try it online!** \- the online interpreter will timeout at 60 seconds then flush it's output (unless it has a cached copy), offline it will print each in turn.

### How?

Evaluates numbers from `n` up, printing them if they are in the sequence. Note that the first number in any output will be greater than `n` since otherwise the range of `b` is not great enough, so there is no need to seed the process with `3`. Also note that the number of palindromes from base **2** to **xi-2** inclusive is just one less than the number of palindromes from base **2** to **xi**.

```
ṄµbḊŒḂ€S’⁼³µ¡‘ß - Main link: n
            ¡   - repeat...
Ṅ               - ...action: print (the CURRENT n)
 µ         µ    - ...number of times: this monadic chain:
   Ḋ            -      deueue -> [2,3,4,...,n]
  b             -      n converted to those bases
    ŒḂ€         -      is palindromic? for €ach
       S        -      sum: counts the 1s
        ’       -      decrement: throw away the truthy base n-1 one
         ⁼³     -      equals input: Does this equal the ORIGINAL n?
             ‘  - increment n
              ß - calls this link as a monad, with the incremented n.

```
> 3 votes

# Answer
# Mathematica, ~~80~~ 71 bytes

*Thanks to JungHwan Min for saving 9 bytes!*

```
Do[#!=Length[i~IntegerReverse~Range[2,i-2]~Cases~i]||Echo@i,{i,3,∞}]&

```

( is the three-byte character U+221E.) Pure function taking a nonnegative integer as input. `i~IntegerReverse~Range[2,i-2]` creates a list of the reversals of the number `i` in all the bases from `2` to `i-2`; then `Length[...~Cases~i]` counts how many of these reversals are equal to `i` again. `#!=...||Echo@i` halts silently if that count is not equal to the input, and echoes `i` if it is equal to the input. That procedure is embedded in a straightforward infinite loop.
> 4 votes

# Answer
# Pyth, 21 19 18 bytes

```
.V3IqQlf_IjbTr2tbb

```

This should work in theory. It works properly if I substitute the infinite loop for any finite one (e.g. `JQFbr3 50*`bqJlf_IjbTr2tb` for 3 up to 50, try here), but the Pyth interpreter doesn't know when or how to print literally infinite output.

Explanation:

```
.V3IqQlf_IjbTr2tbb
.V3                     increase b infinitely, starting from 3
             r2Tb       range of integers including 2 to b - 2
      lf                length of elements retained if:
          jbT             b in that base
        _I                is invariant under reversal
    qQ                  check if the length is equivalent to the input
   I             b      output b if so

```
> 1 votes

# Answer
# Perl 6, 90 bytes

```
->\n{->{$_=++($ //=2);$_ if n==grep {($/=[.polymod($^b xx*)])eq[$/.reverse]},2..$_-2}...*}

```

Try it

```
-> \n {

  # sequence generator
  ->{         # using a code block with no parameter

    $_ =      # set the default scalar to the value being tested
      ++(     # preincrement
        $     # anonymous state variable
        //= 2 # initialized to 2
      );

    # the anonymous state var maintains its state
    # only for this current sequence
    # every time the outer block gets called it is created anew

    $_    # return the current value
      if  # if the following is true

        n == grep # find all that match the following code

          {
            # convert the current value to the base being tested
            # store as an Array in $/
            ($/ = [ .polymod($^b xx*) ] )

            eq    # is string equal to: (shorter than eqv)

            [ $/.reverse ]
          },

          2 .. $_ - 2 # from the list of bases to test
  }

  ...  # keep using that code block to produce values

  *    # indefinitely
}

```
> 1 votes

# Answer
# Bash \+ Unix utilities, ~~134~~ 132 bytes

```
for((x=3;;x++)){
c=$1
for((b=x-1;--b>1;)){
s=`bc<<<"for(y=$x;y;y/=$b)y%$b"`
t=`tac<<<"$s"`
[ "${s#$t}" ]||((c--))
}
((c))||echo $x
}

```

Try it online!

Input is passed as an argument. The output is on stdout.

If you run this normally, it will display one number at a time in the infinite sequence.

If you try this in TIO, it will display as much of the output as it has generated when it times out at 60 seconds.
> 1 votes

# Answer
# Python 2, 132 bytes

```
B=lambda n,b:[]if(n<1)else B(n/b,b)+[n%b]
n=input()
x=3
while 1:
    if sum(B(x,b)==B(x,b)[::-1]for b in range(2,x-1))==n:print x
    x+=1

```

**Try it online**

The TIO program has a footer added so you don't have to wait 1 minute for the program to time out before seeing the output.
> 0 votes

---
Tags: code-golf, sequence, base-conversion, palindrome
---


title: Solve Math Problem Notation

text:
# Question
Title: Solve Math Problem Notation
Imagine I have an infinite number of homework problems (!) each given an integer number.

Math Problem Notation is a notation for describing subsets of the problem using problem specifiers.

An MPN expression can consist of several things:

* A single value. This represents a set containing the number: `99 -> {99}`.
* A simple range. This represents the set containing all the numbers from the beginning to the end of the range: `10~13 -> {10, 11, 12, 13}`. If the left or right sides are missing, then they are assumed to be -Infinity or Infinity respectively: `~10 -> {x|x ≤ 10}`; `~ -> ℤ`.
* An MPN expression, followed by "skip" and another MPN expression. This represents the difference of the two sets: `10~20 skip 12~14 -> {10, 11, 15, 16, 17, 18, 19, 20}`.
* Two MPN expressions, separated by a comma. This represents the union of two sets: `1,8~9,15~17 -> {1,8,9,15,16,17}`.

The "skip" operator binds tighter than the comma operator, so `16,110~112 skip 16 -> {16,110,111,112}` (16 is not included in the set `{110,111,112}`, so the excluding 16 does not matter.)

You can also put expressions in parentheses for disambiguation: `1~9 skip (2~8 skip (3~7 skip (4~6 skip 5))) -> {1,3,5,7,9}`

This is the grammar:

```
<expr>  ::= "(" <expr> ")"
         || <number>
         || [<number>] "~" [<number>]
         || <expr> "skip" <expr>
         || <expr> "," <expr>

```

---

Your task is to write a program that takes two inputs:

* An MPN expression
* A number

and outputs some truthy or falsey value depending on whether that problem is in the set described by the MPN expression.

## Specifications

* You can assume that the first input is a well-formed MPN expression (i.e. that it matches the above grammar)
* Numbers in an MPN expression are always integers. They can be negative or zero, but will never have a fractional part.
* This is , so the shortest valid submission (measured in bytes) wins.
* You can use different characters for `~` and `,`, if you want.

## Test Cases

```
10~20             14 -> True
10~20             20 -> True
10~20 skip 14~18  17 -> False
~ skip 6          8  -> True
16,17 skip 16     16 -> True
(16,17) skip 16   16 -> False
~10,5~            8  -> True
~10,5~            4  -> True
6 skip 6,~        6  -> True

```

# Answer
> 3 votes
# PowerShell, ~~189~~ 195 bytes

```
param($m,$q)('$m',"'(\d*)~(\d*)','($q-ge(`$1)-and$q-le(`$2))'","'\(\)',$q","'((?<=,|skip )\d+|\d+(?=,| skip))','($q-eq`$1)'","'skip','-and!'"-join'-replace'|iex|% Sp* ','|%{"($_)"})-join'-or'|iex

```

## Explanation

I realized early on that the infinities make this untenable for generating arrays and testing for values.

I looked into ranges but in .Net they don't have the range needed (the *length* of the range is limited to a signed (32 bit) integer, so even if it were ok to limit the range to a signed 32-bit int, I wouldn't have been able to handle all ranges.

So I started to just think about this in terms of starts and ends, and ultimately a series of boolean tests and started creating a bunch of regex replaces to turn an MPN into a boolean expression that PowerShell understands.

I basically broke this down into a few rules:

* Ranges were easier to work with first because they can't be expressions on either end, but the open-endedness was a pain to implement shortly. The premise is `2~8` is like saying `n >=2 && n <=8`, but when one of the ends is missing, leave out the `&&` and the missing side. When both are missing, I was going to originally just replace it with `$true`. What I ended up doing was not really testing for the missing sides at all, but I made sure to wrap each number in `()`.
* and then do a straight substitution that replaces empty parentheses `()` with the input value. So, in the case of an MPN like `~8` with an input value of `55`, the first replace will generate `(55-ge()-and55-le(8))`, then the second replace comes along to make it `(55-ge55-and55-le(8))`, essentially nullifying that part of the range.
* Next I had to deal with individual numbers in the MPN, but had to take care not to mess with the ones I inserted from before. It's really just numbers in comma `,` separated lists, and individual numbers before or after a `skip`, so I used unfortunatley long lookarounds.
* `skip` is basically the same as `-and -not` so I do a straight replace of `skip` to `-and!` (using `!` as shorthand for `-not`).
* The next tricky thing was the low order of precendence for the remaining commas. I originally just replaced them with `-or` but it didn't account for subsequent expressions so `16,17 skip 16` was generating code like `($n-eq16)-or($n-eq17) -and! ($n-eq16)`. It needed parentheses, but that seemed unworkable with a straight replace. Since all the other things were replaced except commas, and they have the lowest precedence, I just split the entire generated string on the remaining commas, then wrapped each element in parentheses, and rejoined it with `-or`.

Ultimately the generated code is just piped into `Invoke-Expression` (`iex`) to be executed and then we get the boolean result (you can see the code that gets generated instead of the result here).

This took way too long, and I'm sure there's some room to squeeze out a few more bytes, but I can't look at it anymore :-p

# Answer
> 2 votes
# Perl, ~~99~~ 130 bytes

```
sub f{($_,$n)=@_;s/(-?\d+)?~(-?\d+)?|(-?\d+)/!(defined$3?$n!=$3:length$1&&$1>$n||length$2&&$n>$2)+0/ge;s/skip/&&!/g;s/,/||/g;eval}

```

Try it on Ideone.

Ungolfed:

```
sub f {
    my ($e, $n) = @_;

    $e =~ s/(-?\d+)?~(-?\d+)?|(-?\d+)/ (defined($3) ? $n == $3 : (!length($1) || $n >= $1) && (!length($2) || $n <= $2)) + 0 /ge;
    $e =~ s/skip/ && ! /g;
    $e =~ s/,/ || /g;

    return eval($e);
}

```

# Answer
> 1 votes
# JavaScript (ES6), ~~221~~ ~~292~~ ~~287~~ ~~309~~ ~~274~~ ~~277~~ 278 bytes

*(-5 bytes thanks to Okx)*

```
(j,v,m=1/0,Z=/(skip)([^,]+)/g)=>eval(j[M='replace'](/(-?\d*)~(-?\d*)/g,(e,a,b)=>(a[M]('-','#')||-m)+'<='+(T=v[M]('-','#'))+'&&'+T+'<='+(b[M]('-','#')||m))[M](Z,i=o=>o.match(Z)?i(o[M](Z,'&&!($2)')):o)[M](/,/g,'||')[M](/(^|[^=&#\d])(\d+)([^<\d]|$)/g,'$1$2=='+v+'$3')[M](/#/g,'-'))

```

Wow. This was not easy because of all the edge cases, but I think I did it. I just *hope* there are no special cases that could break the regular expressions used. I will golf this more whenever I can.

## Test Snippet

```
D=(j,v,m=1/0,Z=/(skip)([^,]+)/g)=>eval(j[M='replace'](/(-?\d*)~(-?\d*)/g,(e,a,b)=>(a[M]('-','#')||-m)+'<='+(T=v[M]('-','#'))+'&&'+T+'<='+(b[M]('-','#')||m))[M](Z,i=o=>o.match(Z)?i(o[M](Z,'&&!($2)')):o)[M](/,/g,'||')[M](/(^|[^=&#\d])(\d+)([^<\d]|$)/g,'$1$2=='+v+'$3')[M](/#/g,'-'))
```

```
MPN Expression:<input type="text" value="1~9 skip (2~8 skip (3~7 skip (4~6 skip 5)))" id="MPN"></input>
<br>
Integer:<input type="number" id="INT" value=6></input>
<input type="button" value="Submit" onclick="T=r=>document.getElementById(r).value;console.log(D(T('MPN'),T('INT')))"></input>
```

# Answer
> 0 votes
# Röda \+ bc, 183 bytes

```
f x{{["x=",x,"\n"];replace" ","",",","||","skip\\(","&&!","skip([0-9~]+)","&&!($1)","(?<!~|\\d)(\\d+)(?!~|\\d)","x==$1","(\\d*)~(\\d*)","x>=($1)&&x<=($2)","\\(\\)",x;["\n"]}|exec"bc"}

```

This is similar to the PowerShell answer (or I think so, I don't understand PowerShell). It takes the number as an argument and the code as a value in the input stream, like this: `main { push("1~9") | f(5) }`.

I think it works, at least it solves all test cases. The script below can be used to verify this.

```
main {
    readLines("/tmp/tests.txt") | split(sep=";") | for code, num, ans do
        push(code, " -> ")
        print(code) | replace" ","",",","||","skip\\(","&&!","skip([0-9~]+)","&&!($1)","(?<!~|\\d)(\\d+)(?!~|\\d)","x==$1","(\\d*)~(\\d*)","x>=($1)&&x<=($2)","\\(\\)",num
        a := push(code) | f(num) | head()
        result := push("OK") if [ (a = "0" and ans = "False") or (a = "1" and ans = "True") ] else push("FAIL")
        print code, " ; ", num, " -> ", a, " ", ans, " (", result, ")\n"
    done
}

```

And the tests:

```
10~20;14;True
10~20;20;True
10~20 skip 14~18;17;False
~ skip 6;8;True
16,17 skip 16;16;True
(16,17) skip 16;16;False
~10,5~;8;True
~10,5~;4;True
6 skip 6,~;6;True

```

---
Tags: code-golf, decision-problem, parsing, set-theory
---


title: Leaderboard golf

text:
# Question
Title: Leaderboard golf
Golf the leaderboard of this question (id=111735). Your program should issue **one** HTTP or HTTPS request to StackExchange API, parse it and present to user in form similar to a typical Leaderboard Snippet

Sample output (for the question 47338 instead of this):

```
Leaderboard
    Author  Language    Size
1.  FryAmTheEggman  Pyth    19
2.  Peter Taylor    CJam    24
3.  Martin Ender    CJam    27
3.  Peter Taylor    GolfScript  27
5.  randomra    J   32
5.  Optimizer   CJam    32
7.  Timtech TI-Basic 83/84  40
8.  mollmerx    k   41
9.  Sp3000  ><> 45
10. Sherlock9   Ruby    47
11. Martin Ender    Mathematica 49
12. Alex A. Julia   57
13. Sp3000  Python 2    58
14. Zgarb   Haskell 68
15. Timtech GML 76
16. Jakube  Python 2    79
16. nimi    Haskell 79
18. coredump    Common Lisp 91
19. Jim Large   Ruby    92
Winners by Language
Language    User    Score
Python 2    Sp3000  58
CJam    Peter Taylor    24
Julia   Alex A. 57
TI-Basic 83/84  Timtech 40
><> Sp3000  45
Haskell Zgarb   68
GolfScript  Peter Taylor    27
Common Lisp coredump    91
Pyth    FryAmTheEggman  19
k   mollmerx    41
J   randomra    32
Ruby    Sherlock9   47
Mathematica Martin Ender    49
GML Timtech 76

```

**Note the repeated ranks 3, 5 and 16. Maybe I'll even add a special non-competing answer just to force correct, non-simplified handing of the score duplicates.**

The output should consist of:

1. The line "Leaderboard"
2. The line "\tAuthor\tLanguage\tSize"
3. For each answer, tab-separated line of rank and a `.`, then answer author name, then language name, then score; in ascending order for score
4. The line "Winners by Language"
5. The line "Language\tUser\tScore"
6. For each used language, tab-separated language name, author of the lower score answer and the score

In other words, something like as if one copies and pastes result of the leaderboard snippet of this question to a text file (without "\tLink" things). See also the reference implementation in Python.

## Rules

* No network access apart from one API request to `api.stackexchange.com`
* No usage of API features or languages that appeared after the submission of this question.
* First line of the answer post should be Leaderboard-compatible. If it breaks the leaderboard script attached to the question then answer is non-competing.
* If newly added answer renders some existing answer broken then the author of the old answer should fix it (or it becomes non-competing).
* Links to languages, striked out scores, etc. should be handleded.
* Ranks should be handled like in the snippet (e.g. equal score =\> equal rank =\> gap in ranks).

Accepted answer is the answer with the lowest score after sufficient amount of inactivity (minimum 1 month).

## Good idea

* To test with question IDs 47338 (for duplicate score handling + striked out score handling) and 17005 (for links handling). This bumps the answer from Valid to Good and protects from breaks from later submissions.
* To include output examples both for this and for overridden ID versions.

## Not necessary

* Handling of more than 100 answers (limit of API for single request)
* Handling of comment overrides
* Sorting of "Winners by Language" section
* Discrimination of competing and broken answers

## Leaderboard

```
var QUESTION_ID=111735,OVERRIDE_USER=7773;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Perl + Mojolicious, ~~468~~ ~~456~~ ~~469~~ 504 bytes

Using Mojolicious library.

```
use v5.10;use ojo;while(@i=@{(g("http://api.stackexchange.com/2.2/questions/111735/answers?site=codegolf&filter=withbody&page=".++$p)->json//{})->{items}}){push@r,[$_->{owner}{display_name},(($h=x($_->{body})->at("h1,h2")||next)->at("a")||$h)->text=~/\s*([^,]+)\s*/,$h->text=~/(\d+)[^\d]*$/]for@i}$,="   ";say"Leaderboard
",Author,$l=Language,Size;say+(++$i,$s{@$_[2]}//=$i).".",@$_
for@r=sort{@$a[2]-@$b[2]}@r;%h=map{@$_[1],$_}reverse@r;say"Winners by $l
$l",User,Score;say$_,$h{$_}[0],$h{$_}[2]for keys%h

```

Ungolfed:

```
use v5.10;
use ojo;

my @r;
while (my @i = @{ (g("http://api.stackexchange.com/2.2/questions/111735/answers?site=codegolf&filter=withbody&page=" . ++$p)->json // {})->{items} }) {
    my $h = x($_->{body})->at("h1,h2") or next;
    push(@r, [$_->{owner}{display_name}, ($h->at("a") || $h)->text =~ /\s*([^,]+)\s*/, $h->text =~ /(\d+)[^\d]*$/]) for @i;
}

$, = "\t";
my %s;
say("Leaderboard\n", "Author", (my $l = "Language"), "Size");
say((++$i, $s{$_->[2]} //= $i) . ".", @$_) for @r = sort { $a->[2] <=> $b->[2] } @r;

my %h = map { $_->[1] => $_ } reverse(@r);
say("Winners by $l\n$l", "User", "Score");
say($_, $h{$_}[0], $h{$_}[2]) for keys(%h);

```
> 2 votes

# Answer
# Python 3, ~~860~~ 856 bytes

Golfed slightly, just to bootstrap the leaderboard and provide some template for other golfers:

```
import json,re,html as h,requests as r
p=print
u=h.unescape;a=[];n={}
for i in json.loads(r.get("https://api.stackexchange.com/2.2/questions/111735/answers?page=1&pagesize=100&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe").text)["items"]:
    m=re.match(r'<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)',i["body"].splitlines()[0]);l=u(m.group(1));t=u(i["owner"]["display_name"]);s=m.group(2);a.append((t,l,s))
    if l not in n: n[l]=[]
    n[l].append((t,s))
p("Leaderboard\n\tAuthor\tLanguage\tSize")
z=0;y=None
for i in enumerate(sorted(a,key=lambda x:x[2])):
    if y==i[1][2]:z+=1
    else:z=0;y=i[1][2]
    p("%d.\t%s\t%s\t%s"%(i[0]+1-z,i[1][0],i[1][1],i[1][2]))
p("Winners by Language\nLanguage\tUser\tScore")
for i in n.keys():
    n[i].sort(key=lambda x:x[1])
    print("%s\t%s\t%s"%(i,n[i][0][0],n[i][0][1]))

```

Indented with tabs. The last `print` is deliberately not replaced by `p` to create a score tie with the Mathematica answer.

Ungolfed:

```
import json
import re
import html
import requests
url="https://api.stackexchange.com/2.2/questions/111735/answers?page=1&pagesize=100&site=codegolf&filter=!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"
data=json.loads(requests.get(url).text)
answers=[]
languages={}
for i in data["items"]:
    header=i["body"].splitlines()[0]
    m=re.match(r'<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)', header)
    lang=html.unescape(m.group(1))
    author=html.unescape(i["owner"]["display_name"])
    score=m.group(2)
    answers.append((author, lang, score))
    if lang not in languages: languages[lang]=[]
    languages[lang].append((author, score))
answers.sort(key=lambda x:x[2])
print("Leaderboard")
print("\tAuthor\tLanguage\tSize")
rankadj=0
prevscore=None
for i in enumerate(answers):
    if prevscore == i[1][2]:
        rankadj+=1
    else:
        rankadj=0
        prevscore=i[1][2]
    print("%d.\t%s\t%s\t%s" % (i[0]+1-rankadj, i[1][0], i[1][1], i[1][2]))
print("Winners by Language")
print("Language\tUser\tScore")
for i in languages.keys():
    w=languages[i]
    w.sort(key=lambda x:x[1])
    print("%s\t%s\t%s" % (i, w[0][0], w[0][1]))

```

Note: it does not yet handle links correctly, so fails for, for example, question 17005.
> 6 votes

# Answer
# Bash + JQ, 399 bytes

Note, this can almost certainly be golfed further, by optimizing the `jq` expression logic.

**Golfed**

```
curl api.stackexchange.com/2.2/questions/111735/answers?site=codegolf\&filter=withbody|zcat|jq -r '[.items[]|{o:.owner.display_name}+(.body|capture("^<h1>(?<l>.*?),.*?(?<b>\\d*)\\D*</h"))]|sort_by(.b|tonumber)|("Leaderboard\n\tAuthor\tLanguage\tSize",(keys[] as $i|.[$i]|"\($i+1).\t"+.o+"\t"+.l+"\t"+.b),"Winners by Language\nLanguage\tUser\tScore",(group_by(.l)|.[]|min_by(.b)|.l+"\t"+.o+"\t"+.b))'

```

**Sample Output**

```
Leaderboard
    Author  Language    Size
1.  zeppelin    Bash + JQ   399
2.  Tom JavaScript ES6  454
3.  Denis Ibaev Perl    456
4.  Vi. Python 3    860
Winners by Language
Language    User    Score
Bash + JQ   zeppelin    399
JavaScript ES6  Tom 454
Perl    Denis Ibaev 456
Python 3    Vi. 860

```
> 1 votes

# Answer
# Mathematica, ~~852~~ 856 bytes

Uses the built-in `JSONTools` package. This isn't the kind of thing Mathematica's meant to be used for...so I used it!

```
p=Print;S=StringRiffle;L=Length;r=Range;out=Association@JSONTools`FromJSON[Import["http://api.stackexchange.com/2.2/questions/111735/answers?site=codegolf&filter=withbody"]];l={};i=Association/@(out["items"]);
(f=("body"/.i)[[#]];h=StringPosition[f,{"<h1>","</h1>"}];a="display_name"/.("owner"/.i)[[#]];s=StringSplit[StringTake[f,{h[[1]][[2]]+1,h[[2]][[1]]-1}],{",","<a>","</a>",">","<s>","</s>"," bytes","<strike>","</strike>"}];AppendTo[l,{a,s[[1]],ToExpression@s[[-1]]}])&/@r@L["body"/.i];l=SortBy[l,Last];o=r@L@l;If[l[[#]][[3]]==l[[#-1]][[3]],o[[#]]=o[[#-1]]]&/@r[2,L@l];
p@"Leaderboard"
p@"\tAuthor\tLanguage\tSize"
For[i=1,i<=L@l,i++,p[ToString@o[[i]]<>"."<>S[l[[i]][[#]]&/@r@3,"\t"]]]
l=SortBy[l,{#[[2]],#[[3]]}&];l=DeleteDuplicatesBy[l,#[[2]]&];
p@"Winners by Language"
p@"Language\tUser\tScore"
For[i=1,i<=L@l,i++,p[S[l[[i]][[#]]&/@{2,1,3},"\t"]]]

```
> 1 votes

---
Tags: code-golf, stack-exchange-api
---


title: Eating Skittles Like a Normal Person

text:
# Question
Title: Eating Skittles Like a Normal Person
Skittles are colored candy where there are 5 distinct flavors; grape, green apple, lemon, orange, and strawberry represented by (p)urple, (g)reen, (y)ellow, (o)range, and (r)ed respectively. I used to eat skittles by sorting all the different colors, then eating them in sequence. After getting a few weird looks in the office, I now pretend to eat them like a normal person. Your task is to emulate this:

Your code (full program or function) will receive an array of skittles (10x10) as input (in any reasonable format). This array will represent a pile of unsorted skittles. Your task is to "eat" them from your least favorite to favorite color. My preferred order is grape, green apple, lemon, orange, strawberry, but you are free to choose any order so long as it is consistently enforced (please list your preference in your submission so I can judge you for it). After eating each piece of candy your code will output (in the same format you take input) the remaining pile with the eaten piece replaced by a space. You will repeat until only your favorite remains. You may choose any skittle to eat (may be random or deterministic). Trailing spaces must be kept.

For example, your output sequence could look like this (using 5x5 for brevity and showing spaces as `.`)

```
start   1     2     3     4     5        n
.org. .org. .org. .org. .or.. .or..    ..r..
prgrg .rgrg .rgrg .rgrg .rgrg .r.rg    .r.r.
gggpr gggpr ggg.r ggg.r ggg.r ggg.r    ....r
oyyor oyyor oyyor oyyor oyyor oyyor    ....r
.r.p. .r.p. .r.p. .r... .r... .r...    .r...

```

This is , so shortest code in bytes wins

**TL;DR Rules:**

* Submission may be full program or function
* Input may be taken in any reasonable format (string, list, matrix, etc) by any reasonable method (STDIN, function arguments, etc.). However there must be some delineation between rows
* Output must be produced in the same format as input by any reasonable method (STDOUT, function return, ect.). Intermediate output may or may not be delimited
* First output shall be the first input
* Trailing spaces must be preserved
* Any color order may be used (list in your answer)
* Any skittle of the current color may be eaten
* Last output shall be only your favorite color and spaces
* If possible, include a link to an online compiler to test your submission

# Answer
# Jelly, ~~16 14~~  13 bytes

```
Ṅ⁶ỤṪ$¦µQL>3µ¿

```

**TryItOnline!**

Most to least favourite, as for anyone serious about their O.C.D., is alphabetical!

Takes input and outputs as text (i.e. the rows are delimited by new lines).

3 bytes saved by reversing the direction and using a different method: grade up rather than finding characters from the alphabet.

### How?

```
Ṅ⁶ỤṪ$¦µQL>3µ¿ - Main link: Skittle text
      µ    µ  - monadic chain separation
            ¿ - while
       Q      - unique items
        L     - length
         >3   - greater than 3 (until only new lines, spaces and 'g's remain)
Ṅ             -     print z and a line feed, yield z
    $         -     treat last two links as a monad
  Ụ           -         grade up (get indices of: new lines; spaces; gs; os; ps; rs; ys)
   Ṫ          -         tail (the last of those, so last y if there is one, else last r, ...)
 ⁶            -     space character
     ¦        -     apply at index (replace that index with a space)

```
> 15 votes

# Answer
## JavaScript (ES6), ~~74~~ ~~75~~ 74 bytes

Flavors are ordered as described in the challenge: grape, green apple, lemon, orange, strawberry.

Intermediate outputs are separated by newlines.

```
f=(s,n=3,r=s)=>(S=s.replace('oygp'[n],' '))!=s&&(r+=`
`+S)||n--?f(S,n,r):r

```

### Test case

This test case is using the 5x5 example. Any other grid size should work as expected.

```
f=(s,n=3,r=s)=>(S=s.replace('oygp'[n],' '))!=s&&(r+=`
`+S)||n--?f(S,n,r):r

console.log(f(
` org
prgrg
gggpr
oyyor
 r p
`))
```
> 8 votes

# Answer
# Bash, ~~48~~, 46 bytes

UPDATE:

* Saved two bytes by using raw parameters to printf;

**Golfed**

```
sed -nz "p;:a;`printf "s/%s/ /p;ta;" p g y o`"

```

Takes input at stdin, prints to stdout. Eats purple, green, yellow and then orange.

An equivalent *sed* program would be:

```
p;:a;s/p/ /p;ta;s/g/ /p;ta;s/y/ /p;ta;s/o/ /p;ta

```

**Sample output** (delimiters are for clarity only)

```
-----
 org
prgrg
gggpr
oyyor
 r p
-----
-----
 org
 rgrg
gggpr
oyyor
 r p
-----
-----
 org
 rgrg
ggg r
oyyor
 r p
-----
-----
 org
 rgrg
ggg r
oyyor
 r
-----
-----
 or
 rgrg
ggg r
oyyor
 r
-----
-----
 or
 r rg
ggg r
oyyor
 r
-----
-----
 or
 r r
ggg r
oyyor
 r
-----
-----
 or
 r r
 gg r
oyyor
 r
-----
-----
 or
 r r
  g r
oyyor
 r
-----
-----
 or
 r r
    r
oyyor
 r
-----
-----
 or
 r r
    r
o yor
 r
-----
-----
 or
 r r
    r
o  or
 r
-----
-----
  r
 r r
    r
o  or
 r
-----
-----
  r
 r r
    r
   or
 r
-----
-----
  r
 r r
    r
    r
 r
-----

```

Try it online !
> 8 votes

# Answer
# Python 2, ~~60 57~~ 56 bytes

```
def f(s):print s;q=max(s);q>'g'and f(s.replace(q,' ',1))

```

**repl.it**

Recursive function that eats in reverse alphabetical order, leaving the greens for last.

Input `s` is a string with a row delimiter with an ordinal less than that of a `'g'` (for example a new line or a comma).

The function prints its input, and then recurses if that input contains anything greater than a 'g', passing the input with the first occurrence of the maximum character replaced by a space.

(Almost a port of my Jelly answer.)
> 7 votes

# Answer
# Perl, ~~53~~ 46 + 2 = 48 bytes

Run with `-0n`

-10 bytes thanks to @Dada

*Edit: Also thanks to @Dada for pointing it out, I forgot to print the input as the first output. That's been fixed.*

```
say;eval sprintf"say while s/%s/./;"x4,p,o,g,r

```

There's a little bit of trickery involved in this answer, so I'll break down what's going on.

First of all, Perl doesn't like multi-line parameters being passed. The variable `$/` is the input record separator, and whenever any input encounters the character stored in it, the interpreter terminates that input and begins a new input. The default content is the newline character `\n`, which means that passing a multi-line string is not possible. To do that, we must unset `$/` from its contents. That's where the `-0` flag comes in: setting `-0` will store `null` in the variable `$/`, allowing the interpreter to read everything into the implicit variable `$_` at once.

The next bit of trickery is the `eval` statement. Just what exactly are we `eval`ing? We're `eval`ing the result of the `sprintf` statement, which is broken down as follows:

The first thing that `sprintf` is passed is the string `"say while s/%s/./;"` repeated 4 times, so:

```
say while s/%s/./;say while s/%s/./;say while s/%s/./;say while s/%s/./;

```

Then, `sprintf` is passed four bareword characters, `p,o,g,r`, which are interpolated into the `sprintf` statement, replacing each instance of `%s`. What we then get is the following string, which is passed to the `eval` function:

```
say while s/p/./;say while s/o/./;say while s/g/./;say while s/r/./;

```

Each `while` loop evaluates the expression `s/[color]/./`, which replaces the first instance of whatever color it is in the implicit variable `$_` with a period. If a substitution is made, it returns `1`, otherwise it returns nothing. Since `s///` has side-effects, it modifies the original variable `$_`, whose contents are then printed via `say`. Four versions of this loop are performed, replacing the purples, the oranges, the greens, and then the reds, leaving only the yellows.

The reason that the yellows are left is because `y` cannot be a bareword, because it's actually a function, and having a `y` instead of any of those letters would throw an error. I could change this by putting quotes around it (+2 bytes), or using a capital Y and making the regex case-insensitive (+1 byte), but for , every byte counts, so I decided that I actually *like* lemon skittles the most.

TL;DR: `Grape, Orange, Green Apple, Strawberry, Lemon`
> 6 votes

# Answer
# Java 7, ~~139 135 130 151 138~~ 135 bytes

```
void t(char[]s){int i,j=-1;for(;++j<5;)for(i=-1;++i<109;)if(j>3|s[i]=="yogp!".charAt(j)){System.out.println(s);if(j>3)return;s[i]=32;}}

```

Eats skittles in the order: Yellow, Orange, Green, Purple, Red

I guess this is better than 2 print statements \>.\>
> 4 votes

# Answer
# Perl, ~~30~~ ~~31~~ 33 + 2 = ~~32~~ ~~33~~ 35 bytes

```
for$x(g,o,p,r){say;s/$x/ /&&redo}

```

Run with `-n0` (2 byte penalty).

Apparently, I like to eat Skittles in alphabetical order, because the program turns out shorter that way. The program doesn't really need much explanation: `-n0` reads the input implicitly (`-n` means "read input implicitly", `-0` means "don't break input on newlines"); `for$x(g..r)` runs a loop with `$x` set from each letter from `g` to `r` in turn; `say;` prints the current input, after any mutations; `s/$x/ /` replaces one copy of `$x` (specifically, the first) with a space if possible; and `&&redo` repeats the code inside the braces (without advancing the loop counter) if the replacement was successful.

This program can easily be generalized to more flavours of Skittle without changing its length, and will work with a pile of any size.

Here's an Ideone link where you can test it. (Ideone doesn't allow you to specify command-line options, so I had to add a couple of lines at the start to set `-n0` and the `-M5.010` that you get for free.)
> 4 votes

# Answer
# C#, ~~134~~ 148 bytes

Order: `G -> O -> Y -> P -> R`

```
I=>{var v=new string(I)+";\n";int i,j=0,c;for(;j<4;){c="goyp"[j++];for(i=0;i<I.Length;i++)if(I[i]==c){ I[i]='.';v+=new string(I)+";\n";}}return v;};

```

Used some similar things from @Poke's answer, currently a bit longer though since I need to convert the character array to a string ;(
> 4 votes

# Answer
# C 145 - 5 - 18 - 1 = 121 bytes

```
#define l(a)for(a=0;a<10;a++)
i,j,k,b='a';F(char a[][11]){while(b++<'x')l(i)l(j)if(a[i][j]==b){a[i][j]=32;l(k)puts(a[k]);puts("");}}

```

### ungolfed + pretty

```
#include<stdio.h>
#include<windows.h>
i,j,k;
F(char a[][11])
{
    char b='a';
    while(b++<'x')
        for(i=0;i<10;i++)
            for(j=0;j<10;j++)
                if(a[i][j]==b)
                {
                    system("cls");
                    a[i][j]=32;
                    for(k=0;k<10;k++)
                        puts(a[k]);
                    puts("");
                    Sleep(35);
                }
}
main()
{
    char a[][11]={
            "gggggggggg",
            "goooooooog",
            "goppppppog",
            "goprrrrpog",
            "gopryyrpog",
            "gopryyrpog",
            "goprrrrpog",
            "gopppppppg",
            "goooooooog",
            "gggggggggg"
    };
    for(i=0;a[i][j];)
        puts(a[i++]);
    F(a);
}

```

Here `a[][11]` means taking n-strings of length 11 where 1 char is required for termination so, technically only 10 visible chars.

**order : alphabetical**
this function checks for `'g'` in the given input and eliminates it 1/1 then increments the variable holding `'g'` until it finds a next match(probably letter `'o'`) and then eliminates those matched characters.
The downside is that this function is just too careful.So, if your skittels were of `26` different colors code-named from letters a-z, this function will handle that input too...
> 4 votes

# Answer
# Octave, 49 bytes

Eats skittles in alphabetical order, highest ascii-code first.

```
A=input("");do [~,p]=max(A(:));A(p)=32 until A<33

```
> 3 votes

# Answer
# ES6 (Javascript), ~~72~~,71 bytes

EDITS:

* Minus 1 byte, by using template literal with *of*

A non-recursive version in Javascript.

**Golfed**

```
s=>{r=s;for(c of`pogy`)while(s!=(s=s.replace(c,' ')))r+=`
`+s;return r}

```

Input and output are multiline strings, eats pills in the "purple=\>orange=\>green=\>yellow" order.

**Test**

```
S=s=>{r=s;for(c of`pogy`)while(s!=(s=s.replace(c,' ')))r+=`
`+s;return r}

console.log(
S(` org
prgrg
gggpr
oyyor
 r p `)
);
```
> 3 votes

# Answer
# Vim ~~57~~ 55 bytes

Saving two bytes by removing my line delimiter. Unfortunately it makes it a lot harder to read and check for correctness :(.

```
:set ws!
yGP/o
qqnr G9kyGGp@qq@q/y
@q/p
@q/g
@qdG

```

Unprintables:

```
:set ws!
yGP^O/o
^Oqq^Hnr G9kyGGp@qq@q/y
^O@q/p
^O@q/g
^O@qdG

```

TryItOnline

Eats in the order oypg, leaving all of the r's for the end :)
> 2 votes

# Answer
# Python 3 - ~~141~~ ~~99~~ 75 bytes

```
s=input();[exec("print(s);s=s.replace(c,' ',1);"*s.count(c))for c in'orgy']

```

Program eats skittles in this order - `Orange Red Green Yellow Purple`.

**Edit** \- Thanks to Flp.Tkc who helped to cut down 24 bytes!

```
Input -
ygro  goppr rppog rppog orgy

Output -
ygro  goppr rppog rppog orgy
ygr   goppr rppog rppog orgy
ygr   g ppr rppog rppog orgy
ygr   g ppr rpp g rppog orgy
ygr   g ppr rpp g rpp g orgy
ygr   g ppr rpp g rpp g  rgy
yg    g ppr rpp g rpp g  rgy
yg    g pp  rpp g rpp g  rgy
yg    g pp   pp g rpp g  rgy
yg    g pp   pp g  pp g  rgy
yg    g pp   pp g  pp g   gy
y     g pp   pp g  pp g   gy
y       pp   pp g  pp g   gy
y       pp   pp    pp g   gy
y       pp   pp    pp     gy
y       pp   pp    pp      y
        pp   pp    pp      y
        pp   pp    pp

```

I believe it can be further golfed as it looks very simple.
> 2 votes

# Answer
# Mathematica, 67 bytes

```
Most[#/.(i=0;#:>"."/;i++≤0&/@Characters@"ryop")&~FixedPointList~#]&

```

Eats reds, then yellows, then oranges, then purples.
> 1 votes

# Answer
# MATL, 24 bytes

```
`tDX:t2#X>wx32w(10etun2>

```

Try it online! I prefer eating my skittles in reverse alphabetical order: green is my favourite colour. Explanation:

```
                           % Take input implicitly.
`                          % Start do ... while loop
 tD                        % Duplicate skittle pile (nom!), but give away for display
   X:                      % Put skittles in long row (like normal people do)
     t2#X>                 % Get least favourite skittle name and number in the row
          wx               % Discard the skittle name
            32w            % Put an eaten skittle on the stack (ASCII 32)
               (           % Put the eaten skittle back in the row of skittles.
                10e        % Shape the row back into a 10x10 array
                   tun     % Check the number of unique skittles
                      2>   % Loop while this number >2 (eaten skittles + favourite skittles)
                           % Implicit end of do... while loop.
                           % Display last iteration implicitly, since it's still on the stack.

```
> 1 votes

# Answer
# Java 7, 125 bytes

Purple, Yellow, Green, Red, Orange. I'm enjoying that I get to pick my order in this solution. :D

## Golfed

```
String s(String p){String r=p;for(String c:"pygr".split(""))for(;p.contains(c);r+="\n\n"+p)p=p.replaceFirst(c," ");return r;}

```

## Ungolfed

```
String s(String p) {
    String r=p;
    for (String c : "pygo".split("")) {
        for (; p.contains(c); r += "\n\n" + p) {
            p = p.replaceFirst(c, " ");
        }
    }
    return r;
}

```

Try it here!

A different approach to the other Java answer by @Poke. We start by making a copy of the original string. Iterating through each color, we replace it each time it's found with a space, then append the new layout to the output string, returning after we've eaten everything but orange.

## Notes

Seperation between steps is done with a double newline `\n\n`, but if the input grid can be taken with a trailing newline at the end, it can be shorted to just `\n`.
> 1 votes

# Answer
## Haskell, 60 bytes

```
f x|(a,b:c)<-span(<maximum x)x,b>'g'=(:)<*>f$a++' ':c|1<2=[]

```

Input is a single string where the rows are separated with `,`. Return value is a list of strings with all intermediate steps. Order is alphabetically, largest first, so green remains. Usage example:

```
*Main> mapM_ putStrLn $ f " org ,prgrg,gggpr,oyyor, r p "
 org ,prgrg,gggpr,o yor, r p
 org ,prgrg,gggpr,o  or, r p
 o g ,prgrg,gggpr,o  or, r p
 o g ,p grg,gggpr,o  or, r p
 o g ,p g g,gggpr,o  or, r p
 o g ,p g g,gggp ,o  or, r p
 o g ,p g g,gggp ,o  o , r p
 o g ,p g g,gggp ,o  o ,   p
 o g ,  g g,gggp ,o  o ,   p
 o g ,  g g,ggg  ,o  o ,   p
 o g ,  g g,ggg  ,o  o ,
   g ,  g g,ggg  ,o  o ,
   g ,  g g,ggg  ,   o ,
   g ,  g g,ggg  ,     ,

```

Simple recursion. Save the input list in for the return value, replace the largest element greater `g` with a space and call the function again. Base case is when there's no element left to remove.
> 1 votes

# Answer
# QBasic, 125 bytes

Creative rules abuse!

```
DATA 71,89,82,79
?INPUT$(109)
DO
READ s
FOR r=1TO 10
FOR c=1TO 10
IF s=SCREEN(r,c)THEN SLEEP 1:LOCATE r,c:?" "
NEXT
NEXT
LOOP

```

This submission assumes a lot of things are okay:

* Input and output are uppercase (`GORPY`)
* Input is taken as 109 successive keypresses, which are not echoed to the screen until the last one is entered. At the end of each row except the last one, the user must enter a carriage return.
* Instead of printing the Skittles pile multiple times, the program displays it on the screen with a 1-second pause before each step. (QBasic doesn't have output scrollback, so printing the pile multiple times would only give you the last 2 1/2 steps. Also, this method is a much better depiction of how your pile of Skittles evolves as you eat them.)
* The program ends with an error.

I also have a 130-byte version that uses lowercase and doesn't error.

Here's a sample run in QB64, with `109` changed to `29` for a 5x5 grid:

### Explanation

`DATA 71,89,82,79` stores the ASCII codes of `G`, `Y`, `R`, and `O`.

`?INPUT$(109)` gets 109 keypresses from the user and prints them.

We then enter an infinite `DO ... LOOP` construct. Each time through, we `READ` the ASCII code of the current Skittle into `s`. Then we loop over rows and columns from 1 to 10. `SCREEN(r,c)` gets the ASCII code of the character on the screen at row `r`, column `c`. If this is equal to the current Skittle `s`, we `SLEEP` for one second and then print a space at `r`, `c`.

The main loop runs four times, removing the green, yellow, red, and orange Skittles. On the fifth iteration, `READ` errors because we're out of data.
> 0 votes

---
Tags: code-golf
---