title: Robbers - square times square root

text:
# Question
Title: Robbers - square times square root
**Task:** Crack the scrambled code for multiplying the square root of an integer ***n*** by the square of it!

You must post a comment in the **cops' thread** with a link to your working source, mentioning clearly that you have ***Cracked it***. In your answer's title, you must include the link to the original answer.

## Rules:

* You may only change the order of the characters in the original source.
* Safe answers cannot be cracked anymore.
* The other rules mentioned in the cops' thread
* ***Please edit the answer you crack***

---

## WINNER: Emigna - 10 submissons (had some trouble counting)

*Honorable mentions: Notjagan, Plannapus, TEHTMI*

# Answer
> 3 votes
# NO, 41 bytes, This Guy

```
NOOOOOO?NOOOOOOOOOOO!nnOOOOO
NOOOOOOOO?no

```

# Answer
> 9 votes
# JavaScript (ES7), Neil

```
_26_=>_26_**6.25**.5

```

The hard part, of course, was figuring out what to do with all the extra characters. (And also not posting this solution in the wrong thread, like I accidentally did at first. Oopsie...)

# Answer
> 6 votes
# Python, 15 bytes, Mr. Xcoder

```
lambda x:x**2.5

```

Pretty simple. Just takes `x` and raises it to the `2.5`th power.

# Answer
> 6 votes
## OCaml, 13 bytes, shooqie

```
fun f->f**2.5

```

Try it online!

# Answer
> 5 votes
# Python 3, 44 bytes, Kyle Gullion

Those `*`s were quite misleading. Very clever!

```
lambda i:i**(lambda o,r:o/r)(*map(ord,'i*'))

```

Due to the quite limited character set I would be very surprised if there were any other valid solutions beyond trivial renaming or reordering of arguments.

# Answer
> 4 votes
# C++ (gcc), 100 bytes, Mr. Xcoder

```
#include<math.h>
#include"iostream"
using namespace std;int main(){float n;cin>>n;cout<<pow(n,2.5);}

```

Try it online!

# Answer
> 4 votes
## Haskell, Leo

```
x=exp.(2.5*).log

```

A pointfree function named `x`. Usage: `x 4` -\> `32.0`

# Answer
> 4 votes
# Inform 7, corvus\_192

Cool, an Inform7 entry. :) I just had to give this one a try.

I'm pretty sure this is the intended solution:

```
R is a room.

To f (n - number): say "[n * n * real square root of n]".

```

Note that this solution only works if compiled with the Glulx back-end, due to the use of the `real square root of` function.

---

BTW, the double quotes and square brackets are actually unnecessary; just `say n * n * real square root of n` would work just as well. The periods at the end of the commands could be omitted, too; or we could keep the first period and get rid of the newlines instead. Other parts of the code we could trim away include the article "a" before "room" and the spaces before the parentheses and after the colon. Fortunately, since we've got a spare pair of brackets, we can always use them to comment out all these extra characters. ;) So this is a valid solution, too:

```
R is room.To f(n - number):say n * n * real square root of n[
" a . "
]

```

---

To test this solution interactively, it's convenient to append something like the following test harness to the code:

```
Effing is an action applying to one number.
Understand "f [number]" as effing.
Carry out effing: f the number understood.

```

After compiling and running the program, you can type e.g. `f 4. f 6. f 9. f 25` at the `>` prompt and receive something like the following output:

```
Welcome
An Interactive Fiction
Release 1 / Serial number 170404 / Inform 7 build 6L38 (I6/v6.33 lib 6/12N) SD

R

>f 4. f 6. f 9. f 25
32.0
88.18164
243.0
3125.0
>

```

BTW, I just noticed that Inform (or presumably, rather, Glulx) rounds the last decimal place of `f 6` wrong: the correct value is *much* closer to 88.18163 than to 88.18164. Fortunately, I don't think this affects the correctness of the solution(s), especially since the challenge specified "any rounding mechanism of your choice". :)

# Answer
> 4 votes
## Mathematica, Greg Martin

```
f[y_]:=With[{x=
    #&@@{#(#)#^(1/(1+1))&@y,#&@@@{1^(1),-1}}
},Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]]

```

Thanks for leaving the rounding stuff intact!

Explanation: `#(#)#^(1/(1+1))&@y` does the main work of multiplying `y` squared, aka `y(y)`, and `y`'s square root, `y^(1/(1+1))`. The `#&@@@{1^(1),-1}` bit is just junk to use up the other letters, and `#&@@` picks out the useful bit from the junk.

# Answer
> 4 votes
# MATL, 12 bytes, Luis Mendo

```
10'U&+:'n/^P

```

Calculate 10/4 = 2.5 with 4 coming from string length. Use this as an exponent. P is a no-op here.

# Answer
> 3 votes
## R, Steadybox

```
y<-function(p)(p^(1/2)*p^2);

```

seems to be an anagram of `funny(p1)-tio(^*^)/pc(2)<p2;`

# Answer
> 3 votes
# Python 2, 60 bytes, Anthony Pham

```
print    (input()**(5.0/(2*5554448893999/5554448893840))-0)

```

Based on discarding characters through Python 2's float division (the default for `/` between integers).

# Answer
> 3 votes
# C, 50 bytes, Dave

```
double b(float \ufa2d){return pow(\ufa2d,25e-1);%>

```

Try it online!

This requires `-lm` compiler flag, but I don't know how it would be possible to solve this without it.

# Answer
> 3 votes
# R, Flounderer

This is a crack of the 33 bytes solution of @Flounderer

```
scan()^(floor(pi)-1/2)-sin(7*0e1)

```

Usage:

```
> scan()^(floor(pi)-1/2)-sin(7*0e1)
1: 4
2:
Read 1 item
[1] 32
> scan()^(floor(pi)-1/2)-sin(7*0e1)
1: 6
2:
Read 1 item
[1] 88.18163
> scan()^(floor(pi)-1/2)-sin(7*0e1)
1: 9
2:
Read 1 item
[1] 243
> scan()^(floor(pi)-1/2)-sin(7*0e1)
1: 25
2:
Read 1 item
[1] 3125

```

# Answer
> 3 votes
# EXCEL, 26 Bytes pajonk

```
=SQRT(A1)*A1^2/1/ISNA(IP2)

```

A1 as input IP2 contain a second input with a #N/A Error in this case ISNA(IP2) belongs to 1

For an additional `()` we can do this

```
=SQRT(A1)*A1^2/ISNA(PI(1/2))

```

# Answer
> 3 votes
# RProgN 2, ATaco

```
]2^\š*

```

Apparently StackExchange needs extra characters, so here you go.

# Answer
> 3 votes
# HODOR, 198, This Guy

```
Walder
Hodor?!
hodor.
Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor Hodor,
hodor,
Hodor, Hodor Hodor Hodor Hodor Hodor Hodor, Hodor Hodor,
Hodor, Hodor Hodor Hodor, hodor!,
HODOR!!
HODOR!!!

```

Explanation:

```
Start
read input into accumulator
copy accumulator to storage
Do math, option 7(nth root), n=2
swap storage and accumulator
Do math, option 6(nth power), n=2
Do math, option 3(times), storage
output accumulator as a number
end

```

note: I had to make some modifications to the get interpreter to run on my machine (the one you have posted doesn't seem to accept lowercase h, among some other things)

Also, I don't seem to have enough rep to comment, so if someone could let @This Guy know, I would be grateful

I think this fixed the error, the code now starts with Walder instead of Wylis, which adds the extra byte

# Answer
> 3 votes
## C#, 172 bytes, raznagul

Hardest part was figuring out what to do with all the leftovers.

```
using System;using S=System.Console;class PMabddellorttuuv{static void Main(){S.Write(Math.Pow(double.Parse(S.ReadLine()),2.5));Func<double> o;int q=1,M=q*2,b,e;q*=(q*M);}}

```

# Answer
> 3 votes
## Python 3.6, 64 bytes, Mr. Xcoder

```
php38af4r2aoot2srm0itpfpmm0726991i=     (lambda x:x**2.5*1*1/1);

```

Maybe not what was intended, but works ;)

```
$ python3
Python 3.6.1 (default, Apr  4 2017, 09:36:47)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> php38af4r2aoot2srm0itpfpmm0726991i=     (lambda x:x**2.5*1*1/1);
>>> php38af4r2aoot2srm0itpfpmm0726991i(6)
88.18163074019441
>>> php38af4r2aoot2srm0itpfpmm0726991i(4)
32.0
>>> php38af4r2aoot2srm0itpfpmm0726991i(25)
3125.0

```

Not enough rep to comment on the cops' thread's answer yet, sorry... Would appreciate if someone could do it for me, thanks!

# Answer
> 3 votes
# Röda, 28 bytes, fergusq

```
f(n){push n^0.5,n^2|product}

```

# Answer
> 3 votes
# Python 2.7, Koishore Roy

```
s=e=x=y=input()**0.5
print'%.3f'%(y**(5.0))

```

# Answer
> 3 votes
# R, Flounderer

This is a crack of @Flounderer's 31-byte solution:

