# Question
Title: Answer-Chaining - Positive divisors of a number
*This challenge is officially over, resulting in the win of **Wheat Wizard**, with a total of 7 answers. Any other answer is welcome, but it won't influence the accepted answer for this challenge, nor the winner.*

---

# Task:

Print all the positive divisors of a number `x` taken as input.

### Input:

A single number `x` which is the number (in base 10) whose positive divisors should be computed.

### Output:

All the positive divisors of `x`. Any format is allowed, including `\n`,`,`,`;` and whitespace as separators, as long as it's understandable. The output can be an array of Integers or Strings, too (e.g: `[1, 2, 3, 5, 30]`). You may output the divisors to ***stdout, console*** or the equivalent in your language or they can be **returned from a function**.

---

# Rules

* A user may not answer twice in a row
* Your answer may remove, add or replace at most **15** characters from the previous answer (whitespace does not count), besides for ***Answer 2*** which can "transform" up to **20** characters to get things started
* You are not allowed to post an answer in a programming language that already has an answer, the exception being a *completely* different version of that language (e.g: If I post an answer in `Python 2.7`, you can submit one in `Python 3`, but not in `Python 2.6`)
* **Standard loopholes** are not allowed
* You are **not allowed to use built-ins for getting divisors**, for the sake of this challenge
* You *must* include the answer's number and the language name in the question's title and the number of characters changed from the previous answer

# Scoring

The user with the most submissions once the things settle out wins. In case of a tie, the user with the highest score on one of their answer wins. If there is a tie at the score as well, then the user with the oldest submission(oldest highest-scored answer) will be declared the winner.

*Note:* "settle out" \<=\> **~~7~~ 3 days** have passed since the last answer was submitted

---

## Examples:

```
Input, Output:

14 => [1, 2, 7, 14]
25 => [1, 5, 25]
65 => [1, 5, 13, 65]
114 => [1, 2, 3, 6, 19, 38, 57, 114]

```

Or any other equivalent output satisfying the mentioned conditions.

---

*Final Note*: This question is better if you sort the answers by the oldest. I'll post the first answer in Python 2.7, so you should post the second answer depending on that one. Good luck and have fun!

---

## Leaderboard:

This list may be outdated, fell free to edit it:

> **1)** Wheat Wizard **\[Current Leader \]**: *7 answers* \- **Python 1.6, 05AB1E, Actually, Del|m|t, WSF, Brain-Flak, Lenguage**
>
> **2)** Riley: *3 answers* \- **Seriously, CJam, 2sable**
>
> **3)** Jonathan Allan: *2 answers* \- **Python 3, Jelly**
>
> **3)** ETHproductions: *2 answers* \- **Japt, Pyth**
>
> **3)** Mistah Figgins: *2 answers* \- **Befunge-98, Brain-Flak Classic**
>
> **6)** Riker: *1 answer* \- **MATL**
>
> **6)** dzaima: *1 answer* \- **SOGL 0.8.2**
>
> **6)** LegionMammal978: *1 answer* \- **Whitespace**
>
> **6)** Nick Clifford: *1 answer* \- **Ohm**
>
> **6)** Lynn: *1 answer* \- **GolfScript**
>
> **6)** MickyT: *1 answer* \- **Cubix**

## Distance calculator

You can use this snippet to calculate the distance between two entries:

```
function L(s,t){if(s===t)return 0;var S=s.length,T=t.length;if(S*T===0)return S+T;for(var i=0,v0=[],v1=[];i<=T;i++)v0[i]=i;for(i=0;i<S;i++){v1[0]=i+1;for(var j=0;j<T;j++)v1[j+1]=Math.min(v1[j]+1,v0[j+1]+1,v0[j]+(s[i]!=t[j]));for(j=0;j<=T;j++)v0[j]=v1[j]}return v1[T]}
```

```
<textarea id=A rows=10></textarea><textarea id=B rows=10></textarea><br>
Distance: <span id=O>0</span> <button onclick="O.innerHTML=L(A.value.replace(/\s/g,''),B.value.replace(/\s/g,''))">Run</button>
```

# Answer
> 12 votes
# Answer 20, Brain-Flak, 11

I would like to just take the time to thank everyone that has helped contribute to this goal:

* Riley, 20 bytes
* LegionMammal, 15 bytes
* ETHproductions, 11 bytes
* Lynn, 1 byte

The following users were not able to contribute bytes directly but did help in other ways:

* Mistah Figgins
* DJMcMayhem
* feersum

Thanks everyone for making this possible!

```
"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw
)((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}
#R
{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï,

```

Try it online!

# Answer
> 7 votes
# Answer 3: MATL, Distance 15

```
:tGw\~)
%n=int(input())
%i=1
%div=[]
%while (i<=n):
%    if n % i == 0:
%        div.append(i)
%    i+=1
%print(div)

```

# Answer
> 7 votes
# Answer 7, Japt, 15

```
ò f!vU"Gw\((()<>))
n=int(input())
i=1
div=[]
while (i<=n):
    if n % i == 0:
        div.append(i)
    i=i+1
print(div)#Rḍ⁸T”

```

Try it online!

Changed `#b∫I:b;\?t` to `ò f!vU` (10 points) and added some more Brain-Flak code by changing `~(()` to `((()<>))` (5 points). I believe the code we're working toward is

```
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

### Explanation

```
ò           Generate the range [0...input].
  f         Filter to only items Z where
   !vU        U.v(Z) returns truthily. (`fvU` would be Z.v(U))
              This returns true if U is divisible by Z, false otherwise.
      "...  The rest of the program is enclosed in this string, which is passed as an extra
            argument to `f`. Fortunately, `f` ignores it.
            Implicit: output result of last expression

```

# Answer
> 6 votes
# Answer 8, 05AB1E, 14

```
"'ò f!vUGw\((()<>)){((({'
n=int(input())
i=1
div=[]
while (i<=n):
    if n % i == 0:
        div.append(i)
    i=i+1
print(div)
'#Rḍ⁸T”'".e

```

Try it online!

# Explanation

Luckily 05AB1E has a builtin Python interpreter (of sorts). In order to make this run we push

```
'ò f!vUGw\((()<>)){((({'
n=int(input())
i=1
div=[]
while (i<=n):
    if n % i == 0:
        div.append(i)
    i=i+1
print(div)
'#Rḍ⁸T”'

```

as a string to the top of the stack. We have to use string literals instead of comments here because 05AB1E really doesn't like comments in its Python code. We also have to get rid of the `"` in the original code because it causes the string to end prematurely.

Once the string has been pushed we use `.e` to execute it as python code.

## Work towards Brain-Flak

I was able to add 5 extra characters towards the goal of making a Brain-Flak answer. I would have been able to add 6 but alas I forgot whitespace doesn't count towards the point score.

So far we have:

```
((({})<>)){((({}     ((  )   )       (              <              )           (          )   )
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 6 votes
# Answer 13, Pyth, 15

```
f!%QTS|Q"@░┼_¥
f!vUGw((({})<>)){((({}[()]n=int(input({})(<>))i=1div=while((<>)){ifn%i==0div.append(i)i=i+1}printdiv)}#R{}T.eX
╜R;`;╜%Y*`M∩

```

Try it online!

## Explanation

So I don't know much Pyth, but what I do know is that the source code is in the form of a tree, each command taking a specific number of arguments to its right. The tree of the divisor program I wrote looks like this:

```
     f
    / \
   !   S
   |   |
   %   Q
  / \
 Q   T

```

`Q` is the input. `f` takes two arguments, `F` and `A`, and returns the items `T` in `A` where `F(T)` returns a truthy value. In this case, `F` is a function which returns the logical NOT of `Q%T`, and `A` is `SQ`, which creates the range `[1...Q]`. This has the effect of filtering to only the integers `T` in `[1...Q]` where `Q%T == 0`.

In order to avoid parsing the rest of the code, the entire thing is wrapped in a string, then `|Q"...` returns the logical OR of `Q` and the string. Since `Q` is always positive, it's always truthy, and thus always gets returned from the logical OR.

---

## Work toward Brain-Flak

```
((({})<>)){((({}[()] (({})(<>))      ((             <>                 )   )  {(          )  })}{}
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 6 votes
# Answer 16, GolfScript, 15

```
~:
),(;{
\%!},p#&f!0pv'%QTS|Q"@░┼_¥f::+!vUGw((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}<>)){ifn%i==g00div.append(i)i=i+1{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\

```

Try it online!

I added `~:␤),(;{␤\%!},p#`, using newline as a variable name to fit the size constraint, and squished the entire program back onto one line to comment it out. This was distance 14. Then, I added `{` before `}printdiv` for Brain-Flak.

```
~:␤                    Read input, store as NL
   ),(;                Range [1, 2... NL]
       {␤\%!},         Filter elements that divide NL
              p#       Print and comment everything else out

```

# Work towards Brain-Flak

```
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}     <>                 )   )  {(          ) {})}{}
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 6 votes
# Answer 17, CJam, 15

```
qd:A
),(;
{A\%!},p
e#&f!0pv'%QTS|Q"@░┼_¥f::+!vUGw((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{)){ifn%i==g00div.append(i)i=i+1{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\

```

Try it online!

```
qd:A     # Get input as decimal and store it in A
),(;     # range [0..A]
{    },  # Filter where
 A\%!    # A mod this value == 0
       p # print
e#...    # comment

```

## Work towards Brain-Flak (30 to go)

```
)({}((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{            )   )  {(          ) {})}{}
 (  (( {})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 5 votes
# Answer 4 - Jelly, 4

```
:tGw\~)
%n=int(input())
%i=1
%div=[]
%while (i<=n):
%    if n % i == 0:
%        div.append(i)
%    i+=1
%print(div)Rḍ⁸T

```

**Try it online!**

Relevant code:

```
Rḍ⁸T

```

The `)` acts as a break between links as far as the parser is concerned (I believe).

The built-in would be `ÆD`, instead this creates a range from `1` to the input with `R`, checks for divisibility by the input with `ḍ⁸`, then returns a list of the truthy one-based indexes with `T`.

# Answer
> 5 votes
# Answer 9, Whitespace, 15

```
f!vUGw((({})<>)){((({}n=int(input())i=1div=while(i<=n):ifn%i==0:div.append(i)i=i+1printdiv)}#R{}T”.e<SPACES>

```

Where `<SPACES>` is replaced by the following string, where `T` is 0x09, `L` is 0x0A, and `S` is 0x20:

```
SSSLSLSTLTTTTTSSSLLSSSLSTSSTLSTSSTLTSSTLTSSSLSSSTLTSSSSTSSTLSTSSTLTSTTLTSTLLSLSL
LSSTLSLSTLSTSSSTSTSLTLSSLSLSLLSSSSLLLL

```

Literal newline added for clarity. Noticed that the rules only specify non-whitespace characters. Nope, couldn't help myself.

## Work towards Brain-Flak

I have no idea what was going on earlier, so we now have:

```
((({})<>)){((({}     ((  )   )       (              <              )           (          )   )}{}
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 5 votes
# Answer 18, WSF, 15

```
q

    d:A(),(;{A\%!},pe#&f!0pv'%QTS|Q"@░┼_¥f::+!vUGw)(({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>){ifn%i==g00div.append(i)i=i+1{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\

```

*(This takes input and output via character code)*

## Explanation

WSF is essentially brainfuck except it uses whitespace instead of brainfuck's usual set of operators. Here is the code decompiled into brainfuck:

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

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

```

## Progress towards Brain-Flak

Since WSF is only whitespace I was able to add 15 more characters onto the Brain-Flak code. This puts us at 15 away from the answer, so feel free to post it.

```
()({})(({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})>  )  {(          ) {})}{}
()({})(({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

Since I am not going to get to post the Brain-flak answer myself, I thought I would just take the time to thank everyone that has helped contribute to this goal:

* Riley, 16 bytes
* LegionMammal, 15 bytes
* ETHproductions, 11 bytes
* Lynn, 1 byte

The following users were not able to contribute bytes directly but did help in other ways:

* Mistah Figgins

Thanks everyone for making this possible!

# Answer
> 5 votes
# Answer 19, 2sable, 15

```
"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw)(({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>){ifn%i==g00div.append(>>i)i=i+1}{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\"
ILD¹s%_Ï,

```

Try it online!

I removed the extra whitespace, wrapped everything that existed before into a string, then:

```
IL        # Push [1 .. input]
  D       # Duplicate
   ¹s%    # For each element: input % element
      _   # Logical not
       Ï  # Keep the values from [1 .. input] where this is 1
        , # print

```

# Answer
> 5 votes
# Answer 21, Cubix, 15

Finally managed to fit this in :) Thankfully it is after the Brain-Flak answer got done, because I think I would have hindered. Needed the full 15 to implement.

```
"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw
)(Is{})%?;ONou{((({}[()]<n=int(inpu;<@!-;<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}
#R
{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï,

```

This maps to the following cube

```
              " q d : A ( )
              , ( ; { A \ %
              ! } , p e # &
              f ! 0 p v ' %
              Q T S | Q @ ░
              ┼ _ ¥ f : : +
              ! v U G w ) (
I s { } ) % ? ; O N o u { ( ( ( { } [ ( ) ] < n = i n t
( i n p u ; < @ ! - ; < > ) ) > < > ) < { i = 1 d i v =
w v h i l e ( ( { } ) ) { ( { } [ ( ) ] ) < > } { } } {
} < > ( [ { } ( ) ] { } ) > < > ) < > { i f n % i = = g
0 0 d i v . a p p e n d ( < { } < > { } < > > i ) i = i
+ 1 } { } p r i n t d i v ) } # R { } T : . e X ╜ R ; j
` ; ╜ 0 % Y * ` M ∩ \ " I L D ¹ s % _ Ï , . . . . . . .
              . . . . . . .
              . . . . . . .
              . . . . . . .
              . . . . . . .
              . . . . . . .
              . . . . . . .
              . . . . . . .

```

You can try it here, but you will need to paste it in. I suspect some of the specials are causing problems for the permalink.

The code is essentially over 2 lines. The important parts are:

```
I s     ) % ? ; O N o u
        u ; < @ ! - ;

```

`I s )` This gets the input, swaps the top of the stack (0 would have worked as well) and increments
`% ?` Get the mod and test. If 0 carry on forward or drop down to the redirect
`; O N o` Drop the mod results and output the number followed by a newline
`u` U turn onto the line below
*Following is in order executed*
`; - ! @` Remove the 10 from stack, subtract number from input, test and terminate if zero
`< ; u` Redirect target for first test. Remove top of stack (either mod or subtract result) and u-turn back up to increment

# Answer
> 4 votes
# Answer 6, Python 1.6, 15

```
#b∫I:b;\?t"Gw\~(()
n=int(input())
i=1
div=[]
while (i<=n):
    if n % i == 0:
        div.append(i)
    i=i+1
print(div)#Rḍ⁸T”

```

I removed the `%` symbols and commented out the first line and a bit of the last line. This alone cost me 10 of my 15 points. However I was not yet done; since Python 1 doesn't have `+=` I had to replace `i+=1` with `i=i+1` costing me an extra 3 points. Since I had 2 left over I also added `((` to the beginning. I am planning to make a submission in Brain-Flak later and I need parens.

# Answer
> 4 votes
# Answer 10, Ohm, distance 5

```
@░┼_¥
f!vUGw((({})<>)){((({}n=int(input())i=1div=while(i<=n):ifn%i==0:div.append(i)i=i+1printdiv)}#R{}T”.e<SPACES>

```

...where `<SPACES>` is replaced by that monstrous string from the Whitespace answer.

A bit of a cheeky answer, since everything else is just a wire that lays unexecuted.

# Answer
> 4 votes
# Answer 12, Seriously, 15

```
╩"@░┼_¥
f!vUGw((({})<>)){((({}[()]n=int(input())i=1div=while((<>)){ifn%i==0div.append(i)i=i+1}printdiv)}#R{}T.e"X
╜R;`;╜%Y*`M∩

```

Try it online!

The only difference from the Actually answer is that Seriously uses backticks to mark a function where Actually uses  and  and we just make the extra characters into a string then pop and discard it.

---

## Work Towards Brain-Flak

```
((({})<>)){((({}[()] ((  )   )       ((             <>                 )   )  {(          )  })}{}
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 4 votes
# Answer 14, Del|m|t, 15

```
                                                f!%QTS|Q"@░┼_¥f!vUGw((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=while(({})){({}<>)){ifn%i==0div.append(i)i=i+1}printdiv)}#R{}T.eX╜R;`;╜%Y*`M∩

```

Try it online!

# Explanation

I am really starting to abuse the fact that whitespace is not counted towards the difference here. Del|m|t doesn't really care all that much what characters you you so the vast majority of the code is a sequence of spaces and carriage returns at the beginning of the program. The actual visible parts of the code are not executed at all.

Here is the code transcribed into a more "reasonable" fashion:

```
O R ^ V O @ A K T A J O @ A K U N R O @ B K U @ A K T Q ^ X @ B K T R ^ P O @ A K T K R ^ _ @ ^ @

```

Try it online!

### How it works at the low level

To start we have `O R ^ V` this serves to take input on the first loop and works as a no-op all other times.

We then use `O` to make a copy of the input for later.

`@ A K T` recalls the variable stored in memory position -1 (at the beginning of the program this is 0) and `A J` increments it. `O @ A K U` Stores the now incremented value back in memory position -1 for our next loop around.

`N` calculates the mod of the copy of the input we made a while back and the value just recalled from memory and `R` negates it.

Together `N R` create a boolean that indicates whether or not the our input is divisible by the TOS.

We store a copy of this boolean to memory space -2 using `O @ B K U` and recall the value from memory space -2 using `@ A K T`.

We swap the top two elements with `Q` to ensure that the boolean is on top and output the value if the boolean is true using `^ X`.

If the boolean was false we have an extra value that needs to be eradicated so we recall the boolean we stored in space -2 with `@ B K T` and pop a value if it is false `R ^ P`.

We duplicate the input value with `O` and subtract the value at memory -1 with `@ A K T K`. If this is zero we exit `R ^ _`.

Lastly we have `@ ^` this skips whatever the next value is. We need this because there is a bunch of junk (actually only a `@` symbol) generated by the visible portion of the code.

Once it reaches the end it loops back to the beginnning.

### How it works at the high level

The basic idea is that we have a value primarily stored at memory location -1 that is incremented each time we loop. If that value divides our input we output it and when the two are equal we end execution.

## Progress Towards Brain-Flak

Because whitespace does not count towards the difference I was able to change the code without spending any of my 15 points and thus all of them were invested into the Brain-Flak code.

Here is our current standing.

```
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}     <>                 )   )  {(          )  })}{}
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 4 votes
# Answer 15, Befunge-98, 15

```
&f!0pv
'         %QTS|Q" @ ░┼_¥f
:
:
+
!         vUGw(((   {})<>)){((({}[()
]    <    n=int(i   nput({})(<>))><>)
<      {i=1di     v
  =
w    v
       hile(({      })){({}<>)){ifn%i==
g
0
0    div.app   en   d(i)i=i+1}printdiv)}#R{}T
:
.    eX╜R;
j
`      ;╜
0
%  Y*`M∩
\

```

Try it Online!

(There is probably a lot of unnecessary whitespace, but I can't be bother to golf it out right now)

I used all 15 for the Befunge program, so no changes to the Brain-flak this time.

My main strategy for this was to send the IP going vertically, and using whitespace to execute certain characters from the preexisting code.

### Explanation:

The code that matters to the Befunge program is this:

```
&f!0pv
'                 @
:
:
+
!
]    <
<                 v
w    v
g
0
0    d
:
.    e
j
`
0
%    `
\

```

Which is equivalent to:

```
&f!0pv   Gets input, and stores it at (0, 0) (where the & is)
         The v goes down, hits the < and ], which turns the IP up along the first line

!+::'&   There is a 0 at the bottom of the stack, so ! changes it to a 1 and + increments
         :: duplicates twice, and '& gets the input value

\%       swaps the input and iterator mods them
  0`j.   Checks if input mod iterator is 0 - if it is, print iterator

:00gw    gets the input again, and compares it to the iterator.
         If they are different, the IP travels right to the v
         Otherwise, it continues straight, and hits arrows leading to the end (@)

de`      pushes 0, to be used in the increment line

```

# Answer
> 3 votes
# Answer 1 - Python 2.7

```
n=input()
i=1
div=[]
while (i<=n):
    if n % i == 0:
        div.append(i)
    i+=1
print(div)

```

Distance: ***NA*** \- First answer

**Try it online!**

# Answer
> 3 votes
# Answer 2 - Python 3, 5

```
n=int(input())
i=1
div=[]
while (i<=n):
    if n % i == 0:
        div.append(i)
    i+=1
print(div)

```

**Try it online!**

# Answer
> 3 votes
# Answer 5 - SOGL 0.8.2, 9

```
b∫I:b;\?t"Gw\~)
%n=int(input())
%i=1
%div=[]
%while (i<=n):
%    if n % i == 0:
%        div.append(i)
%    i+=1
%print(div)Rḍ⁸T”

```

Explanation:

```
b∫              repeat input times                [0]
  I             increment (the loop is 0-based)   [1]
   :b           duplicate                         [1, 1]
     ;          put the input one under the stack [1, 114, 1]
      \?        if divides                        [1, 1]
        t        output                           [1, 1]
         "...”   push that long string            [1, 1, "Gw\~...Rḍ⁸T"]

```

Note: the interpreter currently needs the `\n`s be replaced with  in order to not count it as input, but the parser itself considers both interchangable.

# Answer
> 3 votes
# Answer 11, Actually, 15

```
╩@░┼_¥
f!vUGw((({})<>)){((({}]n=int(input())i=1div=while(i<=n):ifn%i==0:div.append(i)i=i+1printdiv)}#R{}T”.e
╜R;⌠;╜%Y*⌡M∩

```

Try it online!

## Explanation

Actually has a nice builtin `÷` for finding the factors of a number, however we are not allowed to use such builtins.

I begin by storing the input to the registers so that it will be unharmed by what is to come. I do this using  but I could have just as easily used one of the other commands available.

Then I paste the code we already had (I removed all the whitespace because it was annoying to work with, I can do this because "whitespace does not count"). Luckily this does a whole lot of nothing when the stack is empty.

Then we have the rest of the program

```
╜   Pull our input from the register
R   Create the range of n
;   Duplicate the range
⌠   Declare a function
 ;  Duplicate n
 ╜  Pull from register
 %  Mod
 Y  Logical not
 *  Multiply by n
⌡   End Function
M   Map the function across the range
∩   Remove the zeros with a Intersection

```

## Work Towards Brain-Flak

All that work and I was only able to get one extra paren in.

```
((({})<>)){((({}   ] ((  )   )       (              <              )           (          )   )}{}
((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{(<{}<>{}<>>)}{})}{}

```

# Answer
> 3 votes
# 23, Brain-Flak Classic, 13

```
"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw)(Is(({})<>))%?;ONou{((({}[]<n=int(inpu;({})(@!-;<>))><>)<{i=1div=wvhile(({})){({}[])<>}{}}{}<>({<({}[])>[]}[]{}{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï,

```

Originally, @Wheat Wizard had posted the brain-flak-classic code as it was on answer 22:

```
()({})((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>({<({}[]{})           ><>)<>{(<{}<>{}<>>)}{})}{}
()({})((({})<>)){((({}[  ]<(({})(<>))><>)<{(({})){({}[  ])<>}{}}{}<>({<({}[]  )>[]}[]{}{})><>)<>{(<{}<>{}<>>)}{})}{}

```

This is 17 characters off. However, I was able to compress this by simply moving the `{})` further right in the proposed code to get

```
()({})((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>({<({}[]         {})><>)<>{(<{}<>{}<>>)}{})}{}
()({})((({})<>)){((({}[  ]<(({})(<>))><>)<{(({})){({}[  ])<>}{}}{}<>({<({}[])>[]}[]{}{})><>)<>{(<{}<>{}<>>)}{})}{}

```

Which is only 13 characters off! So all I did was add/remove brackets to get the proposed code.

---

The original code I posted had a typo, it's fixed now. (Thanks @WheatWizard!)

# Answer
> 1 votes
# 22, Lenguage, 15

Lenguage is a esolang that cares only about how long the program is not about its content. So we can create any lenguage program we want by padding the last program with the proper amount of whitespace. Lenguage is compiled into brainfuck so we will reuse the brainfuck program I wrote a while ago

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

```

I made a few changes to the main program to facilitate later answers, but the end result looks like:

```
<SPACES>"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw)(Is(({})<>))%?;ONou{((({}[()]<n=int(inpu;({})(@!-;<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>({<[{}[]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}#R{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï,

```

where `<SPACES>` represents *55501429195173976989402130752788553046280971902194531020486729504671367937656404963353269263683332162717880399306* space characters.

Am I abusing the whitespace doesn't count rule? Perhaps.

# Work towards Brain-Flak Classic

We had all of those parens already there so I thought I would start us along the way towards Brain-Flak Classic.

```
()({})((({})<>)){((({}[()]<(({})(<>))><>)<{(({})){({}[()])<>}{}}{}<>({<({}[]         {})><>)<>{(<{}<>{}<>>)}{})}{}
()({})((({})<>)){((({}[  ]<(({})(<>))><>)<{(({})){({}[  ])<>}{}}{}<>({<({}[])>[]}[]{}{})><>)<>{(<{}<>{}<>>)}{})}{}

```

---
Tags: math, number, arithmetic, answer-chaining
---


title: Make a Bubble-wrap simulator

text:
# Question
Title: Make a Bubble-wrap simulator
Bubble-wraps are maximum-level entertainment. Everyone can agree to that.

Now, you will make even computers enjoy bubble-wraps.

# Specs

You will be given two integers, w, and h.(each are responsively width and height)

Your program should output all w\*h phases waiting 1 second between each one and terminate.

Every bubble-wrap starts with all cells full.

For example, a 4\*6 bubble-wrap starts like:

```
O_O_
_O_O
O_O_
_O_O
O_O_
_O_O

```

And each phase, a random non-popped cell is popped.For example,

```
O_O_
_O_O
O_X_
_O_O
O_O_
_O_O

```

The program should terminate when all the cells are popped. aka.

```
X_X_
_X_X
X_X_
_X_X
X_X_
_X_X

```

# Examples

```
(4,6)
(5,5)
(6,2)
(10,10)
(7,9)

```

# Answer
> 7 votes
# C (Windows), ~~260~~ 248 bytes

```
#import<windows.h>
i,j,l,r;b(w,h){char*s=malloc(l=w*h+h);for(i=h;i--;*s++=10)for(j=w;j--;*s++=i%2^j%2?79:45);*(s-1)=0;s-=l;for(srand(time(0));j>system("cls")+puts(s)-2;j>-1?s[j]=88:0)for(Sleep(1000),r=rand(),j=-2,i=r+l*2;--i-r;j=s[i%l]==79?i%l:j);}

```

# Answer
> 5 votes
# Python 3, ~~222~~ 220 bytes

This is my first time answering, so please be gentle (and point out mistakes that I have made).

```
import time,random as t
def f(c,r):
 p=print;a='0_'*c;d=((a[:c]+'\n'+a[1:c+1]+'\n')*r)[:-~c*r]
 for i in[1]*((r*c+r%2*c%2)//2):
  p(d);k=1
  while d[k]!='0':k=t.randrange(len(d))
  d=d[:k]+'X'+d[k+1:];time.sleep(1)
 p(d)

```

Try it online!

How it works:

1. Chain a lot of '0\_''s together
2. Chop into '0\_0\_...\n' and '\_0\_0...\n' parts and concatenate
3. Generate random indices until the char at the index is a '0'
4. Create new string with the char at the generated index is replaced with a 'X' (Damn you python for non-mutable strings!)
5. Repeat `r*c+r%2*c%2` times: There are `r*c` bubbles in the pattern, unless r and c are both odd, in which case there are `r*c+1`.

# Answer
> 4 votes
# MATL, 37 bytes

```
:!i:+o`T&Xxt3:q'_OX'XEcD2y1=ft&v1Zr(T

```

The upper-left corner is always an underscore (allowed by the challenge).

The screen is cleared between phases. I could save a byte by not clearing the screen, but it looks better this way.

The program exits with an error (allowed by default) after displaying all phases.

Try it at **MATL Online!** (If it doesn't work after a couple of seconds, please refresh the page and try again).

# Answer
> 4 votes
## Mathematica (145 bytes)

Anonymous function, takes height and width as input (in that order — if that's a problem, replace `{##}` with `{#2,#}` in the middle of the code for an extra 2 bytes).

Code:

```
Monitor[Do[Pause@1,{i,NestList[RandomChoice@StringReplaceList[#,"O"->"X"]&,""<>Riffle["_"["O"][[Mod[#+#2,2]]]&~Array~{##},"
"],Floor[##/2]]}],i]&

```

Explanation:

* `""<>Riffle[Array["_"["O"][[Mod[#+#2,2]]]&,{##}],"\n"]` creates the initial, unpopped bubble-wrap, by making an array of "\_"s and "O"s and then StringJoining them between newlines.
* `NestList[RandomChoice@StringReplaceList[#,"O"->"X"]&,..., Floor[##/2]]` repeatedly chooses one of the "O"s to replace with an "X", as many times as there are "O"s (which is Floor\[width * height / 2\] — thanks to @JonathanAllan for the idea of putting "\_" instead of "O" in the top left corner, otherwise this would be `Ceiling` instead and thus 2 bytes more).
* `Monitor[Do[Pause@1,{i,...}],i]` makes `i` take the values in the list we just calculated, for 1 second each, and dynamically prints `i`.

Example output:

# Answer
> 3 votes
# Jelly, ~~30~~ 29 bytes

```
=”OTX
+þ⁹++µị⁾_OYµṄœS1”XÇ¦µÐL

```

Calls the link as a dyad with the program arguments and then quits with a message (the code for which is `çṛ“\'=ṙMḋḌẓ(ėo»`)

*Nuance:* the bottom-right "cell" will always be a bubble (rather than the top-left like the example in the question), this is to ensure that when all bubbles are popped the random choice returns 0 which will be the `"X"` at the end of the list - replacing that then makes no change to the value and breaks the loop.

*Note:* does not clear the screen (was not specified, and I'm not sure how to do so).

### How?

```
=”OTX - Link 1, choose a random O index or 0: string   e.g. "_O_\nX_O"
 ”O   - "O"
=     - equals (vectorises over the string)            e.g. [0,1,0,0,0,0,1]
   T  - truthy indexes                                 e.g. [2,7]
    X - random choice (if empty this returns 0)

+þ⁹++µị⁾_OYµṄœS1”XÇ¦µÐL - Main link: w, h              e.g. 3, 2
                        - left argument (implicit), w  e.g. 3
  ⁹                     - right argument, h            e.g. 2
 þ                      - outer product with
+                       -     addition                 e.g. [[2,3,4],[3,4,5]]
                        - left argument (implicit), w  e.g. 3
   +                    - add                          e.g. [[5,6,7],[6,7,8]]
                        - right argument (implicit), h e.g. 2
    +                   - add                          e.g. [[7,8,9],[8,9,10]]
     µ                  - monadic chain separation
       ⁾_O              - "_O"
      ị                 - index into (1-based & mod)   e.g. [['_','O','_'],['O','_','O']]
                        -     note: the additions above assure the last entry is an 'O'.
          Y             - join with line feeds         e.g. ['_','O','_','\n','O','_','O']
           µ        µ   - monadic chain separations
                     ÐL - loop until the results are no longer unique:
            Ṅ           -     print with a trailing line feed and yield
             œS1        -     sleep for 1 second and yield
                   ¦    -     apply to index
                  Ç     -         given by calling the last link (1) as a monad
                        -                 (a random O index or 0 if none exists)
                ”X      -         an "X"  (      ... which will be an X already)

```

# Answer
> 2 votes
# Scala, 764 bytes

```
object B{
  def main(a: Array[String]):Unit={
    val v=false
    val (m,l,k,r,n)=(()=>print("\033[H\033[2J\n"),a(0)toInt,a(1)toInt,scala.util.Random,print _)
    val e=Seq.fill(k, l)(v)
    m()
    (0 to (l*k)/2-(l*k+1)%2).foldLeft(e){(q,_)=>
      val a=q.zipWithIndex.map(r => r._1.zipWithIndex.filter(c=>
        if(((r._2 % 2) + c._2)%2==0)!c._1 else v)).zipWithIndex.filter(_._1.length > 0)
      val f=r.nextInt(a.length)
      val s=r.nextInt(a(f)._1.length)
      val i=(a(f)._2,a(f)._1(s)._2)
      Thread.sleep(1000)
      m()
      val b=q.updated(i._1, q(i._1).updated(i._2, !v))
      b.zipWithIndex.map{r=>
        r._1.zipWithIndex.map(c=>if(c._1)n("X")else if(((r._2 % 2)+c._2)%2==0)n("O")else n("_"))
        n("\n")
      }
      b
    }
  }
}

```

### How it works

The algorithm first fills a 2D Sequence with false values. It determines how many iterations (open boxes) exist based on the command line arguments put in. It creates a fold with this value as the upper bound. The integer value of the fold is only used implicitly as a way to count how many iterations the algorithm should run for. The filled sequence we created previously is the starting sequence for the fold. This is used in generating a new 2D sequence of false values with their cooresponding indecies.

For example,

```
[[false, true],
 [true, false],
 [true, true]]

```

Will be turned into

```
[[(false, 0)], [(false, 1)]]

```

Note that all lists that are completely true (have a length of 0) are omitted from the result list. The algorithm then takes this list and picks a random list in the outermost list. The random list is chosen to be the random row we pick. From that random row, we again find a random number, a column index. Once we find these two random indices, we sleep the thread we are on for 1000 miliseconds.

After we're done sleeping, we clear the screen and create a new board with a `true` value updated in the random indices we have created.

To print this out properly, we use `map` and zip it with the index of the map so we have that in our context. We use the truth value of the sequence as to whether we should print an `X` or either an `O` or `_`. To chose the latter, we use the index value as our guide.

### Interesting things to note

To figure out if it should print an `O` or an `_`, the conditional  `((r._2 % 2) + c._2) % 2 == 0` is used. `r._2` refers to the current row index while `c._2` refers to the current column. If one is on an odd row, `r._2 % 2` will be 1, therefore offsetting `c._2` by one in the conditional. This ensures that on odd rows, columns are moved over by 1 as intended.

Printing out the string `"\033[H\033[2J\n"`, according to some Stackoverflow answer I read, clears the screen. It's writing bytes to the terminal and doing some funky stuff I don't really understand. But I've found it to be the easiest way to go about it. It doesn't work on Intellij IDEA's console emulator, though. You'll have to run it using a regular terminal.

Another equation one might find strange to see when first looking at this code is `(l * k) / 2 - (l * k + 1) % 2`. First, let's demystify the variable names. `l` refers to the first arguments passed into the program while `k` refers to the second one. To translate it, `(first * second) / 2 - (first * second + 1) % 2`. The goal of this equation is to come up with the exact amount of iterations needed to get a sequence of all X's. The first time I did this, I just did `(first * second) / 2` as that made sense. For every `n` elements in each sublist, there are `n / 2` bubbles we can pop. However, this breaks when dealing with inputs such as `(11 13)`. We need to compute the product of the two numbers, make it odd if it's even, and even if it's odd, and then take the mod of that by 2. This works because rows and columns that are odd are going to require one less iteration to get to the final result.

`map` is used instead of a `forEach` because it has less characters.

### Things that can probably be improved

One thing that really bugs me about this solution is the frequent use of `zipWithIndex`. It's taking up so many characters. I tried to make it so that I could define my own one character function that would just perform `zipWithIndex` with the value passed in. But it turns out that Scala does not allow an anonymous function to have type parameters. There is probably another way to do what I'm doing without using `zipWithIndex` but I haven't thought too much about a clever way to do it.

Currently, the code runs in two passes. The first generates a new board while the second pass prints it out. I think that if one were to combine these two passes into one pass, that would save a couple of bytes.

This is the first code golf I've done so I'm sure there is a lot of room for improvement. If you'd like to see the code before I optimized for bytes as much as possible, here it is.

# Answer
> 1 votes
## JavaScript (ES6), ~~246~~ 229 bytes

```
document.write(`<pre id=o></pre>`)
setInterval(_=>{(a=o.innerHTML.split(/(O)/))[1]?a[Math.random()*~-a.length|1]=`X`:0;o.innerHTML=a.join``},1e3)
f=(w,h)=>o.innerHTML=[...Array(h)].map((_,i)=>`O_`.repeat(w+h).substr(i,w)).join`
`
```

```
<div oninput=f(+w.value,+h.value)><input id=w type=number min=1><input id=h type=number min=1>
```

# Answer
> 1 votes
# Python - 290 bytes

I've never done one of these before - so any constructive criticism would be appreciated :)

Main trick here is just annoyingly nested list comprehensions. I could save a few characters by not having a newline between the pops but that just looks ugly.

```
r=range
q=print
import random as n,time
def f(H,W):
    def p(b):
        q("\n".join(["".join(["O"if(i,j)in b else"X"if(i,j)in X else"_"for j in r(H)])for i in r(W)]));time.sleep(1);q()
    b=[(i,h)for h in r(H)for i in r(h%2,W,2)];n.shuffle(b);X=[]
    while len(b)>0:
        p(b);X+=[b.pop()]
    p(b)

```

# Answer
> 1 votes
# Charcoal, ~~49~~ ~~46~~ 39 bytes (noncompeting)

```
ＵＯＮＮO_¶_OＡＫＡαＡ№αOβＨＷψβ«Ａ§α§⌕ＡαO‽βXＡ№αOβ

```

## Verbose

```
Oblong(InputNumber(), InputNumber(), "O_\n_O")
Assign(PeekAll(), a)
Assign(Count(a, "O"), b)
RefreshWhile (k, b) {
    AssignAtIndex(a, AtIndex(FindAll(a, "O"), Random(b)), "X")
    Assign(Count(a, "O"), b)
}

```

# Answer
> 1 votes
# APL (Dyalog), ~~61~~ 59 bytes

```
⎕←m←'O_'[2|-/¨⍳⎕]
(b/,m)[?+/b←'O'=,m]←'X'
⎕DL 1
→2/⍨'O'∊⎕←m

```

`⎕←` output
`m←`*m*, where *m* is
`'O_'[``]` these characters indexed by…
`2|` the division-remainder-when-divided-by-two of
`-/¨` the difference between each of
all the coordinates (indices) in an array of shape
numeric input (the number of rows and columns)

`(``)[``]←'X'` assign the character X to one of the…
`b/` filtered-by-*b* (to be defined)
`,m` raveled elements of m, specifically…
`?` a random element (lit. number) in the range one to
`+/` the sum of
`b←`*b*, where *b* is
`'O'=` Boolean for where the letter equals
`,m`*m* raveled

`⎕DL 1`**D**e**l**ay one second

`→2` Go to line 2
`/⍨` if (lit. filtered by)
`'O'∊` whether the letter is a member of
`⎕←m` the outputted value, where the outputted value is *m*

Try it online!

---

From version 16.0 it will be shorter:

`{0::→⋄'X'@(⊂(?∘≢⊃⊢)⍸'O'=⍵⊣⎕DL 1)⊢⎕←⍵}⍣≡'O_'[2|-/¨⍳⎕]`

# Answer
> 1 votes
# Python 3, ~~195~~ 188 bytes

```
import time,random
def f(w,h):
 a=bytearray(b'0-'*w*h);b=[*range(0,w*h,2)];random.shuffle(b);
 while 1:print(*(a.decode()[w*i:w*i+w]for i in range(h)),sep='\n');a[b.pop()]=88;time.sleep(1)

```

Using `bytearray` and `decode` seems to be shorter than slicing and reassembling a string a la `a[:i]+'X'+a[i+1:]`.

```
import time,random
def f(w,h):
 x=[*range(1,h*w,2)];random.shuffle(x)
 while 1:
  for i in range(w*h):
   print('-X0'[(i%w%2!=i//w%2)+(i in x)],end='\n'[i%w<w-1:])
  print();time.sleep(1);x.pop()

```

# Answer
> 0 votes
# Java 7, 317 bytes

```
void c(int w,int h)throws Exception{String r="";int x=0,j=0,i;for(;j++<h;x^=1,r+="\n")for(i=0;i<w;r+=(i+++x)%2<1?"_":"O");for(System.out.println(r);r.contains("O");System.out.println(r=r.substring(0,x)+'X'+r.substring(x+1))){Thread.sleep(1000);for(x=0;r.charAt(x)!='O';x=new java.util.Random().nextInt(r.length()));}}

```

**Explanation:**

```
void c(int w, int h) throws Exception{                     // Method with two integer parameters (throws Exception is required for the Thread.sleep)
  String r = "";                                           //  String we build to print
  int x=0, j=0, i;                                         //  Some temp values and indexes we use
  for(; j++<h;                                             //  Loop over the height
      x^=1,                                                //    After every iteration change the flag `x` every iteration from 0 to 1, or vice-versa
      r += "\n")                                           //    And append the String with a new-line
    for(i=0; i<w;                                          //   Inner loop over the width
        r += (i++ + x)%2 < 1 ? "_" : "O")                  //    Append the String with either '_' or 'O' based on the row and flag-integer
    ;                                                      //   End inner width-loop (implicit / no body)
                                                           //  End height-loop (implicit / single-line body)
  for(                                                     //  Loop
    System.out.println(r);                                 //   Start by printing the starting wrap
    r.contains("O");                                       //   Continue loop as long as the String contains an 'O'
    System.out.println(r=                                  //   Print the changed String after every iteration
        r.substring(0,x)+'X'+r.substring(x+1))){           //    After we've replaced a random 'O' with 'X'
      Thread.sleep(1000);                                  //   Wait 1 second
      for(x=0; r.charAt(x) != 'O';                         //   Loop until we've found a random index containing still containing an 'O'
          x = new java.util.Random().nextInt(r.length()))  //    Select a random index in the String
      ;                                                    //   End loop that determines random index containing 'O' (implicit / no body)
  }                                                        //  End loop
}                                                          // End method

```

**Test gif (4,6)**

# Answer
> 0 votes
## Perl, 148 bytes

146 bytes of code + `-pl` flags.

```
$_=O x($x=$_+1);s/O\K./_/g;for$i(1..($y=<>)){$b.=($i%2?$_:_.s/.$//r).$/}}print$_="\e[H$b";while(/O/){$r=0|rand$y*$x+3;s/.{$r}\KO/X/s||redo;sleep 1

```

To run it:

```
perl -ple '$_=O x($x=$_+1);s/O\K./_/g;for$i(1..($y=<>)){$b.=($i%2?$_:_.s/.$//r).$/}}print$_="\e[H$b";while(/O/){$r=0|rand$y*$x+3;s/.{$r}\KO/X/s||redo;sleep 1' <<< "6
4"

```

# Answer
> 0 votes
# MATLAB (R2016b), 172 bytes

**Code:**

```
x=input('');m=[eye(x(2),x(1)) ''];m(:)='O';m(1:2:end,2:2:end)='_';m(2:2:end,1:2:end)='_';o=find(m=='O');r=o(randperm(nnz(o)));disp(m);for i=r';pause(1);m(i)='X';disp(m);end

```

Recommendations are always welcome! Try it online!

**Program Output:**

**Explanation:**

```
x = input( '' );                    % Input
m = [ eye( x( 2 ), x( 1 ) ) '' ];   % Character Matrix
m( : ) = 'O';                       % Fill Matrix with "Bubbles"

m( 1:2:end, 2:2:end ) = '_';        % Alternate Spaces Between Bubbles (Part 1)
m( 2:2:end, 1:2:end ) = '_';        % Alternate Spaces Between Bubbles (Part 2)

o = find( m == 'O' );               % Index Bubble Locations
r = o( randperm( nnz( o ) ) );      % Randomize Bubble Locations

disp( m );                          % Display Initial Bubble Wrap Phase

for i = r'
    pause( 1 );                     % Pause for 1 Second
    m( i ) = 'X';                   % Pop Bubble
    disp( m );                      % Display Subsequent Bubble Wrap Phase
end

```

---
Tags: code-golf, ascii-art, random, animation
---


title: Print 'em goats

text:
# Question
Title: Print 'em goats
*Related*

Goats are great. Everybody loves goats.

And they also, for some reason, are an excellent complex ascii art for many languages to have built-ins for. Because of this, I personally feel a catalogue to document just how easily a language can print goats is greatly needed.

## The Challenge

Given an integer input via any means print that many Goats separated by Newlines.

Your Goat for reference is:

```
  ___.
 //  \\
((   ''
 \\__,
/6 (%)\,
(__/:";,;\--____----_
;; :';,:';`;,';,;';`,`_
  ;:,;;';';,;':,';';,-Y\
   ;,;,;';';,;':;';'; Z/
   / ;,';';,;';,;';;'
  / / |';/~~~~~\';;'
 ( K  | |      || |
  \_\ | |      || |
   \Z | |      || |
      L_|      LL_|
      LW/      LLW/

```

Your particular goat may have more whitespace around it, if required.

## Example

Given `3` on input, Output:

```
  ___.
 //  \\
((   ''
 \\__,
/6 (%)\,
(__/:";,;\--____----_
;; :';,:';`;,';,;';`,`_
  ;:,;;';';,;':,';';,-Y\
   ;,;,;';';,;':;';'; Z/
   / ;,';';,;';,;';;'
  / / |';/~~~~~\';;'
 ( K  | |      || |
  \_\ | |      || |
   \Z | |      || |
      L_|      LL_|
      LW/      LLW/
  ___.
 //  \\
((   ''
 \\__,
/6 (%)\,
(__/:";,;\--____----_
;; :';,:';`;,';,;';`,`_
  ;:,;;';';,;':,';';,-Y\
   ;,;,;';';,;':;';'; Z/
   / ;,';';,;';,;';;'
  / / |';/~~~~~\';;'
 ( K  | |      || |
  \_\ | |      || |
   \Z | |      || |
      L_|      LL_|
      LW/      LLW/
  ___.
 //  \\
((   ''
 \\__,
/6 (%)\,
(__/:";,;\--____----_
;; :';,:';`;,';,;';`,`_
  ;:,;;';';,;':,';';,-Y\
   ;,;,;';';,;':;';'; Z/
   / ;,';';,;';,;';;'
  / / |';/~~~~~\';;'
 ( K  | |      || |
  \_\ | |      || |
   \Z | |      || |
      L_|      LL_|
      LW/      LLW/

```

## The Rules

* You must take an integer input where `0 < input < 256`, and print that many goats.
* Goats may vary in whitespace, as long as the shape of the goat is the same.
* You must submit a full program.
* This is a catalogue, so any language or language version newer than the challenge is acceptable. Like usual, creating a language that prints `N` goats in `0` bytes isn't incredibly creative. Also, as this is a catalogue, no answer will be accepted.
* This is however , so shortest answer per language.
* If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

## The Catalogue

*Shamelessly stolen from The Hello World Challenge*

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
/* Configuration */

var QUESTION_ID = 107765; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 58375; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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="language-list">
  <h2>Shortest Solution 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>
<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>
<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
## Ruby (2.3), 312 bytes

Hey, at least I didn't use a built-in!

```
n=gets.to_i
puts "
  ___.
 //  \\\\
((   ''
 \\\\__,
/6 (%)\,
(__/:\";,;\--____----_
;; :';,:';`;,';,;';`,`_
  ;:,;;';';,;':,';';,-Y\\
   ;,;,;';';,;':;';'; Z/
   / ;,';';,;';,;';;'
  / / |';/~~~~~\\';;'
 ( K  | |      || |
  \\_\\ | |      || |
   \\Z | |      || |
      L_|      LL_|
      LW/      LLW/\n"*n

```
> 9 votes

# Answer
# Jelly,  ~~194~~  191 bytes

-3 replacing `b24ị` with  (a since-developed atom)

```
“wɦLż8ßȧṛ Ỵ?þġÐ®ạSḍọsñL1⁶ƁṄṫȥẊ`m®Ø⁼ƒ⁺Ė6⁺oHpæİṇµ\ṅṁ⁷V⁶k¡i£}ḣọSƑṭ<ḃṚSØ:kŒxṘıquṂUnƭ⁾DEØẓ×ðH¦ḅċ5pðḳṅ⁶Ḅḍ€®85ɲPp¦Ø0B¥=ẊCƲ<7eØ7ƥ÷8¡ÆḅẎṣṂ(hþẓ]ƲƤȦE¶ƙCɼƭżÆµėṙṾḞ\&O ¬ṆñKmɠ’ṃ“ .¶/\(',6%):";-`YZ|~KLW_”Ṅ¡’

```

**Try it online!**

### How?

The 24 distinct characters from which the goat is constructed are:
`.¶/\(',6%):";-`YZ|~KLW_`
where  represents a line feed, and the first character is a space.

A goat may now be thought of as a 277 digit base 24 number, G, where each digit represents the 1-based and mod-24 index of a character in the above list.

The code forms G using base 250, transforms G to a base 24 representation as a list of digits and indexes into the character set. It then repeats an instruction to print the resulting character array and a line feed `n-1` times.

```
a long string of bytes
  |
“...’ṃ“ .¶/\(',6%):";-`YZ|~KLW_”Ṅ¡’ - Main link: n
“...’                               - make G using base 250
      “ .¶/\(',6%):";-`YZ|~KLW_”    - the characters of a goat, ¶ being a line feed
     ṃ                              - base decompression (use the 24 characters as the base 24 digits)
                                  ’ - decrement n to give n-1
                                 ¡  - repeat the previous link n-1 times
                                Ṅ   - print the result and a line feed

```

The only slight complication is that Jelly's base 250 representation is 1-based and the indexing is modular, so when a zero digit is present it will be a 250 digit - the remedy is to reduce the next most significant digit by 1, and repeat if that becomes a zero. (This occasionally will make for shorter code, but not this time.)
> 6 votes

# Answer
## JavaScript (ES6), 306 bytes

Some slightly compressed goats...

```
[..."abcdefghijklmnopqrs"].map((c,i)=>s=s.split(c).join(`
 jnk me|h--~~|omLqq
r__pr,; |rr';  \\`.substr(i*2,2)),s=`rl_.a//rss
((r ''assl,
/6 (%)s,
(l/:";nsfllff_
;; :q,:q\`;,qnq\`,\`_k;:n;b':,j,-Ysc;nnb':;j Z/c/ ;,bqnq;'k/ /oq/gg~sq;'a( Krhdks_soodcsZood
i_|iL_|
iW/iLW/
`)&&console.log(s.repeat(prompt()))
```
> 2 votes

# Answer
# RProgN, 16 bytes

```
"goat " read m C

```

I assume this is the answer you've been waiting for...

Try it online!
> 2 votes

# Answer
# SOGL, 174 bytes

```
▼īj-ηī¤ķJφB╝║α$a3╬ο'Βw)woE;@ē¹█lα.⁶↓!mΙ;┌.}γ§⁹≡r³╝╚wΓδΘργ±:⁾▓√׀⅝╝█%čczgΧMθL`«UΓ║νZ█č└sΩ±⅛mΤCρ2o¦≠]ΖøΙΧ²`žB+9‰κ╚¦¤Ƨ¹≥ΗxƧWJ∞┐∑¹±YEōΟ№Χθ≥⁹~E∞θ<a∙λy⌠s⁹░WP≡Φ╝∆~λ?(l$′Ζŗ=Κ╗2Ψ⁄>τ-‘*

```

vary simple (from the outside)

```
...‘   push that string decompressed
    *  multiply by input

```

I had to chop the goat up into pieces of strings that each when compressed is as small as possible, which then get each compressed and joined together. more info
> 2 votes

# Answer
## Lua, 306 bytes

`:rep()`'s `io.read()` times.

```
print(([[  ___.
 //  \\
((   ''
 \\__,
/6 (%)\,
(__/:";,;\--____----_
;; :';,:';`;,';,;';`,`_
  ;:,;;';';,;':,';';,-Y\
   ;,;,;';';,;':;';'; Z/
   / ;,';';,;';,;';;'
  / / |';/~~~~~\';;'
 ( K  | |      || |
  \_\ | |      || |
   \Z | |      || |
      L_|      LL_|
      LW/      LLW/
]]):rep(io.read()))

```
> 1 votes

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


title: Shortest code that throws SIGBUS

text:
# Question
Title: Shortest code that throws SIGBUS
We've had challenges for SIGSEGV and SIGILL so why not...

Write the shortest code that results in a **Bus Error (SIGBUS)** in any programming language.

Your program can't call `raise()` or `kill(getpid(),sig)` or `pthread_kill(pthread_self(),sig)`, or any other equivalent.

# Answer
> 6 votes
# x86\_64 bytecode, 15 bytes

```
   0:   c7 04 24 00 00 04 00    movl   $0x40000,(%rsp)
   7:   9d                      popfq
   8:   8b 04 25 01 00 00 00    mov    0x1,%eax

```

Turns on the misaligned address trap flag and then immediately triggers it.

---
Tags: code-golf
---


title: Exit Code Golfing

text:
# Question
Title: Exit Code Golfing
Inspired by this default for IO.

## The Task

Write a program that, given an input integer `x` between 0 and 255, crashes with exit code `x`.

## Restrictions

* You may not call anything which is intended directly for exit code output (`System.exit(x)`, returning from `main`, etc.). Instead, your program must cause an error or crash which will cause, with a probability of 1, the program to exit with the input integer.
    + In this case, the words "error" and "crash" means that the program caused some fatal unintended exception, wherein a method, operation or otherwise was used incorrectly that caused an irreversible failure.
    + You may not directly cause the error by throwing it directly. You must cause it by using a method, function, or otherwise whose purpose serves a different function (i.e. attempting to execute a file write to a read-only directory).
* You must have at least two exit codes accounted for in your program.
* Termination of the process with the use of signals is banned. (Reasoning may be found in this discussion)

## Scoring

Your program's score is determined by the number of supported exit codes, where code concision is tiebreaker. The greatest number of supported exit codes wins!

# Answer
# Unix Shell (+ncurses +BSD utilities), ~~36~~, 26 bytes, 256 exit codes

**Golfed**

```
jot -bu0 $[252+$1]|tput -S

```

> If the -S option is used, tput checks for errors from each line, and if any errors are found, will set the exit code to 4 plus the number of lines with errors. If no errors are found, the exit code is 0. No indication of which line failed can be given so exit code 1 will never appear. Exit codes 2, 3, and 4 retain their usual interpretation.

Once the *tput* exit code goes over 255, it just overflows, so 253 (errors on input) will result in the exit code of 1 e.t.c., thus yielding the desired exit status for the whole range of inputs.

*Note*: whether *tput* will fail on not, when setting/getting a particular capability, depends on the terminal type, I've used: `xterm with 256 colors`

jot is a *BSD* utility, which prints sequential or random data, and (AFAIK) is also available out of the box on OSX systems.

If your system does not have `jot` available, you can use a slightly longer (29 bytes) version:

```
yes u0|sed $[252+$1]q|tput -S

```

Try It Online ! (the 29 bytes version)
> 48 votes

# Answer
# Bash 4.2 + extras, 24 exit codes

```
grep \#$1$ $0|sed 's:#.*::;s:T:tcc -run -<<<main=:;s:C:curl -L x.org/! :'|sh;exit
man#1
C-#2
C/#3
sed#4
C-x/#5
C_#6
C0#7
man /#16
C-f#22
C-o/#23
C-L3#35
C--capath /#60
C--max-filesize 1#63
C--cacert /#77
timeout 1e-9 w#124
/#126
-#127
T6\;#132
T204\;#133
$[2**63%-1]#136
{0..1000000000}#137
T0\;#139
exit _#255

```

*Thanks to @KenY-N for 3 exit codes. Thanks to @el.pescado for 1 exit code.*

### Verification

All tests have been performed on openSUSE 13.2.

```
$ for n in {0..255}; do bash exit.sh $n; (($? == $n)) && echo $n >&0; done &> /dev/null
0
1
2
3
4
6
7
16
22
23
35
60
63
77
124
126
127
132
133
136
137
139
255

```
> 46 votes

# Answer
# INTERCAL (C-INTERCAL), 15 codes, 313 + 2 = 315 bytes

```
        PLEASE WRITE IN .1
(8)     PLEASE CREATE .1 A
        PLEASE A
        PLEASE COME FROM #2$!1/#1'

        DO X
(123)   DO (123) NEXT
        DO COME FROM (222)
(222)   DO STASH .2
(240)   DO ,1 <- #0
(241)   DO ,1 SUB #0 <- #1
(19)    DO .2 <- #256 $ #0
(21)    DO .1 <- #2
(148)   DO GO BACK
(180)   DO RETRIEVE .2
        DO COME FROM (50)
(50)    DO WRITE IN .2
(109)   DO RESUME #0
(120)   DO RESUME #9
        MAYBE COME FROM (223)
(223)   DO COME FROM (223)
(121)   PLEASE NOT X

```

Try it online!

*All* whitespace here is irrelevant. (The original program contained tabs, but I converted them to spaces so that it'd line up correctly on SE; it's conventional to use a tab width of 8 for INTERCAL. I've tested a version of the program with all tabs, spaces, and newlines deleted, though, and it works fine.)

Compile with `-abm` (2 byte penalty, because `-b` is required for the compiler to be deterministic).

As usual for INTERCAL, this takes numeric input in the format, e.g., `ONE TWO THREE` for `123`.

## Explanation

When a C-INTERCAL program errors out, the exit status is the error code modulo 256. As a result, we can aim to write a program that's capable of producing as many runtime errors as possible. This program only omits two runtime errors that don't indicate internal compiler issues: ICL200I, because reproducing it requires the use of external libraries that are only compatible with a single-threaded program (and multithreaded programs have more errors available); and ICL533I, because 533 has the same value modulo 256 as 277 does, and the program's capable of producing ICL277I.

The program always starts the same way. First, we input (`WRITE IN`) a value for the variable `.1`. Then, we use a computed `CREATE` statement to create new syntax (here, `A`); but because it's computed, the definition of the syntax varies based on the value of `.1`. Finally, in most cases we run our new `A` statement, which has been defined to produce an error; the table of possible definitions we have contains a definition for each possible runtime error (other than the exceptions listed above).

First, there are two exceptions to this general scheme. `(0)` is not a valid line number, so if the user inputs `ZERO`, we jump from the second line (numbered `(8)`) to the fourth line by means of a computed `COME FROM` statement. This then falls through into a syntax error `DO X`, which produces error `ICL000I`. (In INTERCAL, syntax errors happen at runtime, due to the tendency of commands to be disabled, syntax to be redefined under you, etc.). The `COME FROM` statement also has a side effect, even if no actual `COME FROM` happens, creating an operand overload from `.1` to `#1` whenever a line with a line number is executed; this is used later on when producing output 21. (Random global side effects are fairly idiomatic in INTERCAL.)

The other exception is with input `ONE TWO NINE`. There's no line number `(129)` in the program, so we get an error for a missing line number, which is `ICL129I`. So I didn't have to write any code to cover that case at all.

Here are the other errors, and what causes them:

* **123** is a `NEXT` stack overflow (`DO (123) NEXT`). The `NEXT` statement needs other modifiers (`FORGET` or `RESUME`) in order to retroactively determine what sort of control statement it was. Not having those causes error ICL123I once there are 80 unresolved \`NEXT statements.
* **222** is a stash overflow (`DO STASH .2` in a `COME FROM` loop). The stashes are limited only by available memory, but that will run out eventually, causing error ICL222I.
* **240** is dimensions an array to size zero. That's exactly what `DO ,1 <- #0` means, and it causes error ICL240I.
* **241** is caused by assigning outside the bounds of an array. In this case, `,1` hasn't been allocated (`,` is used for array-type variables in INTERCAL), so indexing it causes error ICL241I.
* **19** assigns 65536 (`#256 $ #0`) to a 16-bit variable `.2`. It doesn't fit, causing error ICL275I.
* **21** assigns `#2` to `.1`. That might look like a simple enough assignment, but we overloaded `.1` to mean `#1` earlier, and attempting to change the value of 1 with no `-v` option on the command line causes error ICL277I.
* **148** attempts to return to the top entry of the choicepoint stack (`GO BACK`), which doesn't exist at this point in the program (we haven't run any commands to manipulate the choicepoint stack, so it's still empty). That causes error ICL404I.
* **180** attempts to `RETRIEVE .2` from a nonexistent stash (because we didn't stash anything there in this branch of the program), causing error ICL436I.
* **50** requests input (`WRITE IN`) forever in a `COME FROM` loop. Eventually we'll end up reading past EOF, causing error ICL562I.
* **109** runs the statement `DO RESUME #0`, which is meaningless and specifically documented as causing an error (ICL621I).
* **120** runs the statement `DO RESUME #9`. We haven't run that many `NEXT` statements yet, and thus we get error ICL120I. (Intriguingly, this particular error is defined in the INTERCAL documentation as exiting the program normally and then causing the error, rather than exiting the program with an error. I don't believe these two cases are observably different, though.)
* **223** is basically a complex tangle of multithreading primitives that all point back to line 223, causing an infinite loop that blows up memory. Eventually, there's memory exhaustion in the multithreading subsystem, leading to error ICL991I.
* **121** is actually a valid statement (it's a comment), but it appears at the end of the program. As such, execution falls off the end of the program immediately after it executes, causing error ICL633I.

## Verification

Some of the errors involve intentionally running the program out of memory, so I suggest setting fairly small memory limits. Here's the shell command I used to test the program (with newlines added for readability; delete them if you run it yourself):

```
for x in "ZERO" "ONE NINE" "TWO ONE" "FIVE ZERO" "ONE ZERO NINE"
         "ONE TWO ZERO" "ONE TWO ONE" "ONE TWO THREE" "ONE TWO NINE"
         "ONE FOUR EIGHT" "ONE EIGHT ZERO" "TWO TWO TWO"
         "TWO TWO THREE" "TWO FOUR ZERO" "TWO FOUR ONE";
do  echo;
    echo $x;
    echo $x | (ulimit -Sd 40000; ulimit -Sv 40000; ulimit -Ss 40000;
               ./errors; echo $?);
done

```

And here's the output (with the line numbers and "PLEASE CORRECT SOURCE" messages deleted to save space), which I added partly to demonstrate the program working but mostly to show off INTERCAL's silly error messages:

```
ZERO
ICL000I PLEASEWRITEIN.1(8)PLEASECREATE.1APLEASEAPLEASECOMEFROM#2$!1/#1'DOX(123)DO(123)NEXTDOCOMEFROM(222)(222)DOSTASH.2(240)DO,1<-#0(241)DO,1SUB#0<-#1(19)DO.2<-#256$#0(21)DO.1<-#2(148)DOGOBACK(180)DORETRIEVE.2DOCOMEFROM(50)(50)DOWRITEIN.2(109)DORESUME#0(120)DORESUME#9MAYBECOMEFROM(223)(223)DOCOMEFROM(223)(121)PLEASENOTX
0

ONE NINE
ICL275I DON'T BYTE OFF MORE THAN YOU CAN CHEW
19

TWO ONE
ICL277I YOU CAN ONLY DISTORT THE LAWS OF MATHEMATICS SO FAR
21

FIVE ZERO
ICL562I I DO NOT COMPUTE
50

ONE ZERO NINE
ICL621I ERROR TYPE 621 ENCOUNTERED
109

ONE TWO ZERO
ICL632I THE NEXT STACK RUPTURES.  ALL DIE.  OH, THE EMBARRASSMENT!
120

ONE TWO ONE
ICL633I PROGRAM FELL OFF THE EDGE
121

ONE TWO THREE
ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
123

ONE TWO NINE
ICL129I PROGRAM HAS GOTTEN LOST
129

ONE FOUR EIGHT
ICL404I I'M ALL OUT OF CHOICES!
148

ONE EIGHT ZERO
ICL436I THROW STICK BEFORE RETRIEVING!
180

TWO TWO TWO
ICL222I BUMMER, DUDE!
222

TWO TWO THREE
ICL991I YOU HAVE TOO MUCH ROPE TO HANG YOURSELF
223

TWO FOUR ZERO
ICL240I ERROR HANDLER PRINTED SNIDE REMARK
240

TWO FOUR ONE
ICL241I VARIABLES MAY NOT BE STORED IN WEST HYPERSPACE
241

```
> 33 votes

# Answer
# C90 (gcc), 256 exit codes, ~~28~~ ~~27~~ 18 bytes

```
main(){getchar();}

```

I'm not sure if this is clever or cheaty, but I don't think it violates the rules as written: it technically doesn't use `exit`, `return`, or any error throwing mechanism, but simply relies on undefined behavior and the fact that gcc does something rather convenient as far as this challenge goes.

Try it online!

### How it works

This simply uses `getchar` to read one byte from STDIN. By itself, this does nothing.

However, a compliant C90 program must end with a `return` statement or something equivalent; everything else is undefined behavior. gcc ends the generated assembly with a `ret` anyway, so whatever value was casually in the register EAX will get returned by the program. Luckily, glibc's `getchar` stores the byte it reads from STDIN in EAX, so the value of that byte is the exit code of our program.
> 28 votes

# Answer
# Perl, 108 bytes, 256 exit codes

This program (ab)uses Test::More module. It tries to open file named `""` *n* times where *n* is given as command line argument. It fails every time, and each invocation is treated as a test. Test::More return number of failed tests as exit code. `plan tests => $ARGV[0]%255` is needed to get exit code 255.

```
#!/usr/bin/perl
use Test::More;
plan tests => $ARGV[0]%255 if($ARGV[0]>0);
ok(open(F,"")) for (1..$ARGV[0])

```
> 26 votes

# Answer
# C (gcc) under bash shell on x86, 230 bytes, 8 exit codes

Newlines added to aid readability. Comments ignored in score.

```
main(int c, char **v){
int p[2];
switch(atoi(v[1])-128){
case 2:__asm("UD2");        /* SIGILL: x86 undefined instruction */
case 5:__asm("int $3");     /* SIGTRAP: x86 breakpoint instruction */
case 6:abort();             /* SIGABRT: raise() is called under the covers */
case 8:c/=c-2;              /* SIGFPE: divide by 0 (c-2) */
case 11:c=*(int *)c;        /* SIGSEGV: dereference of invalid pointer */
                            /* SIGPIPE: write() to a pipe closed at the other end */
case 13:socketpair(1,1,0,p);close(p[1]);write(p[0],v,1);
case 14:alarm(1);sleep(2);  /* SIGALRM: kernel will send alarm signal after 1 sec */
}
}

```

A feature of the bash shell:

> When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.

So all we need to do is trigger various signals from within a c program. At this point, I assume simply doing `kill(n-128);` is banned. So instead we execute code that triggers various signals, which causes the corresponding error codes to be made available at the calling shell.

The exit codes are 0, 130, 133, 134, 136, 139, 141, 142.

Try it online. Expand the "Debug" section to see the return code.

This can certainly be golfed deeper. But I'd be more interested in adding more signals.
> 19 votes

# Answer
# PHP, 15 bytes, 2 exit codes

Without `die`/`exit`, PHP cannot return anything but `0` or `255` (afaik; probably `~1`), so ...

```
!$argv[1]?:p();

```

If command line argument is falsy, it evaluates to `1` and exits with `0`. If not, it tries to call a function and exits with `<b>Fatal error</b>: Uncaught Error: Call to undefined function p()`.

Run with `-r`.
> 10 votes

# Answer
# Python 2, 13 Bytes, 2 exit codes

```
1/(input()-1)

```

If you enter 0, it tries to print `1/-1` which is -1 which is perfectly fine thus exit code 0. If you enter 1, you get `1/0` which raises a `ZeroDivisionError` in which there is an exit code of 1. With my IDE, there is only 0 and 1 for the exit codes...

Outputs:

---

---
> 10 votes

# Answer
# Excel VBA, <sub>~~414~~ 514</sub> 533 + 3 Bytes, 14 exit codes

Takes input as a `Conditional Compilation Argument`, `n=[input value]` and produces that number's associated error code.

```
Sub e()
Dim a As Application, b As Byte, s As String, v(), x
Set a=Application
#If n=3 Then
Return
#ElseIf n=5 Then
b=a.CommandBars("")
#ElseIf n=6 Then
b=2^8
#ElseIf n=7 Then
ReDim v(9^9)
#ElseIf n=9 Then
v=Sheets("")
#ElseIf n=10 Then
v=Array(1)
For Each x In v
ReDim v(9)
Next
#ElseIf n=11 Then
b=1/0
#ElseIf n=13 Then
Debug.?Int("X")
#ElseIf n=14 Then
Debug.?String(9E8,1)
#ElseIf n=20 Then
Resume
#ElseIf n=28 Then
f 256
#ElseIf n=35 Then
Call c
#ElseIf n=92 Then
For Each x In v
ReDim v(9)
Next
#ElseIf n=94 Then
b=Null
#End If
End Sub

Sub f(n):DoEvents:f n-1:End Sub

```

+3 for `n=[Value]` conditional compilation call

Handles Inputs where `n=`

```
3
5
6
7
9
10
11
13
14
20
28
35
92
94

```

*Note:* VBA does not have exit codes `0` or `1`. I have included the solutions for `3` and `5`, which are the two lowest numbered exit codes available to VBA in their place
> 10 votes

# Answer
# Turtlèd, 4 bytes, 2 exit codes

I don't know if there are any ways to get more exit codes... are there even any more ways in the interpreter language

I found a few four length answers

```
' ?;

```

Try it online!

```
!.(0

```

Try it online!

```
?;(*

```

Try it online!

## How these work:

```
' ?;

```

in my interpreter, there is a ~~bug~~ feature that causes errors when the grid in memory has more than one line, and has no non-space characters on it. this program erases the * on the origin cell `'[space]`, takes non-negative integer input `?` (0 or 1 really), and moves down that many `;`, if it is zero, the grid will only have one line and not error, otherwise it will move down and the error will occur

```
!.(0

```

parentheses and stuff don't get parsed, they just get executed at run time to mean: "skip to the matching paren, if the cell symbol isn't right". in this program, inputting (`!`) one causes the program to write it to the cell (`.`), execute the paren, which checks if the cell symbol is 0, try to skip to the matching paren, but instead throw an error as there is none. if it is zero, it writes it down, checks the parentheses, finds itself on a 0, and then ignores it, and the program finishes

```
?;(*

```

has elements of the previous answer, and the first. it takes non-negative integer input, moves down that many, and checks whether the cell is '\*', searching for a non existing extra paren if it is not. if the input is 1, it will move off the starting space, and find the cell is a space, and error, if it is zero, it will stay on the start space and ignore the paren.
> 7 votes

# Answer
# Javascript (node), 19 bytes, 2 exit codes

Full program:

```
+process.argv[2]&&a

```

Function:

```
f=i=>i&&f(i)

```

`process.argv` is an array that contains the path to the node executable, the path to the javascript file executed and the command line arguments. In this case, this will be either `"1"` or `"0"`. The string is converted to a number with the unary `+` operator. If the number is zero the lazy `&&` operator won't evaluate the right hand side, if the number is truthy (not zero), the right hand side of `&&` is evaluated and an error is thrown because it's referencing an undefined variable, and the program exists with exit code 1.

The function expects the input as a number. If the input is truthy, the function calls itself, and crashes the node runtime with a stack overflow. If the input is 0, the lazy `&&` operator returns 0 without evaluating the right hand side.
> 7 votes

# Answer
# Perl 6, 57 bytes, 256 exit codes

```
use Test;plan $_=@*ARGS[0];ok try {open ""} for ^($_%255)

```

Try it
This is a translation of the Perl 5 example.

## Expanded

```
use Test;  # bring in ｢plan｣ and ｢ok｣

plan $_ = @*ARGS[0]; # plan on having the input number of tests
                     # only actually needed for the 255 case
                     # if the plan is greater than the number of tests
                     # it fails with exitcode 255

  ok                 # increment the failure counter if the following is False
    try {            # don't let this kill the whole program
      open ""        # fails to open a file
    }

for                  # repeatedly do that

  ^(                 # upto Range
    $_ % 255         # either the input number of times, or 0 times for 255
  )

```
> 6 votes

# Answer
# Scala, 19 bytes, 2 exit codes

`if(args(0)=="1")1/0`

`1/(args(0).toInt-1)`

The JVM supports only 1 and 0 as exit codes if you don't call `System.exit`.

The first program tries to calculate `1/0` if the first argument is `1`, which will crash the JVM with an exit code of 1. If the argument is 0, it wil exit succesfully.

The second program to converts the argument to integer, subtracts one and tries to divide 1 by that number. If the argument if 1, it calculates `1/0`, so the JVM will crash; if the argument is 0, it calculates `1/-1` and exits.
> 5 votes

# Answer
# Java, ~~71~~ 66 bytes, 2 exit codes

*4 bytes saved thanks to Holger*

### Full program:

```
interface I{static void main(String[]a){a[a[0].charAt(0)-48]="";}}

```

### Function taking an int as an argument:

```
i->1/(i-1)

```

The program takes the first char of the first argumant (either `'0'` or `'1'` and subtracts 48 (ascii value of `'0'`) to get an integer (0 or 1). It then tries to set the argument at the position of that integer to the empty string. If the input is 1, the program crashes with an `ArrayIndexOutOfBoundsException`, beacuse the argument array only has one element at position 0 (zero-indexed).
> 5 votes

# Answer
# Python 3, 15 bytes, 2 exit codes

Obviously, this is longer than the Python 2 solution, because in Python 3 we can't take a literal input without calling `eval`. However, we can use string comparison techniques interestingly...

```
1/(input()<'1')

```

Input will be either the string `0` or `1` \- if it's 1, the condition evaluates to 0 (false), resulting in an attempt to compute `1 / 0` which obviously crashes (exit code 1). Otherwise, nothing happens, and Python exits with the regular exit code 0.

As far as I'm aware, Python is incapable of crashing with other exit codes.
> 5 votes

# Answer
## Python 2, 11 bytes, 2 exit codes

```
1>>-input()
1/~-input()
0<input()<x

```

Three different 11-byte solutions for three different errors! (Just for fun, this doesn't give points.) By default, Python only has exit codes 0 for successful exit and 1 for error. The successful runs don't output anything.

```
 1>>-input()

```

On input 1, gives "ValueError: negative shift count". On input 0, a zero shift count succeeds and gives 1.

```
1/~-input()

```

On input 1, gives "ZeroDivisionError: integer division or modulo by zero" due to `~-input()`, aka `input()-1` being 0. In input 1, `1/-1` gives -1. `0**-input()` would also work.

```
0<input()<x

```

On input 1, gives "NameError: name 'x' is not defined". On input 0, these first inequality `0<0` is evaluated to False, so the rest is not evaluated and the result is just False.
> 4 votes

# Answer
# SmileBASIC, 640 bytes, 39 exit codes (out of 52)

```
SPSET.,0INPUT C$GOTO"@"+C$@0
STOP@3
A
@4
CLS.@5@A
GOSUB@A@7?1/A@8
X$=3@9
A%=POW(2,31)@10
BEEP-1@11
DIM B[#ZL*#R]@13
READ A
@15
V"OPTION STRICT?X
@16
CALL@D@17
V@A*2
@18
V"VAR A,A
@19
V"DEF A:END:DEF A
@20
V"FOR I=0TO
@21
V"NEXT
@22
V"REPEAT
@23
V"UNTIL
@24
V"WHILE.
@25
V"WEND
@26
V"IF.THEN
@27
V"IF.THEN"+CHR$(10)+"ELSE
@28
V"ENDIF
@29
V"DEF X
@30
RETURN@31
DIM E[-1]@32
V"DEF A:DEF
@34
GOTO"|
@36
XOFF MIC
MICSTOP
@37
XOFF MOTION
GYROSYNC
@38
PRGDEL
@39
DIM F[66]SPANIM.,1,F
@40
DIM G[2]SPANIM.,1,G
@42
MPSTART 2,@A@L
MPSEND"A"GOTO@L@44
PROJECT
@46
USE"PRG1:A
@47
BGMPLAY"`
@48
X=
@51
DLCOPEN"
DEF V C
PRGEDIT 1PRGDEL-1PRGSET C
EXEC 1
END

```

This could definitely be made shorter. SB only has error codes from 0 to 51, and some are impossible to trigger.
> 3 votes

# Answer
# Node.js (ES6), 77 bytes, 2 exit codes

```
require('readline').createInterface({input:process.stdin}).prompt("",i=>i&&x)

```
> 2 votes

# Answer
# Jelly, 4 exit codes, 18 bytes

```
ß€
2*
Ṁ¹Ŀ
RÇĿỌḊ?R

```

Supports exit codes **0**, **1**, **137** (killed), and **139** (segmentation fault).

Try it online!

### How it works

```
RÇĿỌḊ?R  Main link. Argument: n (integer)

R        Range; yield [1, ..., n] if n > 1 or [] if n = 0.
    Ḋ?   If the dequeued range, i.e., [2, ..., n] is non-empty:
 Ç         Call the third helper link.
  Ŀ        Execute the k-th helper link, where k is the the integer returned by Ç.
         Else, i.e., if n is 0 or 1:
   Ọ       Unordinal; yield [] for n = 0 and "\x01" for n = 1.
      R  Range. This maps [] to [] and causes and error (exit code 1) for "\x01".

Ṁ¹Ŀ      Third helper link. Argument: r (range)

Ṁ        Maximum; retrieve n from r = [1, ..., n].
 ¹Ŀ      Call the n-th helper link (modular).
         When n = 139, since 139 % 3 = 1, this calls the first helper link.
         When n = 137, since 137 % 3 = 2, this calls the second helper link.

2*       Second helper link. Argument: k

2*       Return 2**k.
         Since 2**137 % 3 = 174224571863520493293247799005065324265472 % 3 = 2,
         ÇĿ in the main link will once again call the second helper link.
         Trying to compute 2**2**137, a 174224571863520493293247799005065324265472-
         bit number, will get the program killed for excessive memory usage.

ß€       First helper link. Argument: k

ß€       Recursively map the first helper link over [1, ..., k].
         This creates infinite recursion. Due to Jelly's high recursion limit,
         a segmentation fault will be triggered.

```
> 2 votes

# Answer
# ZX81 BASIC \>255 exit codes - 52 bytes (listing)

```
1 INPUT N
2 GOTO 1+(2*(N>0 AND N <=255))
3 PRINT "EXIT CODE ";N
4 RAND USR N

```

Technically, `N` could be any 24 bit floating point number within the range, but we'll assume integers here. Line 2 is equivalent to `IF N>0 AND N <=255 THEN GOTO 3: ELSE GOTO 1` if ZX81 BASIC had `IF/ELSE` in its symbolic instructions.
> 0 votes

---
Tags: code-challenge, restricted-source, error-message
---


# Question
Title: Remove single line and multiline comments from string
### Goal

Using the programming language of your choice, write the **shortest program** to eliminate comments from a string representing a C program.

---

### Input

The string can be taken as any form of input, but it may also be taken as a variable.

---

### Instructions

Two different kinds of comments are to be removed:

* **multiline comments**, starting with `/*` and ending with `*/`
* **single line comments**, starting with `//` and ending with Linux-style line breaks (LF, `\n`)

Comments within strings are not to be deleted. For the purpose of this challenge, you only need to consider `"`-delimited strings. In particular, you can ignore the possibility of `'`-delimited character literals. You may also ignore trigraphs and line continuations (`/\<LF>*...`).

---

### Examples

Input:

```
#include <stdio.h>

int main(int argc, char** argv)
{
    // this comment will be removed
    if (argc > 1) {
        printf("Too many arguments.\n");   // this too will be removed
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");
    // but not this
    printf("just \"ano//ther\" test.");
    return 0;
}

```

Output:

```
#include <stdio.h>

int main(int argc, char** argv)
{

    if (argc > 1) {
        printf("Too many arguments.\n");
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");

    printf("just \"ano//ther\" test.");
    return 0;
}

```

---

Input:

```
/*
    this shall disappear
*/
#include <string>
int main(int argc, char** argv)
{
    string foo = ""/*remove that!**/;
    // Remove /* this
    int butNotThis = 42;
    // But do */ remove this
    int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
    return 0;//just a comment
}/*end of the file has been reached.*/

```

Output:

```
#include <string>
int main(int argc, char** argv)
{
    string foo = "";

    int butNotThis = 42;

    int bar = 4 * 3;
    return 0;
}

```

# Answer
# Retina, 35 + 1 + 2 = 38 bytes

This program consists of two files, hence I've included a 1-byte penalty for the second file.

```
//.*|/\*[\s\S]*?\*/|("(\\.|[^"])*")

```

```
$1

```

This is a simple regex replacement, using the .NET flavour (although this would work the same in most other flavours).

The idea is to match both comments and strings, but only write the match back if it was a string. By matching the strings explicitly, they are skipped when searching for comments.
> 11 votes

# Answer
# Shell + coreutils + gcc compiler collection, 31 bytes

This answer may seem a bit loopholey, but I didn't see anything specifically banning it in the question.

Rather than using clumsy regular expressions, why not use the tool that was built for the job. It should have no problem giving correct results:

```
cpp -fpreprocessed -o- -|sed 1d

```

Takes input from STDIN and output to STDOUT. Normally `ccp` will do all preprocessing (header files, macro expansion, comment removal, etc), but with the `-fpreprocessed` option, it will skip most of the steps, but it will still remove comments. In addition, cpp adds a line like `# 1 "<stdin>"` to the beginning of the output, so the `sed` is there to delete it.
> 15 votes

# Answer
## Java 365

```
String a(String s){String o="";int m=1;for(int i=0;i<s.length();i++){String u=s.substring(i,Math.min(i+2,s.length()));char c=s.charAt(i);switch(m){case 1:m=u.equals("/*")?5:u.equals("//")?4:c=='"'?3:1;break;case 3:m=c=='"'?1:c=='\\'?2:3;break;case 2:m=3;break;case 4:m=c=='\n'?1:4;continue;case 5:m=u.equals("*/")?1:5;i+=m==1?1:0;continue;}o+=m<4?c:"";}return o;}}

```

**Ungolfed**

```
public static final int DEFAULT = 1;
public static final int ESCAPE = 2;
public static final int STRING = 3;
public static final int ONE_LINE_COMMENT = 4;
public static final int MULTI_LINE_COMMENT = 5;

String clear(String s) {
    String out = "";
    int mod = DEFAULT;
    for (int i = 0; i < s.length(); i++) {
        String substring = s.substring(i, Math.min(i + 2 , s.length()));
        char c = s.charAt(i);
        switch (mod) {
            case DEFAULT: // default
                mod = substring.equals("/*") ? MULTI_LINE_COMMENT : substring.equals("//") ? ONE_LINE_COMMENT : c == '"' ? STRING : DEFAULT;
                break;
            case STRING: // string
                mod = c == '"' ? DEFAULT : c == '\\' ? ESCAPE : STRING;
                break;
            case ESCAPE: // string
                mod = STRING;
                break;
            case ONE_LINE_COMMENT: // one line comment
                mod = c == '\n' ? DEFAULT : ONE_LINE_COMMENT;
                continue;
            case MULTI_LINE_COMMENT: // multi line comment
                mod = substring.equals("*/") ? DEFAULT : MULTI_LINE_COMMENT;
                i += mod == DEFAULT ? 1 : 0;
                continue;
        }
        out += mod < 4 ? c : "";
    }

    return out;
}

```
> 3 votes

# Answer
**Python2 - ~~163~~ 134 bytes**

```
import re
def f(s):
 for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
 print s

```

As you can see here, the regex consists of 2 alternating capturing groups. The first one captures all the quoted strings. The second one all the comments.

All we need to do, is removing everything captured by the 2nd group.

Example:

```
Python 2.7.9 (default, Dec 11 2014, 04:42:00)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> def f(s):
...  for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)',s,8):s=s.replace(x[1],'')
...  print s
...
>>> code = r'''#include <stdio.h>
...
... int main(int argc, char** argv)
... {
...     // this comment will be removed
...     if (argc > 1) {
...         printf("Too many arguments.\n");   // this too will be removed
...         return 1;
...     }
...     printf("Please vist http://this.will.not.be.removed.com\n");
...     printf("/* This will stay */\n");
...     printf("\"/* This will stay too */\"\n");
...     printf("//and so will this\\");
...     // but not this
...     printf("just \"ano//ther\" test.");
...     return 0;
... }
... /*
...     this shall disappear
... */
... #include <string>
... int main(int argc, char** argv)
... {
...     string foo = ""/*remove that!**/;
...     // Remove /* this
...     int butNotThis = 42;
...     // But do */ remove this
...     int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
...     return 0;//just a comment
... }/*end of the file has been reached.*/'''
>>> f(code)
#include <stdio.h>

int main(int argc, char** argv)
{

    if (argc > 1) {
        printf("Too many arguments.\n");
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");

    printf("just \"ano//ther\" test.");
    return 0;
}

#include <string>
int main(int argc, char** argv)
{
    string foo = "";

    int butNotThis = 42;

    int bar = 4 * 3;
    return 0;
}

```
> 2 votes

# Answer
# Rebol - 151

```
f: func[t][Q:{"}W: complement charset Q parse t[any[[Q any["\\"|"\"Q | W]Q]|[a:[["//"to[lf | end]]|["/*"thru"*/"]]b:(remove/part a b):a skip]| skip]]t]

```

Ungolfed + some annotations:

```
f: func [t] [
    Q: {"}
    W: complement charset Q     ;; any char thats not a double quote

    ; rule to parse t (c program) - it can be ANY of
    ;     1. string
    ;     2. OR comment (if so then remove)
    ;     3. OR pass thru

    parse t [
        any [
            ;; 1. String rule
            [Q any ["\\" | "\" Q | W] Q]

            ;; 2. OR comments rule
            | [
                a:  ;; mark beginning of match
                [
                    ;;    // comment    OR  /* comment */
                    ["//" to [lf | end]] | ["/*" thru "*/"]
                ]
                b:  ;; mark end of match
                (remove/part a b) :a skip   ;; remove comment
            ]

            ;; 3. OR allow thru (so not a String or Comment)
            | skip
        ]
    ]

    t
]

```
> 1 votes

# Answer
# PHP

Converting @Martin Ender's answer for php:

```
$str = preg_replace_callback('/\/\/.*|\/\*[\s\S]*?\*\/|("(\\.|[^"])*")/m',
  function($matches){
     if(\is_array($matches) && (\count($matches) > 1)){
        return $matches[1];
     }else{
        return '';
     }
  }, $str);

```

now `$str` has lost single- and multi-line comments. This is useful for stripping comments in JSON data before feeding to `json_decode()`.
> 1 votes

# Answer
**C# (262 chars):**

From this very good SO answer:

```
string a(string i){return Regex.Replace(i, @"/\*(.*?)\*/|//(.*?)\r?\n|""((\\[^\n]|[^""\n])*)""|@(""[^""]*"")+", m => { var v = m.Value; if (v.StartsWith("/*") || v.StartsWith("//")) return v.StartsWith("//") ? "\r\n" : ""; return v; }, RegexOptions.Singleline);

```
> 0 votes

# Answer
# JS (ES6), 47 chars (wip)

DEMO: http://codepen.io/anon/pen/dPEMro

```
a=b=>b.replace(/(\/\*[^]*?\*\/|\/\/.*)\n?/g,"")

```

Inspired by my codegolfed minifiers: http://xem.github.io/miniMinifier/

doesn't handle comments in strings yet...

I'm curious to see if it's possible to achieve that in JS regexes.
> -1 votes

---
Tags: code-golf, string, regular-expression, comment
---