```
`[.`=function(`]`)`]`^`[`(lh,9)

```

Ok that was a tough one. It creates a function called ``[.``. The argument to the function is called ``]`` which is elevated to power 2.5 by using the 9th element of the built-in time-serie `lh` ("a regular time series giving the luteinizing hormone in blood samples at 10 mins intervals from a human female, 48 samples." that is used as example in one of R's base packages). `lh[9]` is here on top of it replaced by its equivalent ``[`(lh, 9)`. De-obfuscated by substituting `f` for the function name and `n` for the argument name, the function then becomes `f=function(n)n^lh[9]`.

Usage:

```
> `[.`=function(`]`)`]`^`[`(lh,9)
> `[.`(4)
[1] 32
> `[.`(6)
[1] 88.18163
> `[.`(9)
[1] 243
> `[.`(25)
[1] 3125

```

# Answer
> 2 votes
# Python 2, 44 bytes, Anthony Pham

```
print int(raw_input())**(0+000000000000.5*5)

```

Takes input from raw\_input, converts to int and raises to power 2.5

# Answer
> 2 votes
# JavaScript, **fəˈnɛtɪk**

```
n=>n**("ggggg".length*2**(-"g".length))// ""((((((()))))))***,-...;;=====>Seeeeegggghhhhhhhhhilllnnnnnnorrrsstttttttttttu{}

```

Gets 5/2 through 5 times 2 to the negative first power, where 5 and 1 were received from the length of strings. Took the easy way out in a sense by commenting out the extraneous characters.

# Answer
> 2 votes
## C#, 112 bytes, Jan Ivan

```
using System;class P{static void Main(){var b=Math.Pow(double.Parse(Console.ReadLine()),2.5);Console.Write(b);}}

```

# Answer
> 2 votes
## Fireball, 8 bytes, Okx

```
♥²♥1Z/^*

```

Explanation:

```
♥²♥1Z/^*
♥²       Push first input squared.
  ♥      Push first input again.
   1Z/   Push 1/2
      ^  First input to the 1/2th
       * Multiply square and root

```

Not sure if it works. I have currently no java on my laptop. :(

# Answer
> 2 votes
# 05AB1E, 47 bytes, Okx

```
).2555BFHIJJKKKPQRS``„cg…ghi…lsw…x}T…Áöž«‚¹n¹t*

```

Try it online!

# Answer
> 2 votes
# CJam, 8 bytes, Roman Gräf

My First ever CJam answer.
CnR are great for testing new languages :)

```
ldYYW#+#

```

Try it online!

**Explanation**

```
ld         % double(input)
       #   %              ^
  Y        %               (2
      +    %                 +
   Y       %                  2
     #     %                   ^
    W      %                    -1)

```

# Answer
> 2 votes
# Haskell, 64 bytes, @nimi

```
product.(<$>(($(succ.cos$0))<$>[(flip<$>flip)id$id,recip])).(**)

```

Try it online! That was a fun one. I first found `product.(<$>(($succ(cos$0))<$>[id,recip])).(**)` which behaves correctly and than had to fit `flip flip <$> () $ id .` somewhere into it.

# Answer
> 2 votes
# R, steadybox

```
a222=function(s)(s**0.5)*s**2**1

```

Usage:

```
> a222=function(s)(s**0.5)*s**2**1
> a222(4)
[1] 32
> a222(6)
[1] 88.18163
> a222(9)
[1] 243
> a222(25)
[1] 3125

```

# Answer
> 2 votes
# 05AB1E, 22 bytes, P. Knops

```
n¹t*qA9¥="'?:@->%#[{!.

```

Try it online!

**Explanation**

```
n      # square of input
   *   # times
 ¹t    # square root of input
    q  # end program

```

The rest of the operations never get executed.
We could have done it without the `q` as well by having `?` after the calculation and escaping the equality sign for example with `'=`.

# Answer
> 2 votes
# HODOR, 171 bytes, wwj

```
Walder
Hodor
Hodor
Hodor
Hodor
Hodor
Hodor, Hodor Hodor Hodor Hodor, Hodor Hodor,
hodor.
Hodor.
Hodor?!
Hodor, Hodor Hodor Hodor Hodor Hodor Hodor, hodor!,
HODOR!!
HODOR!!!

```

**Explanation**

* Increment accumulator to 5
* Divide accumulator by 2
* Save a copy of accumulator value
* Set accumulator to 0
* Read input
* Raise input to the value of the stored copy (2.5)
* Output as number

# Answer
> 2 votes
# JavaScript, 39 bytes, SLuck49

```
x=>(l=Math).cbrt(l.exp(l.log(x)*7.5))

```

or similarly

```
x=>(l=Math).exp(l.log(l.cbrt(x))*7.5)

```

Test:

```
alert((

x=>(l=Math).cbrt(l.exp(l.log(x)*7.5))

)(prompt()));
```

# Answer
> 2 votes
# C, 115 bytes, user4867444

New solution that works for 0.

```
o(double n){double l=1;;for(double o=0.;o<=8*8*2e3&&(long)o+n*((long)2*3>>1);o++)l=(l+n/l)/2;printf("%.3f",n*n*l);}

```

Old solution that doesn't work for 0:

```
o(double n){double l=n;;for(double o=1.0;o<=8*8*2e+3&&(long)o*((long)2*3>>1);o++)l=(l+n/l)/2;printf("%.3f",n*n*l);}

```

Applying Newton's method (for square root) a very large fixed number of times seems to give adequate precision for numbers in the required range. I did some character wasting in the first two for loop clauses.

# Answer
> 2 votes
## 05AB1E, 22 bytes, Emigna

```
è›¹DDLÏ_zTnF©¹®/+;}¹DP

```

Most probably not what was intended, but works ;)

Everything before `T` is just byte wasting (but which leaves the stack empty), then it does a 100 Newton iterations, which yields a good enough approximation of the square root, then pushes the input twice and returns the product of the whole stack, thus giving the desired output.

Example runs:

```
$ echo 0 | ./05AB1E.py -e 'è›¹DDLÏ_zTnF©¹®/+;}¹DP'
0.0
$ echo 4 | ./05AB1E.py -e 'è›¹DDLÏ_zTnF©¹®/+;}¹DP'
32.0
$ echo 6 | ./05AB1E.py -e 'è›¹DDLÏ_zTnF©¹®/+;}¹DP'
88.18163074019441
$ echo 25 | ./05AB1E.py -e 'è›¹DDLÏ_zTnF©¹®/+;}¹DP'
3125.0
$ echo 7131 | ./05AB1E.py -e 'è›¹DDLÏ_zTnF©¹®/+;}¹DP'
4294138928.896773

```

# Answer
> 2 votes
# 05AB1E, 15 bytes, user4867444

```
DMžDFD¹s/+;}01P

```

Try it online!

**Explanation**

```
D                 # duplicate input
 M                # push the largest value on the stack (the input)
  žDF             # 4096 times do:
     D            # current value
         +        # added to
      ¹s/         # input divided by current value
          ;       # divide sum by 2
           }      # end loop
            01    # push 1
              P   # product of the stack

```

# Answer
> 2 votes
# 05AB1E, 23 bytes, user4867444

```
$DDžHGD¹s/+;}0@rrzz2+\P

```

Try it online!

**Explanation**

```
$                        # push 1 and input
 DD                      # duplicate the input twice
   žHG                   # 65536 times do:
      D                  # duplicate current value
       ¹s/               # divide input by current value
          +              # add result of division to current value
           ;             # divide by 2
            }            # end loop
             0@          # get the bottom value of the stack (the 1)
               rr        # reverse the stack twice (no-op)
                 zz      # calculate 1/(1/1), a no-op
                   2+    # add 2
                     \   # discard top of stack (the 3)
                      P  # product of stack

```

# Answer
> 2 votes
# JavaScript, SIGSEGV

```
x=>x**(25*10**-1)

```

Try it online!

# Answer
> 1 votes
# Python - SparklePony

```
import math
f=lambda x:x*x*math.sqrt(x)

```

# Answer
> 1 votes
# Scala, corvus\_192

```
d=>math.pow(d,5/2d)

```

Try it here!

Simple lambda expression

# Answer
> 1 votes
# 05AB1E - P. Knops

```
t¹n*

```

Was quite easy :)

# Answer
> 1 votes
# C, Steadybox

```
float q(float b){return(b-b>0.*4*1/1)-sqrtf(b)*pow(b,2)*-1;}

```

Not sure what the original did; I had to discard a lot of random operators and numbers, but once the available words were clear it wasn't too hard to piece together the general idea.

# Answer
> 1 votes
# R, Flounderer

```
scan()**mean(1:4.5)

```

Try it online!

# Answer
> 1 votes
## Python 3.6, c..

```
f=lambda x:x**2.5or'1*77*8+8/5/(((aafothipie.xml)))'

```

Try it online!

Stuffs all the unneeded characters into a string after the `or`. Since `x**2.5` is nonzero and so truthy, the part after the `or` isn't evaluated. Any syntactically valid expression would be OK here.

Python parses `2.5` and `or` as separate tokens in `2.5or`, though the syntax highlighter for the code doesn't recognize this.

# Answer
> 1 votes
# Ruby, G B

```
->a{eval''<<97<<42<<42<<50<<46<<53}

```

# Answer
> 1 votes
## C#, 135 bytes, Jan Ivan

This was a lot of fun, I particularly liked the use of `using static`.

```
using System;using static System.Math;class P{static void Main(){Console.Write(Pow(long.Parse(Console.ReadLine()),1/Round(PI-E,1)));}}

```

# Answer
> 1 votes
# JavaScript, SIGSEGV

```
x=>x**(3.5-+!+[]);

```

Try it online!

# Answer
> 0 votes
# Vyxal, cracks emanresuA's answer

```
5|2/en[(`ĖĖ:

```

Try it Online!

Easy. I came up with the solution in the shower that's how easy it is.

---
Tags: code-golf, number, arithmetic, cops-and-robbers
---


title: Cops - square times square root

text:
# Question
Title: Cops - square times square root
*Note: This is the **cops'** thread, where one should post the scrambled code. Here is the **robbers' thread*** where the cracked source should be posted and linked to the cop's answer.

---

**Task:** Write the shortest *safe* program which multiplies the square root of an integer ***n*** by the square of ***n***

This is , so the rules are:

* In your answer, post a scrambled version of your source code (the characters should be written in any order). The scrambled version **should not** work!
* You can take input in any standard way, the same goes for output. Hardcoding is forbidden
* After the code is cracked by the robbers (if this happens), you must mention that your code has been cracked in your title and add a ***spoiler*** to your answer's body with your exact code
* The same applies to safe answers (mention that it's safe and add the ***spoiler***)
* The code is considered *safe* if nobody has cracked it in 5 days after posting it and you can optionally specify that in the title
* You must specify your programming language
* You should specify your byte count
* You must state the rounding mechanism in your answer (see below)

---

You can assume that the result is lower than 232 and ***n*** is always positive. If the result is an integer, you must return the exact value with or without a decimal point; otherwise the minimum decimal precision will be 3 decimal places with any rounding mechanism of your choice, but can include more. **You must state the rounding mechanism in your answer.** You are not allowed to return as fractions (numerator, denominator pairs - sorry, Bash!)

### Examples:

```
In -> Out

4 -> 32.0 (or 32)
6 -> 88.18163074019441 (or 88.182 following the rules above)
9 -> 243.0
25 -> 3125.0

```

The shortest safe answer by the end of April will be considered the winner.

# Answer
> 2 votes
# 05AB1E, 20 bytes - safe

Another totally different approach from my previous answers.

```
****++/133DDFPTs}¹¹Ð

```

No rounding.

**Example runs**

```
In   -> Out
0    -> 0
4    -> 32.0
6    -> 88.18163074019441
25   -> 3125.0
7131 -> 4294138928.896773

```

I have no doubt @Emigna is going to crack it in a jiffy, but eh, one has to try! :-D

---

**Solution**

```
D1TFÐ*D¹3*+s3*¹+/*}P

```

This is using the fact that this sequence:

u\_0 = 1, u\_{n+1} = u\_n * (u\_n ^ 2 + 3 x) / (3 u\_n ^ 2 + x)

converges to sqrt(x), and cubically fast at that (sorry, didn't find how to format math equations in PCG).

**Detailed explanation**

```
D1TFÐ*D¹3*+s3*¹+/*}P
D1                   # Duplicate the input, then push a 1: stack is now [x, x, 1] (where x is the input)
  TF                 # 10 times (enough because of the cubic convergence) do
    Ð                # triplicate u_n
     *               # compute u_n ^ 2
      D              # and duplicate it
       ¹3*+          # compute u_n ^ 2 + 3 x
           s         # switch that last term with the second copy of u_n ^ 2
            3*¹+     # compute 3 u_n ^ 2 + x
                /    # compute the ratio (u_n ^ 2 + 3 x) / (3 u_n ^ 2 + x)
                 *   # compute u_n * (u_n ^ 2 + 3 x) / (3 u_n ^ 2 + x), i.e. u_{n+1}, the next term of the sequence
                  }  # end of the loop
                   P # compute the product of the whole stack, which at that point contains u_10 (a sufficiently good approximation of sqrt(x)), and the 2 copies of the input from the initial D: we get x ^ 2 * sqrt(x)

```

Try it online!

# Answer
> 18 votes
# Python 3, 44 bytes (cracked)

```
'**:(((paraboloid / rabid,mad,immoral))):**'

```

No rounding. Floating point accuracy.

# Answer
> 11 votes
# MATL, 12 bytes (cracked by @tehtmi)

```
'Un&0P'/^:+1

```

No rounding; uses floating point.

Intended solution (different from that found by @tehtmi):

> `:&+n10U'P'/^`

### Explanation

> `:&+ % Create a matrix of size n × n, where n is implicit input`
> `n % Number of elements. Gives n^2`
> `10U % 10 squared. Gives 100`
> `'P' % 'P' (ASCII code 80)`
> `/ % Divide. Gives 1.25`
> `^ % Power. Implicit display`

# Answer
> 10 votes
# Röda, 28 bytes (Cracked by @tehtmi)

```
 (),.025^^cdfhnnnopprstuu{|}

```

Note the space at the beginning. No rounding, but it uses floating point numbers so precision is limited.

# Answer
> 10 votes
## Perl, 42 bytes (Safe)

There are 41 bytes of code and `-p` flag (no other flags).

```
/"/4~~r..rso4r<_$4va=eg1de|i/h0-&$c={}l+"

```

The result isn't rounded (or rather rounded up to the same point Perl would have round up by doing `$_ = (sqrt $_) * ($_ ** 2)`).

**Solution:**

> `$_=eval".i44<4}{|~"=~s/./chr-10+ord$\&/gre`
> (without the `\` before the `&` \- markdown spoiler seems to dislike `$` followed by `&`)
> Try it online!

**Explanation:**

> `.i44<4}{|~` is `$_**2*sqrt` but with every character replaced by the character with its ascii code + 10. (ascii code of `$` is `36`, so it becomes `.` whose ascii code is `46`, etc.).
> The purpose of `s/./chr-10+ord$\&/gre` is then to undo this transformation: it replaces each character by the character with ascii code 10 lower. (`chr-10+ord$\&` is probably clearer as `chr(ord($\&)-10)` where `chr` returns the character corresponding to an ascii code, and `ord` returns the ascii code corresponding to a character).
> finally, `eval` evaluates this string, and thus computes the result, which is stored in `$_`, which is implicitly printed at the end thanks to `-p` flag.

# Answer
> 8 votes
# Octave, 43 bytes (Safe)

```
$'()*+,-/23579:[]aelnouv'*,-23:[]lu',-23]',

```

This is a script that requires input from the command line (it's not a function). It's floating point accuracy (so no rounding).

**Solution:**

> `eval(-[5,-2:3,-3:2]+['nlouu*$$',39,']2/7'])`

**Explanation:**

> `eval( <string> ) % Evaluated the string inside the brackets and executes it`
> Everything inside the `eval` call gets evaluated to `input('')^2.5`
> **How?**
> `-[5,-2:3,-3:2] % A vector: [-5, 2, 1, 0, -1, -2, -3, 3, 2, 1, 0, -1, -2]`
> `['nlouu**$$',39,']2/7'] % This is a string: nlouu**$ concatenated with the number`
> `. % 39 (ASCII ']'), and ']2/7'. Thus, combined: 'nlouu**$$']2/7'`
> Adding the first vector to this string will convert it to the integer vector:
> `[105, 110, 112, 117, 116, 40, 39, 39, 41, 94, 50, 46, 53]`
> `eval` implicitly converts this to a string, and these numbers just so happens to be: `input('')^2.5`

# Answer
> 7 votes
# C, 50 bytes (Cracked by fergusq)

```
%(())   ,-12225;>\\aaabbdddeeefffllnoooprrttuuuuw{

```

Uses standard IEEE754 rounding. As noted by fergusq's answer, may require `-lm` depending on your compiler.

# Answer
> 6 votes
# Swift - 64 bytes (Safe)

```
prot Fdnufi;nooitamunc xetgru(->atl)Ior:n{tFn pg,F(ao.o25t)(w)l}

```

No rounding, and displays a `.0` even if the result is an integer.

# Answer
> 6 votes
# Mathematica, 131 bytes, non-competing?, cracked

*This has been **cracked by @lanlock4**! However, I still have internet points to bestow on someone who finds the original solution, where all the characters are actually needed....*

```
f[y_]:=With[{x=@@@@@@#####^^&&&(((()))){{}}111111,,+-/y},Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]]

```

This is intended as a puzzle. Although you may use the above characters however you want, I certainly intend for the answer to follow the form

```
f[y_]:=With[{x=
    @@@@@@#####^^&&&(((()))){{}}111111,,+-/y
},Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]]

```

where the first and third lines are just a wrapper to make the rounding and display legal (it writes every output to exactly three decimal places, rounded), and the second line is the scrambled version of the guts of the code. Sample outputs:

```
6 -> 88.182
9 -> 243.000
9999 -> 9997500187.497

```

(Mathematica is non-free software, but there is a Wolfram sandbox where it is possible to test modest amounts of code. For example, cutting and pasting the code

```
f[y_]:=With[{x=
    y^2.5
},Print[#,".",IntegerString[Round@#2,10,3]]&@@QuotientRemainder[1000x,1000]]

```

defines a function, which you can subsequently call like `f@6` or `f[9]`, that does the same thing as the unscrambled version of the code above. So does this really have to be non-competing?)

# Answer
> 4 votes
# C#, 172 bytes (Cracked by SLuck49)

```
       (((((())))))***,,,,......1225;;;;;;<====>CFLMMMMMPPPRSSSSSWaaaaaaabbbbcccddddddeeeeeeeeeeegghiiiiiiiillllllmmnnnnnnnooooooooqqqqrrrssssssssstttttttttuuuuuuuvvwyy{{}}

```

This code is a full program.

There are seven space characters at the start.

The input is read form STDIN and printed to STDOUT. The result is in `double`, no rounding done.

Original Code ungolfed:

```
using System;
using S = System.Console;

class P
{
    static void Main()
    {
        var t = S.ReadLine();
        double q = int.Parse(t);
        Func<double, double, double> M = Math.Pow;
        S.Write(M(q, 2 * .25) * M(q * q, 1));
    }
}

```

# Answer
> 4 votes
# Haskell, 16 bytes (Cracked by @nimi)

```
()*...25=eglopxx

```

No particular rounding

# Answer
> 4 votes
# R, 28 bytes (Cracked by @Flounderer)

```
funny(p1)-tio(^*^)/pc(2)<p2;

```

Standard R floating-point accuracy.

# Answer
> 4 votes
## Ohm, 11 bytes

```
M ⁿ¡D¼½;+1I

```

Use with `-c` flag. Uses CP-437 encoding.

# Answer
> 3 votes
# Python 2, 60 Bytes (Cracked by @notjagan)

```
 3n0)4  5)594p3(p5*5i9t4542)0/*((8(t.84- 90945 u)i*48/95n8r8

```

No rounding involved. Accurate up to 10 decimal digits.

# Answer
> 3 votes
# Inform 7, 71 bytes (Cracked by @Ilmari Karonen)

```
""()**-..:[]
                 RT
aaaabeeeffilmmnnnnnooooooqrrrrrssstuuy

```

The code includes 17 spaces and 2 new lines. This is a full Infrom 7 program defining a function that prints the result with a precision of 5 decimal places.

# Answer
> 3 votes
## Haskell, 64 bytes, (cracked by Laikoni)

```
$$$$$$(((((())))))**,...0<<<>>>[]cccccdddeffiiiiilloopppprrsstuu

```

Standard Haskell floating point operations.

My original version is:

> product.((($succ$cos$0)(flip(\**).)\[id,recip\])).flip(id)

# Answer
> 3 votes
## JavaScript (ES7), 20 bytes (Cracked by @IlmariKaronen)

```
****..22255666=>____

```

Standard JavaScript precision.

# Answer
> 3 votes
## R, 19 bytes (Cracked by @Steadybox)

```
mensana(4*5*c(.1)):

```

Standard rounding

## R, 33 bytes (Cracked by @plannapus)

```
(rofl(17)^coins(2*e)/pisan(10))--

```

## R, 31 bytes (Cracked by @plannapus)

`h=f`l`u`n`c`t`i`o`n([],[])^(.9)`

# Answer
> 3 votes
# Python 3.6, 59 bytes

```
ba(,b5,d' (,a/([m:'-)oa)(bl*aadplma dba](r)d )l*d,:)*m:-mml

```

No rounding. Floating point accuracy.

# Answer
> 3 votes
# Fourier, 124  119 Bytes

```
((()))*******--011111<=>>>HHINNNN^^^eeehhhhkkkkmmmmmmmmmmmmmmmmossuuuuuuuuuuuuuuuuu{{{{{{{{{{}}}}}}}}}}~~~~~~~~~~~~~~~~

```

There are no whitespaces or newline characters.

Square root is rounded to the nearest whole number because Fourier doesn't seem to handle anything other than integers (and since @ATaco got permission, I hope this is ok)

fixed an editing mistake, if you were already cracking this, the previous was functional

Realized that I had misunderstood part of the code, and was using more characters than I needed to

If I missed anything let me know

# Answer
> 3 votes
# Octave, 30 bytes (Safe)

```
(((((())))))**++/:@eeeiiijmsu~

```

A bit simpler than my first one. Shouldn't be too hard, but it's hopefully a fun puzzle.

# Answer
> 2 votes
# Javascript, 123 bytes, Cracked by notjagan

```
 """"""((((((((()))))))))********,--.....//2;;======>>Seeeeeeegggggggggggghhhhhhhhhhhilllllnnnnnnnnnnorrrsstttttttttttttu{}

```

This code is a full function

There is one space character at the very start of the list of characters

The rounding of this answer is the floating point precision for Javascript, accuracy is within 10^-6 for every answer.

Got shorter because the precision didn't need to be maintained quite as high as I thought it did.

I had realized that it would be much easier to solve than I initially had made it but it was already there :P

**Initial code:**

```
g=t=>t-(t*t-n)/("le".length*t);e=h=>{n=h*h*h*h*h,s=2**(n.toString("ng".length).length/"th".length);return g(g(g(g(g(s)))))}

```

Newtons method, applied 5 times from the closest power of 2

# Answer
> 2 votes
## OCaml, 13 bytes (Cracked by @Dada)

```
2*fn-5f>f*u .

```

No rounding (within IEEE 754 scope).

# Answer
> 2 votes
## Excel VBA, 59 bytes (Safe)

```
?(())*..//11124AAAAFPSW[[]]^acceehiiiiklnnnnoooppqrrstttttu

```

No particular rounding.
Uses the Immediate Window.

# Answer
> 2 votes
# RProgN 2, 6 Bytes (Cracked by @notjagan)

```
š2]^*\

```

No rounding, displays many decimal places. Does not display any for an integer solution.

# Answer
> 2 votes
# Octave, 42 bytes (Safe)

```
((((()))))+,,,-//01111111@[]^mnooorrssst~~

```

No rounding. Floating point accuracy.

### Intended solution

> `@(s)norm(roots([-1,~1,s^(10/(1+1))]),1/~1)`
> Try it online!

# Answer
> 2 votes
# Python 3.6 - 52 bytes (Cracked by @xnor)

```
f=lambda x:x**125*77*8+8/5/((('aafoort.hipie.xml')))

```

Standard Python rounding

# Answer
> 2 votes
## Ruby, 35 bytes (cracked by xsot)

```
'a'0-a<2<e<2<l<3<v<4<4<4<5<5<6>7{9}

```

No rounding. Floating point accuracy.

# Answer
> 2 votes
## C#, 112 bytes (cracked by Emigna)

```
     ((((())))),.....25;;;=CCLMMPPPRSWaaaaaaabbbccdddeeeeeeeeghiiiiiillllmnnnnnooooooorrrsssssssstttttuuvvwy{{}}

```

no rounding done

```
using System;
class P
{
    static void Main()
    {
        var b=double.Parse(Console.ReadLine());
        Console.Write(Math.Pow(b,2.5));
    }
}

```

# Answer
> 2 votes
# 05AB1E, 47 bytes

```
)*.2555BFHIJJKKKPQRST``cgghilnstwx}«¹¹Áöž‚„…………

```

Does not round, uses floating point accuracy.

# Answer
> 2 votes
## CJam, 8 bytes (Cracked by E~~n~~mig~~m~~na)

```
WYdYl##+

```

No rounding. Uses double precision.

# Answer
> 2 votes
# Fireball, 8 bytes (Cracked by Roman Gräf)

```
♥1Z*^²/♥

```

Does not round, uses floating point precision.

Code surrounded with hearts ;)

Should pretty easy to crack, once you have a look into Fireball.

# Answer
> 2 votes
# R, 32 bytes (Cracked by @plannapus)

```
i=na*0.5f*n(2*s*cos(t))*22*s*12u

```

Standard floating-point accuracy.

# Answer
> 2 votes
## Excel, 26 bytes

```
=(())*//11122AAAIINPQRSST^

```

No rounding.

*Note: As Excel is paid software, this works also in free LibreOffice*

# Answer
> 2 votes
# JavaScript + paper.js, 210 bytes (safe)

This one's fun. No comments for you, and no strings either.

paper.js is a vector graphics framework. This is a full program that takes input via a prompt and outputs graphically, because it's possible. There is no rounding and floating-point accuracy (I think).
Reference
Try code here

```
Math.tan(prompt(a,0));
leg Rave, ew(0,0),ectoPlasm = Real new qrt(;
marvin atTax M(en) in vr;tent * hat.o = Mat
nottet near(0a,a) w cgee;
brown.cern(lantern) ;( w 0,0.art;vict.o brace
r=v=,h.c.)an=.flClr= Cor0)

```

Edit: Just noticed (my fault for not reading properly)

> The shortest safe answer by the end of April will be considered the winner.

Well, oops.

Original solution:

```
var a = prompt(0,0);
var r = new Rectangle(0,0,a,a).area;
var t = new Rectangle(0,0,Math.cbrt(a),Math.sqrt(Math.cbrt(a))).area;
var n = new PointText(view.center);
n.content = r * t;
n.fillColor = new Color(0);

```

Try code here

# Answer
> 2 votes
# NO!, 41 bytes (Cracked by Emigna)

NOOO! NO! can finally compete! ~~Although no-one will be bothered to crack this anyway :(~~

Anyway *sigh* here's the code:

```
NNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO??
nnno!

```

Full list of commands here. Coded in Python so uses Python rounding.

NOOOOOOOOO!!!!!!!! Someone cracked it. (Curse you Emigna!) (just kidding!)

# Answer
> 2 votes
## C, 115 bytes, (Cracked by @tehtmi)

```
""%&&((((((()))))))******++++,..//01122233388;;;;;;<====>>   bbbdddeeeefffggillllllllllnnnnnnnnoooooooooooprrtuuu{}

```

Notice that it does include 3 spaces.

Always outputs 3 exact decimals, rounded to the closest thousandth.

Should be rather fun to crack as it doesn't involve any built-in to compute powers or square roots, as opposed to most (cracked) solutions so far.

Example run (which also gives you a few small hints):

```
int main() {
  int n[] = {4, 6, 9, 25};
  for (int i = 0; i < 4; i++) {
    printf("%i => ", n[i]);
    o(n[i]);
    printf("\n");
  }
}

```

outputs:

```
4 => 32.000
6 => 88.182
9 => 243.000
25 => 3125.000

```

Tested with both gcc and clang, with no compilation flag needed.

---

It's been cracked; the original solution was

```
o(double n){long o=2.303e18+(*(long*)&n>>1);double l=*(double*)&o;for(o=2;o++<8;)l=(l+n/l)/2;printf("%.3f",l*n*n);}

```

which uses a magic constant in the same spirit as the infamous fast inverse square root algorithm to do just a handful of Newton iterations (as opposed to several thousands in the cracked solution)

# Answer
> 2 votes
# HODOR, 172 bytes, Cracked by Emigna

```
Walder
Hodor Hodor Hodor Hodor Hodor Hodor
Hodor Hodor Hodor Hodor Hodor
Hodor Hodor Hodor Hodor
Hodor Hodor Hodor
Hodor Hodor
Hodor
hodor hodor
HODOR HODOR!!!!!!!,,,,,,..?

```

let me know if I missed anything

# Answer
> 2 votes
# 05AB1E, 35 bytes

```
ö£=s‰sr2xöR+RM0`.T"YVBYCDž„¨¨"6£H-L

```

This one took me a while to make.

There's some double quotes in there, so you can surround as much of the code as you want in them.

No rounding, decimal point precision.

# Answer
> 2 votes
# Lua 5.3, 110 bytes (safe)

```
((((()))))**,,,,,-....=====>~             aaaaaaaaacddddeeeffhhhiiiiiiilllmmnnnnnnooopppppprrrrrrrsssssssstttt

```

Calculations are standard using Lua numbers (ie double in common implementations). Tested using PUC-Rio interpreter. (I hope I didn't do anything bad, but I think it is reasonable...)

This is a full program with input from the command line.

Original solution:

> `for a,r in pairs(math)do l,s=pcall(r,-math.pi)if s~=s and a>=(i or a)then i,p=a,r end end s=...print(s*s*p(s))`

Explanation:

> `math.sqrt` is retrieved from the math library by looping through the `math` table and looking for functions that return NaN (and don't throw an error) when applied to negative pi. There are only a few functions like this, and `sqrt` is alphabetically last.

# Answer
> 2 votes
# 05AB1E, 23 bytes (Cracked by Emigna)

A totally different approach than my previous answers :)

```
$++/02;@DDDGHP\rrszz}¹ž

```

No rounding.

**Example runs**

```
In   -> Out
0    -> 0
4    -> 32.0
6    -> 88.18163074019441
25   -> 3125.0
7131 -> 4294138928.8967724

```

# Answer
> 2 votes
# Javascript, 15 17 bytes, Cracked by @Emigna

```
(x=>x****-125*10)

```

Solution:

> `x=>x**(25*10**-1)`

# Javascript, 18 bytes, Again, Cracked.

```
x=>x**-(!3.5++)[];

```

Solution:

> `x=>x**(3-!+[]+.5);`

# Answer
> 1 votes
# Python 3.6 - 15 bytes (Cracked by Kritixi Lithos)

```
axx 2*d:b.*5mal

```

Standard rounding precision of Python

# Answer
> 1 votes
# C++, 100 bytes (Cracked by @fergusq)

```
#.leiha2dm"
tuchn"crmueie<linaatt#dso
fameng pcae sli;t>dt nnsiuno;s mnpti;ouic(<){n(a;>w<n>n)co.,5}

```

Standard C++ rounding precision

# Answer
> 1 votes
# Python 2, 44 Bytes (Cracked by @fəˈnɛtɪk)

```
np5w***i0(0(0r0n0t+iarn00p0)_(0tu00i50.0)) t

```

Has accuracy up to 10 decimal digits (I think). No rounding involved and there is a space involved.

# Answer
> 1 votes
# Scala, 19 bytes (Cracked by @math\_junkie)

```
)>,/2(=addd.hmoptw5

```

This is a function of type `Int=>Double`.

# Answer
> 1 votes
# C, 60 bytes (Cracked by @Dave)

```
1(root, flat*fat bern**lotr);pw(f{bus(--q.b4/q0*1-2)})(b>1)b

```

Standard C float accuracy.

# Answer
> 1 votes
# 05AB1E, 4 bytes (Cracked by @Mr. Xcoder)

Must be really easy to crack, but I'll still post it here

```
n*t¹

```

Normal rounding

# Answer
> 1 votes
# 05AB1E, 23 bytes (Cracked by Emigna)

Another try

```
A9n*¥="'q?:@->%t#[{¹!.

```

Normal rounding

# Answer
> 1 votes
# 05AB1E, 22 bytes, Cracked by user4867444

```
+/;DDDFLPT_nz}©®¹¹¹Ïè›

```

**Example runs**

```
In -> Out
0  -> 0
4  -> 32.0
6  -> 88.18163074019441

```

**Original solution**

> `LnD¹›_Ï®©èTFD¹/z+;}¹DP`

# Answer
> 1 votes
# Javascript (ES6), 39 bytes (Cracked)

```
(((())))*....57===>Mabcefghlllloprttxxx

```

The rounding is normal floating point precision for Javascript.

# Answer
> 1 votes
# HODOR, 198 bytes (Cracked by wwj)

*NB: Had to correct the code!*

Uses the brand-new `hodor` command (Updated Saturday)! Yes, I know I'm not supposed to say but it's pretty obvious anyway and (as far as I know) I'm the only person who can code in Hodor so worth some help :)

This is the code: and the full list of commands is here

```
H!HDHrlrHrhoooo!h, oo!do ordoH!oHHd
dodHrodorooooHdddoooOOo ddro roorrro.r,H
ooO ooHr,
HdHo oo H!O?Hd, oo,, Hdodhd oor, dd!HHrDo aod
rdroHdH,HrRr
 o o RHrdHoo,oro Hr
oo
oHoer o r oddodo,rr
rdd!WrH d

```

# Answer
> 1 votes
# JavaScript (ES7), 24 bytes (Safe)

```
()+01488M``aabeiijlooqtv

```

Standard 64 bit floating point rounding.

---

### Solution

> `eval(atob`8j0+8ioqMi41`)`

### Tests

```
console.log(eval(atob`8j0+8ioqMi41`)(0));    // 0
console.log(eval(atob`8j0+8ioqMi41`)(1));    // 1
console.log(eval(atob`8j0+8ioqMi41`)(2));    // 5.656854249492381
console.log(eval(atob`8j0+8ioqMi41`)(4));    // 32
console.log(eval(atob`8j0+8ioqMi41`)(10));   // 316.22776601683796
```

# Answer
> 1 votes
# Stacked, 64 bytes

```
:u#{`E2t#tv',lnp~.iuP#2qr+t,'3m3em`,#9''.::mluls on\ts r:a\:+.S0

```

Good luck.

Result for `6`: `88.181630740194411535`.

# Answer
> 1 votes
# bash, 158 bytes

This program requires a 64 bit processor to function. Pass input number as argument; result on stdout. I believe rounding is floor function. This program actually does decimal output. If you got integer only keep trying.

```
^=======|       -!
///////......
''(((((((((((())))))))))))
[]$$$$$$$$$****
\\\\\\
#++
000000000000
111111222
bcdddeeeehhhiill
nn
NNNNNNoooOOOOOOO
sssSSSS
tw

```

# Answer
> 1 votes
## C#, 135 bytes (cracked by SLuck49)

```
      (((((()))))),,-..../11;;;CCEILMMMPPPRRSSWaaaaaaacccdddeeeeeeeeggghiiiiiiiillllmmnnnnnnnnoooooooorrsssssssssssttttttttuuuvwyy{{}}

```

no rounding done
(First try)

# Answer
> 1 votes
# Javascript (ES7), 53 bytes (safe)

```
(((())))*++++,,,/0233346=====>>[[]]aaaabbbccelootttuv

```

The rounding is normal floating point precision for Javascript.

Tested this in the latest Chrome and FF.

---

### Solution

> `u=>(o=(t,c,a=o+c,b=a[t])=>eval(a[42]+b+b+3*30/t))(36)`
> This works because `a=o+c` is `'(t,c,a=o+c,b=a[t])=>eval(a[42]+b+b+3*30/t)undefined'`.
> So `a[42]='u', a[36]='*', 3*30/36=2.5`, making `eval('u**2.5')`.

### Tests

```
var f=u=>(o=(t,c,a=o+c,b=a[t])=>eval(a[42]+b+b+3*30/t))(36);
console.log(f(0));    // 0
console.log(f(1));    // 1
console.log(f(2));    // 5.656854249492381
console.log(f(4));    // 32
console.log(f(10));   // 316.22776601683796
```

# Answer
> 1 votes
# 05AB1E, 15 bytes, (Cracked by Emigna)

```
+/01;DDDFMPs}¹ž

```

Normal rounding

**Example runs**

```
In   -> Out
0    -> 0
4    -> 32.0
6    -> 88.18163074019441
25   -> 3125.0
7131 -> 4294138928.896773

```

# Answer
> 1 votes
# Python 2.7, 174 bytes

```
_cc*gnta(dkree_rtrto._i9kuc_ l5_r_cctbimWka(Wihlkeu_5_eur_rri_keeluc4clrp ..u_)(HohhH)ap5o(trbnord_ir9/*in)_clrikroap.ie.tg_obkfkseeeel*in2Hkdu*ffmo4lWlrncde_22);doodt a49 hu

```

# Answer
> 1 votes
# 05AB1E, 27 bytes - safe

Yet another totally different approach from my previous answers.

```
(/1DFFOOPT`ins}}©®¹¹Ðèëž‚‚‹

```

No rounding.

**Example runs**

```
In   -> Out
0    -> 0
4    -> 32.0
6    -> 88.18163074019441
25   -> 3125.0
7131 -> 4294138928.896773

```

---

**Solution**

```
Ð(‚žFFDO©n¹‹i`T/ë1è®s}‚}O¹P

```

This is simply computing the square root with a trivial (and very dumb) trial-and-error strategy...

**Detailed explanation**

```
Ð(‚žFFDO©n¹‹i`T/ë1è®s}‚}O¹P
Ð(‚                         # triplicate the input, reverse the sign of the last copy, and wrap the last 2 items in a list, which going forward is going to be the list of our current sqrt approximation and of the next decrement in our dumb search (so it starts at [x, -x])
   žFF                      # 16384(!) times, do
      D                     # duplicate the current [value, decrement] list
       O©                   # compute the sum value + decrement, and also save it in the register
         n                  # compute the square of that potential new approximation of the square root
          ¹‹                # and compare it with the input
            i               # if our new approximation is smaller than the actual square root, then
             `              # push the flattened [value, decrement] list to the stack as value, decrement
              T/            # and divide our decrement by 10
                ë           # else (our new approximation is still bigger than the actual square root, then)
                 1è         # extract the current decrement from the list
                   ®        # retrieve the new approximation from the register
                    s       # and switch them to again have them in the value, decrement order
                     }      # end of the if
                      ‚     # no matter which branch of the if we went into, the last 2 items of the stack are now the new approximation and the new decrement, in order: wrap them in a list for the next loop iteration
                       }    # end of the loop
                        O   # replaces the output of the loop (the final [value, decrement] list) by its sum, which given the very small value of the decrement at that point is pretty much the same as our final approximation of sqrt(x)
                         ¹  # push another copy of x; the stack is now [x, sqrt(x), x] (where the first x comes from the very first copy of the initial Ð)
                          P # computes the product of the whole stack

```

Try it online!

# Answer
> 1 votes
# Java 7, 224 bytes (safe)

```
      ""&&((((((((()))))))))***++++++,,,,,,,-......//000000001113344556677;;;;;;;;;;<<======>>LLSS[\\\\\]aaaaaaaabbbbcccccccccdddddddddeeeeffffggggggiiiiiiiklllmmmnnnnnnnoooooooopprrrrrrssssssssssssstttttttttttuuuuuuuuvy{{}}

```

Look I know it's a lot of bytes but it's a full java program so you can expect a good portion of it to be basic boiler plate... and surely there are no tricks being employed. Output has 3 decimal places and operates the same as the examples in the challenge. I could probably make this harder but part of the fun is seeing how you end up breaking this and solving it in an unintended way. Good luck!

P.S. that's 6 spaces in case you're curious.

**Example Runs**

```
0    ->          0.000
4    ->         32.000
6    ->         88.182
25   ->       3125.000
7131 -> 4294138928.897

```

Solution:

```
class u{static double s,a,c,n,d,g,t;public static void main(String...u)\u007bd=Long.parseLong(u[0]);n=d/(c+++1);for(;g<(t=13);g++){for(;s<n;s+=c)if(s*s>d&&(s-=c)>0)break;c/=t;}System.out.format("\045\0563\146",s*d*d);}\u007d

```

Ungolfed:

```
class u{
static double s,a,c,n,d,g,t;               // static doubles default to 0.0
public static void main(String...u)\u007b  // had to use 1 or 2 unicode escapes for fun

d=Long.parseLong(u[0]);
n=d/(c+++1);                              // get d/2 while also making c=1

for(;g<(t=13);g++){                       // get 13 decimals of precision
  for(;s<n;s+=c)                          // increment the current decimal position
    if(s*s>d&&(s-=c)>0)break;             // square the current value and make sure we're still below the target
  c/=t;
}
System.out.format("\045\0563\146",s*d*d); // java also has octal string escapes
}
\u007d

```

# Answer
> 1 votes
# Vyxal, 12 bytes, Cracked by lyxal

```
`25/n:([|eĖĖ

```

Have fun!

# Answer
> 1 votes
# Vyxal, 14 bytes

```
`25/$n:([|tėĖĖ

```

On to round 2!

# Answer
> 0 votes
# Python 2, 39 bytes (cracked by @Mr. Xcoder)

```
q=a(lxt)mh*mprf.hr
ax tttaixxmb :m*asod

```

Standard Python float rounding.

# Answer
> 0 votes
# C#, 179 bytes, safe

```
(((((((((((((())))))))))))))*****++,,,,,-..///////000000000111112222222222:;;;<=====>>>>?AFM[[[[[[[[[[[]]]]]]]]]]]abbbcdddddeeeeehllllnnnnnnnnnnnnnooooooooooorrrrrsttuuuuuww{{{}}}

```

There is no rounding. The code forms a lambda that takes an `int` and returns a `double`.

---

**Solution**

```
n=>{Func<double[],double>r=null;return(r=(o)=>(Math.Abs(o[1]-o[2])>=0.0000001)?r(new[]{o[0],o[2],(o[2]+(o[0]/o[2]))/2}):o[2])(new[]{n,(n*1d)/2,((n*1d)/2+(n/(n*1d)/2))/2})*(n*n);};

```

**Exploded Solution**

```
(int n) =>
{
    Func<double[], double>r = null;

    r = (double[] o) =>
    {
        if(Math.Abs(o[1]-o[2]) >= 0.0000001))
        {
            return r(new[]{ o[0], o[2], (o[2] + (o[0] / o[2])) / 2 });
        }
        else
        {
            return o[2];
        }
    };

    var initialO = new[]
    {
        n,
        (n * 1d) / 2,
        ((n * 1d) / 2 + (n / (n * 1d) / 2)) / 2
    };

    return r(initialO) * (n * n);
};

```

# Answer
> 0 votes
# Python 3.6 - 64 bytes (Cracked by user4867444)

```
f1;7*x0d/2p6*mm1i*99 5 a o o t(a bphpx:m38af4r*1221=s2rm.0itlpa)

```

Extremely high precision. No rounding.

**ORIGINAL SOLUTION:**

> `from math import pi as p;f=lambda x:x**(p**3/12.402510672119928)`

# Answer
> 0 votes
# PHP, 61 Bytes (Safe)

No rounding

```
a$rians=)n$$/rnd=aa(*gt$)gg*g)(g)$(r|pg-n(+(;$r($)(tr)=r)ngq.

```

## Original Solution

```
print($argn**(sqrt(((a|n).rd)($g=$argn==$argn))/($g+$g)-$g));

```

# Answer
> 0 votes
## Python 2.7, 41 bytes

```
(sexypint=='pint')**(55.0)**fur==(.3%0%y)

```

rounding done by "%.3f"

---
Tags: code-golf, number, arithmetic, cops-and-robbers
---


title: From 0 to 2^n - 1 in POPCORN order

text:
# Question
Title: From 0 to 2^n - 1 in POPCORN order
... Ah sorry, no popcorn here, just POPCNT.

Write the shortest **program** or **function** which takes in a number `n` and **output** all integers from 0 to 2n \- 1, in ascending order of *number of 1 bits in the binary representation of the numbers* (popcount). No duplicates allowed.

The order of numbers with the same popcount is implementation-defined.

For example, for `n = 3`, all these output are valid:

```
0, 1, 2, 4, 3, 5, 6, 7
[0, 4, 1, 2, 5, 3, 6, 7]
0 4 2 1 6 5 3 7

```

The input and output format are implementation-defined to allow the use of language features to further golf the code. There are a few restrictions on the output:

* The numbers must be output in decimal format.
* The output must contain a reasonable separator between the numbers (trailing separator allowed, but not leading).

Line feed (`\n`), tab (`\t`), space, `,`, `.`, `;`, `|`, `-`, `_`, `/` are quite reasonable separator. I don't mind additional spaces for pretty printing, but don't use letter or digits as separators.
* The numbers and separators can be surrounded by `[ ]`, `{ }` or any array or list notation.
* Don't print anything else not stated above.

### Bonus

Multiply your score by **0.5** if your solution can generate the number on the fly. The spirit of this bonus is that if you were to directly convert your printing solution to a generator, the generator only uses at most O(n) memory where n is the number of bits as defined above. (You don't have to actually convert your solution to generator). Note that while I impose n \<= 28, the memory needed to store all numbers still grows exponentially, and a naive sorting solution would hog up at least 4 GB of memory at n = 28.

Please add some simple explanation of how your solution works before claiming this bonus.

# Answer
# Pyth, 9 bytes

```
osjN2U^2Q

```

`o`rder by the `s`um of the base 2 representation (`jN2`) over the range (`U`) of `2 ^ Q`.

(`Q` = `eval(input())`).

Try it here.
> 10 votes

# Answer
# Python 2, 72 bytes * 0.5 = 36

```
N=1<<input()
for k in range(N*N):
 if bin(k%N).count('1')==k/N:print k%N

```

Try it online!

A new method for this now-ancient challenge. The less-golfed below below might be easier to understand:

**87 bytes**

```
n=input()
for i in range(n+1):
 for x in range(2**n):
  if bin(x).count('1')==i:print x

```

Try it online!

We loop over target popcounts `i` in increasing order, and for each one iterate over the `n`-bit numbers and prints those with exactly `i` set bits.

Even though this loops over the `n`-bit numbers many times, it still satisfies the efficiency bonus criteria of only using `O(n)` memory if the loop were converted to a generator. If fact, the golfed code allocates `n` bits to the target popcount as well as `n` bits to the number being checked. They are stored as a `2*n`-bit number, which allows counting up this single number and extracting the first and last `n` bits as needed.

---

# Python 2, 59 bytes

```
lambda n:sorted(range(1<<n),key=lambda x:bin(x).count('1'))

```

Try it online!

A short sorting-based approach that does not qualify for the bonus.

---

# Python 2, 75 bytes * 0.5 = 37.5

```
N=2**input()-1
v=N-~N
while v:t=1+(v|~-v);v=N&t|~-(t&-t)/(v&-v)/2;print v^N

```

Try it online!

Repeatedly generates the next highest `v` with the same POPCOUNT by this bit-twiddling algorithm.

Actually, it turned out easier to generate them in decreasing pop-count, then print the complement to make it increasing. That way, then `v` overflows `2**n`, we simply remove all but `n` bits with `&N` where `N=2**n-1`, and that gives the smallest number one popcount lower. That way, we can just do one loop. There's probably a better solution that directly finds the next *lower* number with the same POPCOUNT.

Due to a fencepost issue, we need to start with `v=2**(n+1)-1` so that the operation produces `v=N-1` on the first loop.

Output for `4`:

```
0
8
4
2
1
12
10
9
6
5
3
14
13
11
7
15

```
> 7 votes

# Answer
## J, 19 characters, no bonus.

```
[:(/:+/"1@#:)@i.2^]

```
* `2 ^ y` – two to the power of `y`.
* `i. 2 ^ y` – the integers from `0` to `(2 ^ y) - 1`.
* `#: i. 2 ^ y` – each of these integers represented in base two.
* `+/"1 #: i. 2 ^ y` – the sums of each representation
* `(i. 2 ^ y) /: +/"1 #: i. 2 ^ y` – the vector `i. 2 ^ y` sorted by the order of the items of the previous vector, our answer.
> 5 votes

# Answer
## Python, 63 chars

```
F=lambda n:`sorted(range(1<<n),key=lambda x:bin(x).count('1'))`

>>> F(3)
'[0, 1, 2, 4, 3, 5, 6, 7]'

```
> 3 votes

# Answer
**C 179 * 0.5 = 89.5**

```
main(){int n,i=0,m,o;scanf("%d",&n);m=~((~0)<<n);for(;n--;++i){for(o=0;o<m;++o){int bc=0,cb=28;for(;cb--;)bc+=o&(1<<cb)?1:0;if(bc==i)printf("%d ",o);}}printf("%d\n",m);return 0;}

```

**EDIT: 157 * 0.5 = 78.5**

```
main(){int n,i=0,m,o;scanf("%d",&n);m=~((~0)<<n);for(++n;n--;++i){for(o=0;o<=m;++o){int bc=0,cb=28;for(;cb--;)bc+=o&(1<<cb)?1:0;if(bc==i)printf("%d ",o);}}}

```

**EDIT: 132 * 0.5 = 66**

```
main(){int n,i=0,m,o;scanf("%d",&n);m=~((~0)<<n);for(++n;n--;++i){for(o=0;o<=m;++o){if(__builtin_popcount(o)==i)printf("%d ",o);}}}

```

or a bit nicer formatted:

```
main()
{
    int n, i = 0, m, o;
    scanf("%d", &n);
    m = ~((~0) << n);
    for(++n; n--; ++i)
    {
        for(o = 0; o <= m; ++o)
        {
            if (__builtin_popcount(o) == i)
                printf("%d ", o);
        }
    }
}

```

What it does?

```
m = ~((~0) << n);

```

calculates the last number to show (pow(2, n) - 1)

```
    for(++n; n--; ++i)
    {
        for(o = 0; o <= m; ++o)
        {

```

the outer loop iterates over the bit count (so 0 to n-1) while the inner loop just counts from 0 to m

```
            if (__builtin_popcount(o) == i)
                printf("%d ", o);

```

On x86 there is the POPCNT instruction that can be used to count the set bits. GCC and compatible compilers may support the \__builtin\_popcount function that basically compiles to that instruction.
> 3 votes

# Answer
## Mathematica, 50 46

```
SortBy[Range[0,2^#-1],Tr@IntegerDigits[#,2]&]&

```

.

```
SortBy[Range[0,2^#-1],Tr@IntegerDigits[#,2]&]&

{0, 1, 2, 4, 8, 16, 3, 5, 6, 9, 10, 12, 17, 18, 20,
24, 7, 11, 13, 14, 19, 21, 22, 25, 26, 28, 15,
23, 27, 29, 30, 31}

```
> 3 votes

# Answer
# CJam, 13 bytes

```
2ri#,{2b1b}$p

```

Pretty straight forward implementation.

**How it works**:

```
2ri#,             "Get an array of 0 to 2^n - 1 integers, where n is the input";
     {    }$      "Sort by";
      2b1b        "Convert the number to binary, sum the digits";
            p     "Print the array";

```

Try it online here
> 2 votes

# Answer
# K (ngn/k), ~~18~~ ~~9~~ 8 bytes

-9 bytes from @ngn's improvements

-1 byte from using `where` instead of `take`

```
<+/!2+&:

```

Try it online!

A tacit function, equivalent to `{<+/!2+&x}`.

* `2+&:` generate `x` 2's
* `!...` generate "odometer" of the input (in this case this provides the binary representation of the numbers from 0 to pow(2,x))
* `+/` sum column-wise
* `<` "grade up" the sums (i.e. sort them by the number of 1's in the binary-representation of each value)
> 2 votes

# Answer
# Husk, 8 bytes

```
ÖoΣḋŀ`^2

```

Try it online!

```
     `^2  flip ^, partially applied, gets fully applied with implicit input, 2 ^ n
    ŀ     range from [0, n)
Ö         sort by
 o        composed function
  Σ       sum
   ḋ      binary digits

```
> 2 votes

# Answer
# Bash + coreutils, 66

One to get you started:

```
jot -w2o%dpc $[2**$1] 0|dc|tr -d 0|nl -ba -v0 -w9|sort -k2|cut -f1

```
> 1 votes

# Answer
# Mathematica, 26

```
Tr/@(2^Subsets@Range@#/2)&

```

Example:

```
Tr/@(2^Subsets@Range@#/2)&[4]

```

> {0, 1, 2, 4, 8, 3, 5, 9, 6, 10, 12, 7, 11, 13, 14, 15}
> 1 votes

# Answer
# JavaScript (ES6) 41 (82\*0.5)

The simplest way, golfed

```
F=b=>{
  for(l=0;l<=b;l++)
    for(i=1<<b;i;t||console.log(i))
      for(t=l,u=--i;u;--t)
        u&=u-1;
}

```

**Ungolfed**

```
F=b=>
{
  for (l = 0; l <= b; l++)
  {
    for (i = 1 << b; i > 0; )
    {
      --i;
      for (t = 0, u = i; u; ++t) // Counting bits set, Brian Kernighan's way
        u &= u - 1;
      if (t == l) console.log(i);
    }
  }
}

```

**Test** In Firefox/FireBug console

```
F(4)

```

> 0
> 8
> 4
> 2
> 1
> 12
> 10
> 9
> 6
> 5
> 3
> 14
> 13
> 11
> 7
> 15
> 1 votes

# Answer
# Haskell, (87 * 0.5) = 43,5

```
f n=[0..n]>>=(\x->x#(n-x))
a#0=[2^a-1]
0#_=[0]
a#b=[1+2*x|x<-(a-1)#b]++[2*x|x<-a#(b-1)]

```

Usage example: `f 4`, which outputs `[0,1,2,4,8,3,5,9,6,10,12,7,11,13,14,15]`

How it works: neither sorting nor repeatedly iterating over \[0..2^n-1\] and looking for numbers containing i 1s.

The `#` helper functions takes two parameters `a` and `b` and constructs a list of every number made up of `a` 1s and `b` 0s. The main function `f` calls `#` for every combination of `a` and `b` where `a+b` equals `n`, starting with no 1s and `n` 0s to have the numbers in order. Thanks to Haskell's laziness all those lists don't have to be constructed completely in memory.
> 1 votes

# Answer
## Ruby 47 chars

Much like the Python one from @KeithRandall :

```
f=->n{(0..1<<n).sort_by{|x|x.to_s(2).count ?1}}

```
> 1 votes

# Answer
# Jelly, 7 bytes

```
2*’BS$Þ

```

Try it online!

## Explanation

```
2*’BS$Þ
2*      2^n
  ’     decremented
     $Þ sort the (implicit) range using the following two functions:
   B    binary
    S   summed

```
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
oL<Σb1¢

```

Try it online!

```
oL<Σb1¢  # full program
   Σ     # sort...
 L       # [1, 2, 3...
o        # ...2 **...
         # implicit input
 L       # ]...
  <      # with one subtracted from...
         # (implicit) each element...
   Σ     # by...
      ¢  # number of...
     1   # ones...
      ¢  # in...
         # (implicit) current element in list...
    b    # in binary
         # implicit output

```

# Alternative, 7 bytes

```
oL<Σ2вO

```

Try it online!

```
2вO  # full modified section
  O  # sum of...
 в   # list of (base-10) values of digits of...
     # (implicit) current element in list...
 в   # in base...
2    # literal

```

# Another alternative, 7 bytes

```
oL<ΣbSO

```

Try it online!

```
bSO  # full modified section
  O  # sum of...
 S   # list of characters of...
     # (implicit) current element in list...
b    # in binary

```
> 1 votes

# Answer
# Vyxal, 6 bytes

```
‹Eʁµb∑

```

Try it Online!

```
  ʁ    # 0...
‹E     # 2 ** (n-1)
   µ   # Sorted by
    b  # binary
     ∑ # Summed

```
> 1 votes

# Answer
# Java 8, 205

```
public class S{public static void main(String[] n){java.util.stream.IntStream.range(0,1<<Integer.parseInt(n[0])).boxed().sorted((a,b)->Integer.bitCount(a)-Integer.bitCount(b)).forEach(System.out::print);}}

```
> 0 votes

# Answer
C++11, 117 characters:

```
using namespace std;int main(){ set<pair<int,int> > s;int b;cin>>b;int i=0;while(++i<pow(2,b))s.insert({bitset<32>(i).count(),i});for (auto it:s) cout <<it.second<<endl;}

```

Ungolfed:

```
using namespace std;
int main()
{
    set<pair<int,int> > s;
    int b;
    cin>>b;
    int i=0;
    while (++i<pow(2,b))  {
        s.insert({bitset<32>(i).count(),i});
    }
    for (auto it:s) {
        cout <<it.second<<endl;
    }
}

```

Explanation:

Create a set of int,int pairs. The first int is bit count, the second one is the number. Pairs compare themselves according their first parameter, so the set is sorted by bit count.
> 0 votes

# Answer
# MathGolf, 6 bytes

```
óráÅàç

```

Try it online.

**Explanation:**

```
ó       # Push 2 to the power of the (implicit) input-integer
 r      # Pop and push a list in the range [0,2**input)
  á     # Sort this list by,
   Å    # using the following two characters as inner code-block:
    à   #  Convert it to a binary-string
     ç  #  And only leave the truthy digits, removing the 0s

```
> 0 votes

# Answer
# Perl, 64/2 = 32

```
#!perl -ln
for$i(0..$_){$i-(sprintf"%b",$_)=~y/1//||print for 0..2**$_-1}

```

Simply iterate over the range `[0..2^n-1]` `n + 1` times. In each iteration print only the numbers that have number of 1 bits equal to the iteration variable (`$i`). Bits are counted by counting `1`'s (`y/1//`) in the number converted to binary string with `sprintf`.

Test me.

# Perl, 63

Sorting approach:

```
#!perl -l
print for sort{eval+(sprintf"%b-%b",$a,$b)=~y/0//dr}0..2**<>-1

```
> -1 votes

---
Tags: code-golf
---


title: Alternating Pattern

text:
# Question
Title: Alternating Pattern
In a now deleted stackoverflow question, someone posted the following:

Write a program or function to print alternating patterns in `*` and `#` based on a given integer `n`. Some examples:

Input: `n=1`
Output:

```
*

```

Input `n=5`
Output:

```
*####
###**
***##
###**
*####

```

Input: `n=8`
Output:

```
*#######
######**
***#####
####****
****####
#####***
**######
#######*

```

Since it looked like a pretty cool code-golfing challenge, here it is.

**How are these patterns build?**

The first line starts with a single `*`, followed by `n-1` amount of trailing `#`.
The second line then contains two `*`, with `n-2` amount of leading `#`.
The third line starts with three `*`, followed by `n-3` amount of trailing `#`.
etc.

Once we've reached the middle (`n/2`), we count back again with the amount of `*`, which can be seen in the examples above.

NOTE that for odd input numbers the inversed pair of lines (so first and last; second and next to last; etc.) are exactly the same. In the `n=5` example the first and last lines are `*####`; the second and next to last lines are `###**`.
For even input numbers however the inversed pair of lines are reversed. In the `n=8` example the first and last lines are `*#######` and `#######*`; the second and next to last lines are `######**` and `**######`; etc.

## Challenge rules:

* You can use any two distinct *printable* characters instead of `*` and `#`. You can use `A` and `B`; `3` and `7`; `<` and `>`; etc. Please state in your answers what you've used.
* You can assume `n` will be a positive integer (`>= 1`)
* You are allowed to output a list/array of strings for each line or a 2D matrix of characters, instead of printing them to STDOUT.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, adding an explanation for your answer is highly recommended.

## Test cases (first `n=1` through `n=10`)

```
*

*#
#*

*##
#**
*##

*###
##**
**##
###*

*####
###**
***##
###**
*####

*#####
####**
***###
###***
**####
#####*

*######
#####**
***####
###****
***####
#####**
*######

*#######
######**
***#####
####****
****####
#####***
**######
#######*

*########
#######**
***######
#####****
*****####
#####****
***######
#######**
*########

*#########
########**
***#######
######****
*****#####
#####*****
****######
#######***
**########
#########*

```

# Answer
> 14 votes
# Jelly, 9 bytes

```
>þµoṚUÐeY

```

Try it online!

# Explanation

```
>þ           Create a table of (x>y) over [1…n]×[1…n]:
               [0 1 1 1 1]
               [0 0 1 1 1]
               [0 0 0 1 1]
               [0 0 0 0 1]
               [0 0 0 0 0]
  µ          Take this array, and...
   oṚ        OR it with its reverse:
               [0 1 1 1 1]
               [0 0 1 1 1]
               [0 0 0 1 1]
               [0 0 1 1 1]
               [0 1 1 1 1]
    UÐe      Apply U (reverse) to even-indexed rows.
       Y     Join by newlines.

```

# Answer
> 17 votes
# Python 2, 62 bytes

```
lambda n:["%*s"%(i%2*2*n-n,"x"*min(i+1,n-i))for i in range(n)]

```

Try it online!

Uses `x` and space.

The rows are computed like this:

```
"%-5s" % "x"      == "x    "
"%5s"  % "xx"     == "   xx"
"%-5s" % "xxx"    == "xxx  "
"%5s"  % "xx"     == "   xx"
"%-5s" % "x"      == "x    "

```

Using the `%*s` specifier to choose between `n` and `-n`.

# Answer
> 7 votes
# APL (Dyalog Classic), 18 bytes

```
⎕a[↑⊢∘⌽\(⊂>⊢⌊⌽)⍳⎕]

```

Try it online!

outputs `AB` instead of `*#`

evaluated input n

`⍳⎕` the vector `0 1 ... n-1`

`⊢⌊⌽` min () between themselves () and their reverse () - see *trains*

`⊂>⊢⌊⌽` where is the  vector as a whole () less than each of its `⊢⌊⌽` \- return a vector of boolean (0/1) vectors

`⊢∘⌽\` reverse every other vector

mix into a matrix

`⎕a` the uppercase English alphabet, `'AB`...`Z'`

`⎕a[` `]` replace `0` `1` with `'A'` `'B'`

# Answer
> 6 votes
# Perl 6, 57 bytes

```
{map ^$^a: {fmt -$a*(-1)**$_=>\*x($_+1 min$a-$_): "%*s"}}

```

Try it online!

Uses the same method as Lynn's Python answer. Outputs using `*` and space.

# Answer
> 6 votes
# MATL, ~~34~~ ~~31~~ 18 bytes

```
:t!>tPY|!"@X@oQ&P!

```

Try it on MATL Online

Uses 0 for * and 1 for #. Based on Lynn's Jelly answer.

---

Older answer, 31 bytes:

```
2/tk:wXk:Ph"X@ot~XHh@Gy-hHQ&PY"

```

Try it on MATL Online

Uses 1 for * and 0 for #.

```
         % implicit input, say 5
2/       % divide input number by 2 [2.5]
tk       % make a copy and floor that [2.5, 2]
:        % create range 1 to the floored value [2.5, [1, 2]]
wXk      % bring out the division result and this time ceil it
         %  [[1, 2], 3]
:        % create range 1 to that [[1, 2], [1, 2, 3]]
Ph       % flip the last array and concatenate horizontally
         %  [[1, 2, 3, 2, 1]]
"        % loop through the array
  X@o    % Is the current loop index odd? 1 for odd, 0 for even
  t~     % duplicate and logical negate that
  XH     % copy that value to clipboard H
  h      % and concatenate the values ([1 0] on odd iterations, [0 1] on even)
  @      % push current value from array (say 2, then stack is [[0 1], 2)
  G      % push input again
  y-     % subtract current array value from input [[0 1], 2, 3]
  h      % concatenate those two [[0 1], [2, 3]]
  H      % get the stored value from clipboard H (1 for even iterations, 0 for odd)
  Q      % increment that
  &P     % flip the array in that dimension: in even iterations, this flips
         %   across columns and hence inverts the two values. [[0 1], [3, 2]]
         %   in odd iterations, it's a no-op
  Y"     % run-length decoding - repeat the element from first array the number of times
         %  specified in the second array
         % implicit loop end, implicit output

```

# Answer
> 5 votes
# Jelly,  ~~12~~  15 bytes

+3 fixing `n=1` edge-case bug :(

```
R«Ṛ$‘r⁸ṬUÐe0YE?

```

A full program accepting an integer which prints the output as defined in the OP using `0` and `1` for `*` and `#` respectively.

**Try it online!**

### How?

```
R«Ṛ$‘r⁸ṬUÐe0YE? - Main Link: integer, n
R               - range -> [1,2,3,4,...,n]
   $            - last two links as a monad:
  Ṛ             -   reverse -> [n,...,4,3,2,1]
 «              -   minimum (vectorises) -> [1,2,3,4,...,4,3,2,1]
    ‘           - increment (vectorises) -> [2,3,4,5,...,5,4,3,2]
      ⁸         - chain's left argument, n
     r          - inclusive range (vectorises) -> [[2,3,...,n],[3,4,...n],[4,5,...n],[5,...n],...,[5,...n],[4,5,...n],[3,4,...n],[2,3,...,n]]
       Ṭ        - untruth (vectorises) -> [[0,1,1,...,1],[0,0,1,1,...,1],[0,0,0,1,...,1],[0,0,0,0,1,...,1],...,[0,0,0,0,1,...,1],[0,0,0,1,...,1],[0,0,1,1,...,1],[0,1,1,...,1]]
         Ðe     - apply to entries with even indices:
        U       -   upend              -> [[0,1,1,...,1],[1,1,...,1],[0,0,0,1,...,1],[1,...,1,0,0,0,0],...]
              ? - if...
             E  - ...condition: all equal? (only true when n=1, where we have [1,1])
           0    - ...then: zero
            Y   - ...else: join with newline characters
                - implicit print

```

# Answer
> 5 votes
# Charcoal, 21 bytes

```
≔⮌…⁰ＮθＥθ⭆θ›§⟦μλ⟧κ⌊⟦κι

```

Try it online! Uses `0` and `1`. Link is to verbose version of code and includes `§*#` which translates the output to the `*` and `#` in the question. Explanation:

```
    Ｎ                   Input number
  …⁰                    Range from 0
 ⮌                      Reversed
≔    θ                  Assign to `q`
      Ｅθ                Map over reversed range
        ⭆θ              Map over reversed range and join
           §⟦μλ⟧κ       Alternate between range and reversed range column
                 ⌊⟦κι   Minimum of range and reversed range row
          ›             Greater
                        Implicitly print each row on its own line

```

# Answer
> 4 votes
# Jelly, 15 bytes

```
r1«RR;ṬṖɗ€‘UÐeY

```

Try it online!

Full program.

`*` = `1`
`#` = `0`

# Answer
> 4 votes
# Java 10, 145 bytes

```
n->{var r=new char[n][n];for(int j=0,k;j<n;++j)for(k=0;k<n;)r[j][k]=k++<(j<n/2?j%2<1?j+1:n+~j:j%2>0?j:n-j)?j%2<1?'*':'#':j%2>0?'*':'#';return r;}

```

All the ternary makes it a bit messy, but it works fine. I tried flattening the nested loop, and various other things, but they only increased the byte count. Try it online here.

Ungolfed:

```
n -> { // lambda taking an integer as output and returning a char[][]
    var r = new char[n][n]; // the output array; we make use of Java 10's var here (replace with char[][] for another 4 bytes to make this work in Java 8)
    for(int j = 0, k; j < n; ++j) // iterate over the lines
        for(k = 0; k < n; )       // iterate over the j'th line
            r[j][k] = // set the current character
                      k++ < // determine if we're in the first or second portion of the line:
                            (j < n/2 ? // for the first half of the output:
                                 j%2 < 1  // on even lines ...
                                 ? j + 1  // ... print the first symbol j+1 times ...
                                 : n + ~j // ... on odd lines, print it n-j-1 times.
                             : j%2 > 0 ?  // for the second half of the output, on odd lines ...
                                 j :      // ... print the first symbol j times ...
                                 n - j)   // ... on even lines, print it n-j times.
                      ? j%2 < 1 ? '*' : '#'  // for the first part of the line, use '*' on even lines, '#' otherwise
                      : j%2 > 0 ? '*' : '#'; // for the second part of the line, use '*' on odd lines, '#' otherwise
    return r; // return the completed array
}

```

# Java ~~8~~ 11, ~~179~~ 127 bytes

```
n->{String r="",a,b;for(int j=0;j<n;b="#".repeat(j<n/2?n+~j:j),r+=(j++%2<1?a+b:b+a)+"\n")a="*".repeat(j<n/2?j+1:n-j);return r;}

```

Try it online here (TIO does not have Java 11 yet, so this uses a custom method that results in the same byte count as `String#repeat()`).

Thanks to Kevin Cruijssen for golfing a whopping 52 bytes!

Ungolfed:

```
n -> { // lambda taking an int argument and returning a String
    String r = "", // the output String
           a,      // temporary String containing the '*'s
           b;      // temporary String containing the '#'s
    for(int j = 0; j < n; // loop over the lines
        b = "#".repeat( // repeat the '#' character ...
            j < n/2 ? n + ~j // ... n-j-1 times in the first half of the output ...
            : j), // ... j times in the second half
        r += (j++ % 2 < 1 ? a + b : b + a) + "\n") // assemble the j'th line and append it to the output: on even lines, the '*'s go first; on odd lines, the '#'s go first
        a = "*".repeat( // repeat the '*' character ...
              j < n/2 ? j + 1 // ... j+1 times in the first half of the output ...
              : n - j); // n-j times in the second half
    return r; // return the completed output
}

```

# Answer
> 4 votes
# Lua,  ~~148~~  133 Bytes

```
function(n)t,a,b={},".","#"for i=1,n do r=i<n/2+1 and i or-~n-i s=a:rep(r)..b:rep(n-r)t[i]=i%2<1 and s:reverse()or s end return t end

```

Try it online!

-15 bytes thanks to @KevinCruijssen and @JoKing.

```
function(n)
   t = {}; a = "."; b = "#"          -- initialize variables, output is in table
                                     -- strings are needed in variables for
                                     --   the str:rep and str:reverse syntax

   for i = 1, n do                          -- build the rows of the table
      r = i<=(n+1)/2 and i or n-i+1         -- logic used to count up then down
      str = a:rep(r)..b:rep(n-r)            -- append correct number of '.'s, fill
                                            --   in the rest with '#'s
      t[i]=i%2==0 and str:reverse() or str  -- logic used to control reversing
   end
   return t                                 -- return table
end

```

# Answer
> 3 votes
# Kotlin, 86 bytes

```
{n:Int->for(i in 0..n)println("%${i%2*2*n-n}s".format("x".repeat(Math.min(i+1,n-i))))}

```

Try it online!

Uses `x` and space as output symbols. Derivates from Lynn Answer

# Answer
> 3 votes
# C (gcc), 104 99 bytes

```
h,j,k;f(i){char s[h=i++];for(j=0;k=++j>i/2?i-j:j,j<i;memset(memset(s,42,h)+j%2*k,35,h-k),puts(s));}

```

Try it online!

# Answer
> 3 votes
## Perl 5 \+ `-pa -MPOSIX -M5.010`, 58 bytes

```
say+sort{$|--}1x abs,2x("@F"-abs)for(1..ceil$_/=2),-$_..-1

```

Try it online!

# Answer
> 3 votes
# C (gcc), 118 108 bytes

This one isn't going to win, but it's a different approach (or at least, I think so!) Instead of doing string manipulations, I make use of the fact that \\$10^x-1\\$ over \\$\[1..n\] = \\{9, 99, 999, ...\\}\\$, which then can be multiplied to get the appropriate pattern; `printf()` then does the zero-padding for right-justification.

Sadly, `int` only has sufficient range to do up to 9 digits (on 32-bit platforms), so you need to go to `long` for larger patterns; a language that natively does MP arithmetic might be able to use this for something.

Thanks to ceilingcat for the suggestion.

```
h,j,k;p(h){h=h?10*p(--h):1;}f(i){for(j=0,h=i++;k=++j>i/2?i-j:j,j<i;printf("%0*d\n",h,~-p(k)*p(j%2*(h-k))));}

```

Try it online!

---

### Proof of concept that this works with MP arithmetic:

### C# (Mono C# compiler), 187 165 bytes

(143 bytes + 22 bytes for the `using System.Numerics;` in the header)

```
q=>{var r="";for(int j=0,h=q+1,k;j<q;r+=((BigInteger.Pow(10,k)-1)*BigInteger.Pow(10,j%2*(q-k))).ToString("D"+q)+"\n")k=++j>h/2?h-j:j;return r;}

```

Try it online!

# Answer
> 3 votes
# Vim, 99 keystrokes

It's always interesting to try to do vim with input arguments. It's very unnatural, so it's not going to be amazingly short. There probably are other good approaches to this.

Input is assumed to be by itself in a buffer. Registers are assumed to be empty. Editor is assumed to be tall enough to contain the result without scrolling (this could technically be avoided at the cost of some keystrokes).

```
"nD@ni<cr><esc>MmaGddM
<c-v>'aI*<esc>qwgvjokoI*<esc>@wq@w<esc>
:set ve=all<cr>@nlh<c-v>@nkr#
:%s/ /#/g<cr>o<esc>
2Gqqdt#$p2j0@qq@q

```

Explanation

```
 | Buffer state (odd and even case):
 | 5                    6

"nD              read input into register n
@ni<cr><esc>     add n newlines
MmaGddM<c-v>'a   visual block select center row(s)
I*<esc>          prepend a column of *
qw               record macro w
  gvjoko         expand selection up and down
  I*<esc>
  @w             recurse
q
@w<esc>          run macro w and exit visual block select

 | Buffer state:
 | *                    *
 | **                   **
 | ***                  ***
 | **                   ***
 | *                    **
 |                      *

:set ve=all<cr>  move anywhere!
@nlh<c-v>@nkr#   add last column of #s

 | Buffer state:
 | *   #                *    #
 | **  #                **   #
 | *** #                ***  #
 | **  #                ***  #
 | *   #                **   #
 |                      *    #

:%s/ /#/g<cr>      replace spaces with #

 | Buffer state:
 | *####                *#####
 | **###                **####
 | ***##                ***###
 | **###                ***###
 | *####                **####
 |                      *#####

o<esc>2G           prep and jump to line 2
qqdt#$p2j0@qq@q    (effectively) flip every other onward

 | Buffer state:
 | *####                *#####
 | ###**                ####**
 | ***##                ***###
 | ###**                ###***
 | *####                **####
 |                      #####*

```

And in base64, with actual characters (put input in `input` and keystrokes in `keys` and run using `vim -u NONE -s keys input`)

```
Im5EQG5pDRtNbWFHZGRNFidhSSobcXdndmpva29JKhtAd3FAdxs6c2V0IHZlPWFsbA1AbmxoFkBua3IjOiVzLyAvIy9nDW8bMkdxcWR0IyRwMmowQHFxQHE=

```

# Answer
> 2 votes
# , 75 bytes

```
function(n)outer(1:n,1:n,function(x,y,a=x<y|x>n-y+1)+ifelse(x%%2,a,rev(a)))

```

Try it online!

* Inspired by @Lynn answer
* function getting `n` as parameter and returning a matrix of `0/1` where `0` corresponds to `'*'` and `1` corresponds to `'#'`

# Answer
> 2 votes
# K (ngn/k), 22 bytes

```
{"*#"i|:/'i>/:i&|i:!x}

```

Try it online!

`{` `}` function with argument `x`

`!x` the list `(0;1;`...`;x-1)`

`i:` assign to `i`

`i&|i` minima (`&`) of `i` and its reverse (`|`)

`i>/:` compare with greater than (`>`) `i` against each element from the list on the right (`/:`) - return a boolean matrix (list of lists)

`i|:/'` for each (`'`) j in `i`, reverse (`|:` \- we need the `:` to force `|` to be unary) the corresponding element j times (`n f/ x` applies `f` `n` times on `x`). Effectively, reverse every other row.

`"*#"` use matrix elements as indices in the string `"*#"`

# Answer
> 0 votes
# Python 3, 251 bytes

```
n = int(input())

for i in range(1,n+1):
  if i%2 != 0:
    for j in range(1,n-i+2):
      print("*",end=" ")

  for j in range(1,i+1):
    print("#",end=" ")

  if i%2 == 0:
    for j in range(1,n-i+2):
      print("*",end=" ")

  print()

```

Try it online!

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


title: Convert Regex to Mask

text:
# Question
Title: Convert Regex to Mask
*From my CMC.*

Given a regex and a non-empty printable ASCII text, return one bit per character in the text, indicating the positions of beginnings of non-overlapping matches, and also the positions of beginnings of sequences that are not part of any non-overlapping matches.

You can:

* take the regex as a regex object, string or any other way that is reasonable or allowed by default rules
* take the text as a string object, character list, or any other way that is reasonable or allowed by default rules
* return the bits as an array, integer, or any other way that is reasonable or allowed by default rules

You may use any flavour, library, or implementation for regexes, as long as you support:

* any-character wildcards, e.g. `.`
* positive and negative character classes, e.g. `[ab]` and `[^ab]`
* repetitions, e.g. `a?` and `a+` and `a*` and/or the general `a{m,n}` form
* capturing groups, e.g. `(ab)`
* alternatives, e.g. `a|b`

## Examples

`[0123456789]+` or `[0123456789]{1,}`
`Hello4the42`
`10000110010`

`(aa)+` or `(aa){1,}`
`aaaaaaa`
`1000001`

`aaa`
`baaaab`
`110010`

`aaa|b`
`baaaab`
`110011`

`aab?` or `aab{0,1}`
`baaaab`
`110100`

`x.*z` or `x.{0,}z`
`abcdef`
`100000`

(you can take this as `(?:)` if necessary)
`Hello`
`11111`

`[^aeiou]+` or `[^aeiou]{1,}`
`Hello, world!`
`1110110011000`

`aaa`
`aaaaaaa`
`1001001`

`10101`
`101010101`
`100001000`

# Answer
# APL (Dyalog Unicode), 23 bytes

Assumes an index origin of 0.

```
{(⍳≢⍵)∊0,∊+\¨⍺⎕S 0 1⊢⍵}

```

Try it online!

`⍺⎕S 0 1⊢⍵`: **S**earch for matches of the regex  in the string . For each each match return the number of characters before the match (0) and the length of the match (1).
`+\¨`: For each match, get the cumulative sums. This gives the 0-based starting index of the match and the first index after the match. : Flatten into a single list of indices.
`0,`: Prepend a zero in case there was no match at the beginning.
`(⍳≢⍵)∊`: For each index of the string , is it an element of this list?
> 4 votes

# Answer
# Retina, ~~42~~ 36 bytes

```
~L$`^.*
0A`¶, ,S0`($&)
.
0
m`^.
1
¶

```

Try it online! Link includes test suite which doesn't support empty regex, so `()` is used instead. Explanation:

```
L$`^.*
0A`¶, ,S0`($&)

```

Wrap the regex in a capturing group and prefix it with commands that delete the regex from the input and split the ASCII text on the regex, including only the first capturing group in the output. (This unfortunately still renumbers the other capturing groups. A similar problem applies to the `w` modifier in Retina itself, but at least Retina is able to avoid renumbering numbered capturing groups in that case.)

```
~`

```

Evaluate those commands on the original input.

```
.
0

```

Change all characters to `0`s.

```
m`^.
1

```

Change all characters at the beginning of lines to `1`s.

Join everything back together.
> 4 votes

# Answer
# , 77 bytes

```
function(p,t,m=el(gregexpr(p,t))){T[c(m,m+attr(m,"m"))[m>0]]=1;T[1:nchar(t)]}

```

Try it online!

Outputs `1` for starts of matches/non-matches, `NA` otherwise.

---

# , ~~84~~ ~~86~~ 84 bytes

*Edit: thanks to pajonk for spotting a bug when there is no match*

```
function(p,t,l=0:nchar(t),m=el(gregexpr(p,t)))`[<-`(!l,c(m,m+attr(m,"m"))[m>0],1)[l]

```

Try it online!

Outputs `1`/`0`.

```
function(p,t,           # p = pattern, t = text,
 m=el(gregexpr(p,t)))   # m = positions of matches,
                        # with attribute "match.length" = lengths of matches
                        # (can be abbreviated as "m");
 head(...,-1)           # Return all except the last element of...
 `[<-`(                 # assigning the elements of...
 !0:nchar(t)            # ...a vector of 1 followed by nchar(t) zeros...
 c(m,                   # at the positions of the matches,
     m+attr(m,"m")      # and the positions immediately after the matches,
  )[m>0]                # (but ignoring the value of -1 assigned to 'no match')...
 ,1)                    # ...to 1

```
> 4 votes

# Answer
# Python 3.8 (pre-release), 86, 79 bytes

```
lambda r,s:(c:=1<<len(s)-1)|sum({c>>j for i in r.finditer(s)for j in i.span()})

```

Try it online!

Old version

Takes a re object and a string and returns a string of 1s and 0s an integer that encodes the mask in binary.

Output is created by bitwise arithmetic. As we know the leftmost bit is set there are no worries about leading zeros. Ideally, we would like to `or`-reduce the set bits. As there is no short way to do this (is there?) we instead take the sum after eliminating any duplicates.
> 4 votes

# Answer
# Ruby, 81 bytes

```
f=->r,s,a=0{s>''?[(a=((s=~r)!=0?a-1:[a-1,s[r].size].max))>0,*f[r,s[1..-1],a]]:[]}

```

Try it online!
> 3 votes

# Answer
# Python, 87 bytes

```
def f(s,p):
 r=[i:=0]
 for m in p.finditer(s):r+=m.span()
 for x in s:yield i in r;i+=1
```

Attempt This Online!

Takes a string and an `re.Pattern` object, and returns a generator of booleans.

I'm really not happy with the last line; it seems like there must be a better way of doing it.

---

Explanation:

* `i:=0`: using the observation that the first bit is always set, we can abuse the initial definition of `r` to initialise `i` to `0` at the same time
* `for m in p.finditer(s):`: for every (non-overlapping) match of `p` inside `s`:
    + `r+=m.span()`: append the range of the match object - inclusive start, exclusive end. This is convenient, because we need to include a `1` for the start of every match, and after the end of every match.
    If two matches are consecutive, this is not a problem, because it doesn't matter if the same value is added to the list twice (once for the end of the first, and once for the start of the second).
* Finally, output a generator of booleans for each index in the string's range according to whether that index is in the list `r`.

If a match occurs at the end of the string, an out-of-bounds index will be appended to `r`, but this also doesn't matter, because we only check indeces in `s`'s range.
> 2 votes

# Answer
# Burlesque, 43 bytes

```
s1{g1~&l_j}{g1~=}w!ClFL`Fz?{L['0j.*'10sa}\m

```

Try it online!

```
s1       # Set 1 to be the RegEx
{g1      # Get the RegEx
 ~&      # Partition based on the RegEx (PreMatch, Match, PostMatch)
 l_j     # Get PostMatch out of block and on top of the stack
}
{
 g1~=    # PostMatch still contains match to RegEx
}w!      # While
ClFL     # Collect results and flatten
`Fz?     # Remove empty string(s)
{
 L[      # Length
 '0j.*   # "0"*Len
 '1 0 sa # Set first char to 1
}\m      # Map and concatenate

```
> 2 votes

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

```
s=>r=>[...s].map((_,i)=>s.replace(r,(...p)=>i=(v=p.at(-2)-i)&&v+p[0].length&&i)&&!i)

```

Try it online!

* `Array#at` is ES2022.

Could be 73 bytes if regex passed to this function use `(?:aa)` instead of `(aa)`.

---

# JavaScript (Node.js) \+ core-js, 78 bytes

```
s=>r=>[...s].map((_,i)=>s.matchAll(`(${r})|((?!${r}).)+`).some(v=>v.index==i))

```
> 2 votes

# Answer
# Julia 1.3, 73 bytes

```
a\b=(r=[0;b...].==0;findall(a,b).|>m->r[m.start]=r[m.stop+1]=1;pop!(r);r)

```

Try it online!

* `findall(::Regex,::String)` was added in Julia 1.3 and returns a vector of ranges for each match.
* `pop!(r);r` is one byte shorter than `r[1:end-1]`
* expects `a` as a `Regex` object and `b` a `String`
* output is a vector of `Bool`s
> 1 votes

---
Tags: code-golf, string, array, regular-expression, text-processing
---


title: Will one-cell brainfuck halt?

text:
# Question
Title: Will one-cell brainfuck halt?
Brainfuck is an esoteric programming language that is Turing Complete, meaning you can't tell whether a given program will halt without running it. It's cell-based and has an infinite tape of cells, values containing an unsigned integer from 0 to 255, but if you give it arbitrary-size cells, just three is enough to make it Turing Complete.

But one cell isn't in either case.

The bit of brainfuck that we'll be using contains these four operations:

* `+`: Increment the current cell
* `-`: Decrement the current cell
* `[`: Loop while the current cell is nonzero
* `]`: End a loop

You should use a single unsigned integer from 0 to 255 as the cell, wrapping round when you decrement zero or increment 255.

You may return any two distinct, consistent values to say whether it halts or not. The program will be a valid brainfuck program (balanced brackets) and only contain these four characters. You may *not* output by halting/not halting.

## Testcases

If you want to look at these in more depth, here's a good visualizer.

### Falsy (doesn't halt)

```
+[]
+[++]
+[++[+]--]
+[----]
+[-]-[+[-]-]
+[[-]-[+[-]-+[++]-[+]]-[++][-]]
++[-]+[--]-

```

### Truthy (halts)

```
[+]
+
+[+]
++[+++]
+++--[++-][+][+]
+[+]-[+++]-

```

Standard rules apply.

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

```
s=>eval(`try{${s.replace(/./g,(c,i)=>(c=='['?'for(;v;){':c>{}?'}':`v=v${c}1&255`)+`;s[t++>>9].x;`)}}catch{1}`,v=t=0)

```

Try it online!

---

# JavaScript (Node.js), 135 bytes

```
s=>(e=(p,v,b=0)=>(s[p]=='['?b|!v?++b:b:s[p]>'['?b|v?--b:b:b)?e(b>0?p+1:p-1,v,b):s[p]?e[m=[p,v]]||e(p+(e[m]=1),v+(s[p]+1|0)&255):0)(0,0)

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 36 bytes

```
0ì„+-„><‡'[„₄ƒ:']"D₁Ö#N₄Qi0q}}":1«.V

```

Outputs `1` if it halts; `0` if it doesn't halt.

Try it online or verify all test cases.

**Explanation:**

```
0ì                 # Prepend a "0" in front of the (implicit) input-string
„+-„><‡            # Replace all "+" with ">" and all "-" with "<"
'[„₄ƒ:            '# Replace all "[" with "₄ƒ"
']"D₁Ö#N₄Qi0q}}": '# Replace all "]" with "D₁Ö#N₄Qi0q}}"
1«                 # Append a trailing "1" at the end
.V                 # Execute it as 05AB1E code
                   # (after which the result is output implicitly)

```

Verify all test cases without `.V` to see what 05AB1E programs the inputs are transformed into.

```
0ì                 # We start the cell at 0

„+-„><‡            # `>` increases the top of the stack by 1
                   # `<` decreases the top of the stack by 1

'[„₄ƒ:            '# `₄ƒ` loop `N` in the range [0,1000]

']"D₁Ö#N₄Qi0q}}": '#
   D               # Duplicate the top
    ₁Ö             # Pop and check if it's divisible by 256
      #            # If this is truthy: stop the loop
       N           # Else: push the loop index `N`
        ₄Qi        # If it's equal to 1000:
           0       #  Push a 0
            q      #  And stop the entire program
                   #  (after which this 0 is output implicitly as result)
             }     # Close the if-statement
              }    # Close the loop

1«                 # Push a 1
                   # (which is output implicitly as result if we didn't halt)

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), 117 bytes

```
ToExpression[a=b=0;StringReplace[#,{"["->"Do[If[c∣a,Break[]];","]"->"i<c||(b=1),{i,c=256}];",c_:>"a"<>c<>"=1;"}]]b&

```

Try it online!
> 3 votes

# Answer
# Python 3, 245 bytes

```
p=input()
m={}
s=[]
for i,c in enumerate(p):
	if"["==c:s+=[i]
	if"]"==c:m[s[-1]]=i;m[i]=s.pop()
a=n=0
while a<len(p):
	if(a,n)in s:print();break
	s+=[(a,n)];q=p[a]
	if"["==q and n<1or"]"==q and n:a=m[a]
	if"+"==q:n+=1
	if"-"==q:n-=1
	a+=1;n%=256

```

Try it online!

so idrk how the fancy string substitution solutions are working so here's my terrible attempt to just run the code instead
> 3 votes

# Answer
# Charcoal, ~~90~~ 88 bytes

```
≔⁰η≔⁰ζ≔⟦⟧εＷ∧‹ηＬθ¬№υ⟦ηζ⟧«⊞υ⟦ηζ⟧≡§θη[¿ζ⊞εηＷ›№…θ⊕η[⁺№…θ⊕η]Ｌε≦⊕η]≔⊖⊟εη≔﹪⁺Ｉ⁺§θη1ζ²⁵⁶ζ≦⊕η»⁼ηＬθ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the program halts, nothing if not. Explanation:

```
≔⁰η

```

Start at the beginning of the code.

```
≔⁰ζ

```

Start with zero in the cell.

```
≔⟦⟧ε

```

Start with no unmatched `[`s.

```
Ｗ∧‹ηＬθ¬№υ⟦ηζ⟧«

```

Repeat until either the end of the program is reached or the current state has been seen previously (i.e. an infinite loop has been detected).

```
⊞υ⟦ηζ⟧

```

Record the current state.

```
≡§θη

```

Switch on the next program character.

```
[¿ζ

```

For `[`, if the cell is non-zero, then...

```
⊞εη

```

... save the current position, so it can be quickly restored when the matching `]` is reached, otherwise...

```
Ｗ›№…θ⊕η[⁺№…θ⊕η]Ｌε≦⊕η

```

... advance the current position to the matching `]`.

```
]≔⊖⊟εη

```

For `]`, jump back to the matching `[`, which will then test the cell value.

```
≔﹪⁺Ｉ⁺§θη1ζ²⁵⁶ζ

```

Otherwise, adjust the cell value modulo 256 as necessary.

```
≦⊕η

```

Advance to the next character of the program. (In the case of `[` jumping forward to its matching `]`, this skips past the `]`. In the case of `]` jumping back to its matching `[`, this increment has been adjusted for, so that the `[` becomes the next code to execute.)

```
»⁼ηＬθ

```

Output whether the end of the program was reached.
> 2 votes

---
Tags: code-golf, decision-problem, brainfuck, halting-problem
---