title: Can you give me half? (No digits)

text:
# Question
Title: Can you give me half? (No digits)
The task is to provide code that evaluates to 0.5 numerically, i.e. the output must be recognized by your chosen language as a numeric value (Number, float, double, etc), not as a string. The catch, the characters 0 through to 9 cannot be used.

PLEASE NOTE: This IS NOT a golfing challenge, this is a popularity contest, so creative answers are encouraged. The more obscure and convoluted answers are also encouraged.

One example that fits the brief would be the following:

`((++[[]][[~~""]]<<++[[]][[~~""]]))**((--[[]][[~~""]]))` which works out to 0.5 in JavaScript.

A bounty of 150 will be awarded as an added incentive for the most voted creative answer. Good luck!

Any questions, feel free to ask.

# Answer
# Jelly, 177 bytes

```
Never gonna give you up,
Never gonna let you down,
Never gonna run around and desert you.
Never gonna make you cry,
Never gonna say goodbye,
Never gonna tell a lie and hurt you.

```

Try it online!

Explanation thanks to caird coinheringaahing.

```
Never gonna give you up,                Helper Link; never called
Never gonna let you down,               Helper Link; never called
Never gonna run around and desert you.  Helper Link; never called
Never gonna make you cry,               Helper Link; never called
Never gonna say goodbye,                Helper Link; never called
Never gonna tell a lie and hurt you.    Main Link
Never gonna tell a lie and hurt yo      Random stuff that doesn't matter
                                  u     Undefined so everything before it gets trashed
                                   .    0.5

```

... yeah. Not that exciting when you see how it works.
> 50 votes

# Answer
# Perl 5

```
Once upon a midnight dreary, while "I pondered", !weak and weary;
Over many a quaint and curious volume of for@gotten, @lore;
While I nodded, nearly napping, until /|there came a tapping|/;
As if someone ? ${!gently} = "rapping" ^ "rapOing at": my $chamber, $door;
"Tis some visitor", I-muttered, "tapping at my chamber door";
print unpack f, ${!this} and nothing x more

```

Try it online!

Ah, distinctly I remember it was in the bleak December; And each separate dying ember wrought its ghost upon the floor.

### Explanation / Spoiler:

Perl has a feature called 'barewords', which allows alphanumeric sequences to automatically be parsed as strings. This means that something like

```
foo bar baz

```

Will parse as valid Perl, but give a runtime error. However, if we can avoid Perl evaluating it, we can avoid the runtime error. The following program will run without any error:

```
foo bar baz while 0

```

Now let's have a look line by line:

```
Once upon a midnight dreary, while "I pondered", !weak and weary;

```

`"I pondered", !weak and weary` evaluates essentially to `("I pondered", false)` which is falsy so the stuff on the left hand side of the while loop does not get evaluated.

```
Over many a quaint and curious volume of for@gotten, @lore;

```

This is a `for` loop over the lists `@gotten` and `@lore`, which are empty, so the left hand side doesn't get evaluated.

```
While I nodded, nearly napping, until /|there came a tapping|/;

```

This is an `until` loop, where `/|there came a tapping|/` is a regex matching against `$_`. Even though `$_` is empty, the leading `|` matches against the empty string so the match becomes truthy so we don't evaluate the left hand side.

```
As if someone ? ${!gently} = "rapping" ^ "rapOing at": my $chamber, $door;

```

`if` is a keyword here. `someone` is a bareword which is truthy, so we evaluate `${!gently} = "rapping" ^ "rapOing at"`, which sets `${''}` to the string `"\0\0\0?\0\0\0 at"`. `my $chamber, $door` parses as a function call which is never evaluated, so there's no error.

```
"Tis some visitor", I-muttered, "tapping at my chamber door";

```

`I` and `muttered` are both barewords.

```
print unpack f, ${!this} and nothing x more

```

This parses as `(print unpack f, ${!this}) and nothing x more`. `${!this}` is `${''}`, which is our string from earlier. `unpack f` is a function that unpacks a single 32 bit float from a packed 4 byte representation. The first 4 bytes of `${''}` are `"\0\0\0?"`, which happens to be a valid representation of `0.5`. The rest of the string is ignored.

Since `(print unpack f, ${!this})` is truthy, the right hand side of the `and` is evaluated. `x` is the string repeat operator, and `nothing` and `more` are both barewords, so there's no error generated.
> 28 votes

# Answer
# Raku, 5 bytes

```
π/τ

```

Try it online!

The constant Pi divided by Tau is, of course, `1/2`. An alternative without the pesky unicode is to spell it out like `pi/tau`.
> 26 votes

# Answer
# Python 3, 117 bytes

Try it online!

```
(lambda n:round(sum(__import__('random').random()for _ in range(n))/n,ord('B')-ord('A')))(ord('~')*ord('~')*ord('~'))

```

This takes the average of a bunch of random numbers in the range 0-1 then rounds it. There is a *very* small chance this does not evaluate to 0.5
> 23 votes

# Answer
# Vyxal, 122 bytes

```
H   H  AAAAA  L      FFFFF
H   H  A   A  L      F
HHHHH  AAAAA  L      FFFFF
H   H  A   A  L      F
H   H  A   A  LLLLL  ½

```

Try it Online!

You asked for half, so I've given you half in more ways than 1 (/2).

This relies on the fact that most things here are NOPS and that getting the length of a number works.

The real work comes when we get to the `L`s in the bottom row: the first `L` is passed, 0, which has length 1. The next 4 `L`s all return 1 because the length of 1 is 1. The `½` then divides that 1 by 2.
> 22 votes

# Answer
# Jelly, "HALF OF ONE"

Yes, Jelly can output half of one with just `.` but did you know there is a secret verbose mode with a certain lexicon of ***reversed English***?

```
ENO FO FLAH

```

**Try it online!**

### How?

OK, so I lied.

```
ENO FO FLAH - Link: no arguments            (implicit 0)
E           - (implicit [0]) all equal?            -> 1
 N          - negate                               -> -1
  O         - ordinal (a no-op with numeric input) -> -1
    F       - flatten                              -> [-1]
     O      - ordinal (vectorises; again a no-op)  -> [-1]
       F    - flatten                              -> [-1]
        L   - length                               -> 1
         A  - absoulte value                       -> 1
          H - halve                                -> 0.5

```
> 18 votes

# Answer
# Jelly, 1 byte

```
.

```

Try it online!

I know it isn't golf, but why be creative when the tools are provided for you?

`.` is a decimal literal in Jelly. When the values before the `.` is omitted, it defaults to `0` and after it defaults to `5`. Therefore `.` is just `0.5`
> 16 votes

# Answer
# BQN

A.k.a "the worm".

```
=⊸÷⟜≠⌾‿⌾

```

Try it!

Produces a 2-element list consisting of two built-ins (), then divides the rank (1) by the length (2).

Various superfluous parentheses and no-ops can be added for style:

`(=÷≠)(⌾‿⌾)`
`=(⊸)(÷⟜≠)(⌾‿⌾)`
`⊣(=)(⊸)(÷⟜≠)(⌾‿⌾)`
`(=)(⊸)(÷)(⟜)(≠)(⌾‿⌾)`

Or how about the chicken and the owl:

`(≡÷≠)⊢⟨˙⋄˙⟩`
`(≡÷≠)⊢⟨⌾,⌾⟩`
> 15 votes

# Answer
# C (GCC, MIPS)

```
// A very mysterious function
float mystery()
{
    // A very mysterious string
    char whaaaaaa['?'] = "?";
    // A very mysterious cast
    return *(float *)whaaaaaa;
}

```

> If you want to test it on a non-based x86 or ARM CPU, try `htonl('?')`.

#### Explanation

> The reason I choose MIPS is because I wanted it to be big endian.
> The convenient thing about 0.5f is it is represented as `0x3f000000`. `0x3f` is `?` in ASCII.
> The string will be stored as `3f 00 00 00 ...` in memory, and dereferencing it on a big endian machine will conveniently result in `0x3f000000`.
> 15 votes

# Answer
# Wolfram Language (Mathematica), 75 bytes

```
ElementData["Hydrogen","AtomicNumber"]/ElementData["Helium","AtomicNumber"]

```

The atomic numbers of hydrogen and helium are exactly 1 and 2, respectively. Atomic masses aren't exact (except for carbon-12's, by defintion, when expressed in daltons), but atomic numbers are, since they're simply the number of protons in the atoms of the element.

\[Not sure how to get this working in TIO, or if solutions requring a server connection are allowed in popularity contests.\]
> 14 votes

# Answer
# Python 3, 420 bytes

```
from math import*
H=lambda n:int(n,int(sqrt(ord('Ā'))))
o=ord
print(round(sin(H('d')*pi/(H('d')-H('a')))*cos(H('d')*pi/(o('G')-ord('A')))-sin(H('b')*pi/(o('G')-ord('A')))*cos(-(H('f')-H('a'))*pi/(H('d')-H('a'))))/(round((sin(pi/(o('h')-o('a')))*(pi/(o('h')-o('a'))))+(sin((H('f')-H('a'))*pi/H('e'))*(H('f')-H('a'))*pi/H('e'))+(sin(sqrt(o('@'))*pi/((o('h')-ord('a'))))**(H('d')-H('a')))+(sin(sqrt(o('Q'))*pi/H('e'))))))#

```

Try it online!

Directly from my math book. Solving it by bare hands was a big pain. But writing this answer from mobile was fun. oh plus got a nice byte count.

$$ \frac{\sin \frac{13\pi}{3}\cos \frac{13\pi}{6}-\sin \frac{11\pi}{6}\cos \left(-\frac{5\pi}{3}\right)}{ \sin^2\frac{7\pi}{3}+\sin^2\frac{5\pi}{14}+\sin^2\frac{8\pi}{7}+\sin^2\frac{9\pi}{4}}=0.5 $$
> 13 votes

# Answer
# JavaScript, 67 bytes

Abuses the fact that `undefined` is a valid identifier in JS.

```
undefined=>(undefined=>undefined/(undefined+undefined))(!undefined)

```

Try it online!
> 13 votes

# Answer
# Jelly, 10 bytes

```
Ænɓ,ÆṛUÆrḢ

```

Try it online!

I already made an answer that fits with Jelly's ability to be short. How about an answer about Jelly's ability to have stupidly convoluted builtins?

We construct the polynomial \\$4x^2 - 4x + 1\\$, then solve it as equal to \\$0\\$, giving \\$x = \frac 1 2\\$

## How it works

```
Ænɓ,ÆṛUÆrḢ - Main link. Takes no arguments
Æn         - Next prime after zero; 2
  ɓ        - New dyadic chain f(2,2):
   ,       - Pair; [2,2]
    Æṛ     - Construct the polynomial with the roots 2, 2: [4,-4,1]
      U    - Reverse; [1,-4,4]
       Ær  - Get the roots of this polynomial; [0.5, 0.5]
         Ḣ - Get the first element

```

Why use 1 byte when lot byte do trick?
> 10 votes

# Answer
# Ruby

Line number trickery.

```
p __LINE__ -
  __LINE__ **-
  __LINE__ *
  __LINE__ .
  to_f

```

Try it online!

### Explanation

`__LINE__` is a global constant which stores the current line number. As such, the program can be rewritten into one line as: `p 1-2**-3*4.to_f`, which just so happens to evaluate to `0.5`. The `.to_f` is needed to cast the result to a float (otherwise `(1/2)` is printed).
> 10 votes

# Answer
# Dyalog APL

```
÷∊⊆⊂∪⊃⊢⊣⊥⍨⍲⍀∨\⍱⌿∧/↑↓⍎⍕⍋⍒⍸⍴⍪,⍉⊖⌽⌹|⌈⌊*¨⍟⍤○⍥!×+~-≢⍬⍝

```

EDIT: I've updated the picture & text, but not the link nor the explanation.

Try it online!

Uses as many unique primitives as I had the patience to cram in. Andvmany thanks to Adám for giving me a bunch more to cram in! It looks cooler with a proper APL font:

(That is, as many primitives as I could use in a linear chain of execution without parentheses. I'm sure you can use every single one if you allow parentheses, as that opens up the dyadic functions.)

### Explanation

```
÷        Inverse            ->  1/2
↑        Mix                ->  2
↓        Split              ->  2
⊃        First              ->  2
∪        Unique             ->  2
⊂        Enclose            ->  2
⊣        Same (left)        ->  2
⊢        Same (right)       ->  2
∨\       Scan with GCD      ->  2
∧/       Reduce with LCM    ->  2
⍸        Where              ->  [1,2]
⍴        Shape              ->  [1,1]
⍪        Table               ->  3
,        Ravel              ->  3
⍉        Transpose          ->  3
⊖        Horizontal flip    ->  3
⌽        Vertical flip      ->  3
|        Absolute value     ->  3
⌈        Ceiling            ->  3
⌊        Floor              ->  3
*        Exponent           ->  3.14159
¨        Map                ->  1.14472
⍟        Natural logarithm  ->  1.14472
⍤        Atop               ->  3.14159
○        Pi times           ->  3.14159
⍥        Over               ->  1
!        Factorial          ->  1
×        Direction          ->  1
+⍨       Add to itself      ->  2
~        NOT                ->  1
-        Negate             ->  0
∊        Enlist             ->  0
≢        Length             ->  0
⍬        Empty list         ->  []

```
> 8 votes

# Answer
# Perl 6

```
say ½

```

Try it online!

Doesn't need explanation, does it?
> 6 votes

# Answer
# Pyth, 4 bytes

```
cTyT

```

Try it here!

Divides ten by twice ten.
> 6 votes

# Answer
# C (gcc), 30 bytes

```
float f(){float x=' ';x/='@';}

```

Try it online!

Because \\$x\\$ is a `float` the characters `' '` (\\$32\\$) and `'@'` (\\$64\\$) get converted to floating point numbers. Then the GCC trick of returning the last calculation is used to return \\$\frac{1}{2}\\$.
> 6 votes

# Answer
# APL (Dyalog Extended)

```
#÷⍥≢⍬⍬

```

Try it online!

Divides the length of a reference to the root namespace (1) by the length of `[[],[]]` (2).
> 5 votes

# Answer
# APL (dzaima/APL)

```
⎕←⌈∘○⍢÷*≢~≢⍬

```

Try it online!

the empty list; `[]`

its length; `0`

`~` logical NOT; `1`

`*`*e* to the power of that; `2.71828…`

`⍢÷` while inverted; `0.36787…`

`∘○` multiply by π; `1.15572…`

round up; `2`

Then we "un-invert"; `0.5`
> 5 votes

# Answer
# Desmos, 686 bytes

```
f\left(x\right)=\frac{\frac{\left(\csc x\right)\left(\csc x\right)-\left(\cot x\right)\left(\cot x\right)}{\left(\sin x\right)\left(\sin x\right)}-\frac{\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)-\left(\sin x\right)\left(\sin x\right)}{\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)-\left(\cos x\right)\left(\cos x\right)}}{\sin\left(\arcsin\left(\left(\cos x\right)\left(\cos x\right)-\cos\left(x+x\right)+\left(\left(\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)\right)\left(\cos x\right)\right)\left(\left(\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)\right)\left(\cos x\right)\right)\right)\right)+\left(\csc x\right)\left(\csc x\right)-\left(\cot x\right)\left(\cot x\right)}

```

Or rendered properly:

\\$f\left(x\right)=\frac{\frac{\left(\csc x\right)\left(\csc x\right)-\left(\cot x\right)\left(\cot x\right)}{\left(\sin x\right)\left(\sin x\right)}-\frac{\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)-\left(\sin x\right)\left(\sin x\right)}{\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)-\left(\cos x\right)\left(\cos x\right)}}{\sin\left(\arcsin\left(\left(\cos x\right)\left(\cos x\right)-\cos\left(x+x\right)+\left(\left(\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)\right)\left(\cos x\right)\right)\left(\left(\left(\sec x\right)\left(\sec x\right)-\left(\tan x\right)\left(\tan x\right)\right)\left(\cos x\right)\right)\right)\right)+\left(\csc x\right)\left(\csc x\right)-\left(\cot x\right)\left(\cot x\right)}\\$

Try it online! Defines a function f that will return 0.5 no matter what you put into it, pretty much. It will barf on multiples of π/2 though. Sorry if Desmos lags a bit.
> 5 votes

# Answer
# Desmos, ~~14~~ 7 bytes

```
e/(e+e)

```

Try it on Desmos!
> 5 votes

# Answer
# Python 3, 71 bytes

```
from http import HTTPStatus
print(HTTPStatus.OK/HTTPStatus.BAD_REQUEST) # 200/400

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), 35/12 bytes

```
Limit[(-I*I-Cos[x])/(x*x),x->I/∞]

```

The starting point for this is the following limit:

$$\lim\_{x\rightarrow 0}\frac{1-\cos(x)}{x^2} = \frac{1}{2}$$

To eliminate the numbers, I then replaced 0 with ⅈ/∞, 1 with –ⅈ^2, and x^2 with x\*x:

$$\lim\_{x\rightarrow i/\infty}\frac{-i^2-\cos(x)}{x\*x} = \frac{1}{2}$$

Or, less fancy:

```
-I*I/Floor@E

```

$$\frac{-i\*i}{\lfloor e \rfloor} = \frac{1}{\lfloor \approx 2.718 \rfloor} =\frac{1}{2}$$

\[Wasn't sure if the etiquette is to combine this with my previous answer or post separately but, following Caird's example, I did the latter.\]
> 4 votes

# Answer
# JSFuck, 2443 bytes

```
[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]])()((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[+!+[]+[!+[]+!+[]+!+[]]]+[+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+([+[]]+![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[!+[]+!+[]+[+[]]])

```

Quite big
> 4 votes

# Answer
# Factor \+ `math.unicode`

```
½ .

```

Try it online!

---

Or, slightly more interesting: since Factor has a *ton* of constants and helper words named `a`, `b`, `c`, etc. in private vocabularies, I thought it would be fun to see how far down the alphabet I had to go before arriving at a solution. Turns out not very far. I struck gold with the word `a` from the `math.finance.private` vocabulary which is defined as `: a ( n -- a ) 1 + 2 swap / ; inline` Or, in math terms: \\$a(n)=\frac{2}{n+1}\\$. Then, I just had to find a value of \\$3\\$ which turns out to be defined in `checksums.md5.private` as `CONSTANT: d 3 inline`. So:

# Factor \+ `math.finance.private checksums.md5.private`

```
d a .

```

Try it online!
> 4 votes

# Answer
# , 11 bytes

```
_"_-:@-:_"_

```

Try it online!

* In J, `-:`, as a dyadic verb, means "do the two things match?" and, as a monadic verb, means "half".
* `_` is the literal symbol for infinity. Adding `"_` turns it into a verb of infinite rank that always returns the value infinity. This is required syntactically for the right version of `_"_`, and we add it to the left one for symmetry.
* Now, for any argument, the verb checks if `_` is equal to `_`, and always returns 1. And half of 1 is 0.5.
> 3 votes

# Answer
# APL (Dyalog Unicode)

```
(+-÷)⍨⍣(×≡#⍬)≢⍬

```

Try it online!

the empty list; `[]`

its length; 0

`(``)` compute:

`#⍬` a literal; `[reference-to-root-namespace,[]]`

the depth (nestedness) of that; `-1` (maximum depth is 1, but negative value indicates raggedness)

apply the following tacit function that many times (i.e. find an argument to the following function such that the result is 0 (from the length of the empty list above)

`(``)⍨` apply this function with its sole argument as both left and right argument:

`+-÷` the sum minus the ratio

Effectively solves \\$x+x-x÷x=0\\$ or \\$2x-1=0\\$ which gives \\$x=1÷2=0.5\\$.
> 3 votes

# Answer
# Ly, 23 bytes

```
<<'<::+/u':':'u/+::<'<<

```

Try it online!

A reversible one just for fun...

```
<<                       # Shift stack left twice
  '<                     # Push "<" on the stack
    ::                   # Duplicate top of stack twice
      +/                 # Add then divide to get 0.5
        u                # Print as a number
                         # The rest of the code winds up being ignored...  The code just
                         # has to be valid and not generate output.
         ':':'u          # Push "::u" onto the stack
               /+::      # Divide, add, then duplicate top of stack twice
                   <     # Shift stack left
                    '<   # Push "<" on the stack
                      <  # Shift stack left (to an empty stack)

```

And another one that's a mirror image around a central point.

# Ly, 21 bytes

```
<<'<::+/'upu'\+::>'>>

```

Try it online!
> 3 votes

# Answer
# QBasic (QB64)

```
X = Y = Z
PRINT ATN(X) / ATN(X / Y)

```

> All variables in QBasic are initialized to 0. The first line is `X = (Y = Z)`, where the first `=` is assignment but the second `=` is comparison. Truthy is -1 in QBasic, so now `X` is -1. QB64 allows division by 0, returning floating point infinity (or in this case, negative infinity); \\$\arctan(-1) = -\frac \pi 4\\$, and \\$\arctan(-\infty) = -\frac \pi 2\\$.
> 3 votes

# Answer
# Desmos, 23 bytes

```

\frac{\{\}}{\{\}+\{\}}

```

(newline is required)

Looks crazy, but it really isn't once you figure out that `\{\}` is just `1`.

The actual crazy part is that it doesn't render properly on Desmos, though it still outputs `0.5`.

Try It On Desmos!
> 3 votes

# Answer
# RAMDISP, 19 bytes

```
[P[[[[]]][/[[]]];]]

```

RAMDISP is my own programming language, but i made it before this challenge, so i think it's allowed. \[i also had to fix a bug i left in it, which i only found after trying to do this challenge\]

explanation:

```
[P - pipes through the following array
  [
    [[[]]] - the value 2.
    [/ - divide
      [[]] - the value 1.
    ] - by the incoming number.
    ; - print the result
  ]
]

```
> 3 votes

# Answer
# Charcoal, 57 bytes

```
Ｉ⁻Ｌα⊘Ｌ

https://www.youtube.com/watch?v=AyOqGRjVtls

```

Try it online
> 2 votes

# Answer
# Python 3, 25 bytes

```
print(len("l")/len("pr"))

```

Try it online!

Short, sweet, and with only 11 distinct bytes too.
> 2 votes

# Answer
# 05AB1E, 18 bytes

```
тT*;тT*·<ŸтT*/ΩΔ;t

```

Try it online!

Choose a random float in \\$\[0.5, 2)\\$, and iterate \\$x\mapsto \sqrt{x \over 2}\\$ until convergence.

In theory the iteration converges to \\$0.5\\$ for all positive real numbers, but there might be floating point issues leading to results close to \\$0.5\\$.

---

# 05AB1E, 7 bytes

```
XΔNÌoz-

```

Try it online!

$$ 1-\sum^\infty\_{k=2}{1 \over 2^k} = 1-{1 \over 2} = {1 \over 2} $$

```
X        # start at 1
 Δ       # until the result doesn't change:
  NÌ     #   iteration index N + 2
    o    #   2 ** (N+2)
     z   #   1 / 2**(N+2)
      -  #   subtract this from the current value

```
> 2 votes

# Answer
## \<\>^v

```
≈:) :) :) :) :( :( :( )≈)?/;

```

```
≈    Duplicate top of stack (by default stack is [0])
then the :) and :( do nothing, because : executes only the next characted if the top two elements of the stack are not equal, so it skips over the parentheses.

) Increment top of stack -> stack is now [0, 1]
≈ Duplicate top of stack -> stack is now [0, 1, 1]
) Increment top of stack -> stack is now [0, 1, 2]
? Reverse stack -> stack is now [0, 2, 1]
/ Set top of stack to top of stack / second element of stack -> stack is now [0, 1, 0.5]
; Print top of stack

```

run online
> 2 votes

# Answer
# Barrel, 2 bytes

```
½

```

Evaluates to, and prints, 0.5. Not necessarily terribly imaginative, but probably one of the best solutions to this problem in Barrel.
> 2 votes

# Answer
# , 57 bytes

```
function(`+`=function(x)as.double(as.roman(x)))+'I'/+'II'

```

Try it online!

As odd as it may sound, R has a partial support for Roman numerals.

So, in this code we:

* abuse the plus sign by turning it into a function accepting Roman numerals strings and returning the numeric value
* we *aesthetically* compute `+I / +II` (we actually calculate `1 / 2` because the abused plus sign act as a roman-to-double parser)
* then we return the result
> 2 votes

# Answer
# Python 3

Not very creative but ehh

```
ord('!')/ord('B')

```

edit: as pointed out by EasyasPi (thanks), doesn't work for python 2
> 1 votes

# Answer
# Red, 82 bytes

```
print divide length? next system/locale/days to-float length? system/locale/months

```

Try it online!

Divides the number of days in a week minus one to the number of months. The current Red built doesn't need `to-float`.
> 1 votes

# Answer
# , 82 bytes

```
function()round(mean(runif(sqrt(exp(exp(pi)))) - rnorm(sqrt(exp(exp(pi))))),pi/pi)

```

Try it online!

Generates the mean of (\\$\sqrt{e ^ {e ^ \pi}}\\$ random uniform numbers in the range (0, 1) minus \\$\sqrt{e ^ {e ^ \pi}}\\$ random numbers from a normal distribution with mean 0 and standard deviation 1) and rounds it to 1 decimal place.
> 1 votes

# Answer
# ZX Spectrum Basic, 8 bytes

`PRINT SGN PI/INT EXP SGN PI`

This is actually a well-known compression technique for numeric constants. Plain `PRINT 0.5` would require 10 bytes (1 byte for the `PRINT` keyword, 3 bytes for the ASCII string `0.5`, 6 bytes for the float constant)
> 1 votes

# Answer
# Vyxal

```
\/C⌐\\C/-

```

#### Explanation:

```
\/C          . gets the codepoint of /
   ⌐         . 1 - x
    \\C      . gets the codepoint of \
       /     . division (to get -0.5)
        -    . subtract from implicit 0

```

Try it Online!
> 1 votes

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

```
Console.Write('$'/(float)'H');

```

Try it online!

Division of Ascii Codes: '$' = 36, 'H'(alf) = 72
> 1 votes

# Answer
# Python 3, 203 bytes

```
((True+True)*(True+True+True)**(True+True+True+True)*(True+True+True+True+True)/(True+True+True+True)-(True+True)**(True+True+True)*(True+True+True+True+True)**(True+True))/((True+True)*(True+True)+True)

```

Heh.
> 1 votes

# Answer
# Python 3

```
len('check')/len('check-mate')
# Output: 0.5

```
> 1 votes

# Answer
# Ruby, 27 bytes

```
->{($.**=$.).to_f/($.<<$.)}

```

Try it online!

Using the variable `$.` which is initially set to zero, and the interesting property `0⁰==1`.
> 1 votes

# Answer
# Python 3, 14 bytes

```
d=True;d/(d+d)

```

`True` is basically just `1` in Python, so this is basically just

```
1/(1+1)

```

which obviously evaluates to `0.5`.
> 1 votes

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

```
~[] / ~~(Math[`SQRT${-~-~[]}`] * Math[`SQRT${-~-~[]}`]) * ~[]

```

Try it online!

The `~~` just before the Math.SQRT2 multiplication is needed because Math.SQRT2 * Math.SQRT2 = 2.0000000000000004.
> 1 votes

# Answer
# Dyalog APL, 5 bytes

```
÷⌊*≡⍬

```

Not very creative, but golfy! Try it online.

```
÷       Inverse              ->   1/2
⌊       Floor                ->   2
*       Exponent [1]         ->   2.71828
≡       Depth                ->   1
⍬       Empty list           ->   []

[1]: Default base is e, so e^1

```
> 0 votes

# Answer
# JavaScript

```
t=true;
console.log((t) / ((t) ^ (t + t) ^ (t)) ** (t));

```

JavaScript works well, here is a simple numerically deficient example getting you the half or it.
> 0 votes

# Answer
# JAVA

As a simple java project. I haven't looked at the others, so it is entirely possible (and likely) that this is the umpteenth answer to contain this solution. This code, placed inside `src/Run.java` of a fresh project, will return o.5.

The actual algorithm is only 2 (sorry, two XD) lines; The rest is just getting it to print. I know you asked for whimsical, but I was impressed with the simplicity of this, so I used it, for better or worse....

This algorithm takes advantage of the fact that any number, when divided by (itself plus itself) will give one half.

```
public class Run {

    public static void main(String[] args) {
        double x = Math.random();
        double y = x/(x+x);
        System.out.println(y);

    }

```

}

Btw, Im not sure how to do the giant text in md, so I just used a title hash. Ill be back to fix once I figure it out.

EDIT: Although I guess using java for this two line solution is a bit whimsical! LOL
> 0 votes

---
Tags: popularity-contest, restricted-source
---


title: Space Cleaners!

text:
# Question
Title: Space Cleaners!
A space cleaner is a special character which removes all spaces between it and the first non space character to its left and it is represented by a '!' character. If it reaches the beginning of the string it stops.

Given a string output the string in any reasonable format after the cleaning process.

Trailing spaces at the end of the string must be still be in the output.

Remember that space cleaners remain after their job.

Input will only consist of printable ASCII characters.

This is code-golf, so least number of bytes win.

# Test Cases

```
" ! a! !b c!d !" => "! a!!b c!d!"
"a    !" => "a!"
"!    a" => "!    a"
"!    !    !" => "!!!"
"! " => "! "

```

# Answer
> 8 votes
# 05AB1E, 5 bytes

```
„ !¤:

```

Try it online!

---

### Explanation

```
„ !                  # 2 char string " !"
   ¤                 # Push the tail of that (so "!")
    :                # Infinite replacement

```

# Answer
> 5 votes
# Retina, 5 bytes

```
 +!
!

```

Try it online.

Not much to say. Simply removes all spaces in front of every `!` with a simple replace.

# Answer
> 5 votes
# JavaScript (ES6), 24 bytes

Thanks to @Nick Kennedy for the TIO link and -2 bytes, since I could omit the function name `f=`

```
_=>_.replace(/ +!/g,'!')

```

Try It Online

Nothing special, same regex as other answers. New to `codegolf`, was a simple one to translate to js. If anyone can think of improvements I'd love to see them.

# Answer
> 4 votes
# PHP, 35 bytes

```
<?=preg_replace('/ +!/','!',$argn);

```

Try it online!

Just a simple RegEx replace.

# Answer
> 4 votes
# Haskell, ~~48~~ 42 bytes

*-6 bytes thanks to H.PWiz!*

```
g(' ':b)|'!':_<-g b=g b
g(a:b)=a:g b
g a=a

```

Try it online!

### Explanation:

```
g(' ':b)                 -- Given a string starting with space
        |'!':_           -- Check if '!' is the first element of
              <-g b      -- The function applied to the rest of it
                   =g b  -- Return the function applied to the rest of it
g(a:b)=a:g b             -- Otherwise just apply the function recursively
g a=a                    -- Until the string is empty

```

# Answer
> 4 votes
# , 25 bytes

```
gsub(" +!","!",scan(,''))

```

Straightforward enough with a simple regex substitution!

Try it online!

# Answer
> 3 votes
# Python 3, 50 bytes

```
f=lambda s:' !'in s and f(s.replace(' !','!'))or s

```

Try it online!

Port of Expired Data's 05AB1E answer, so make sure to upvote him!

---

Original answer:

# Python 3, 63 bytes

```
lambda s:'!'.join(i.rstrip(' ')for i in(s+'_').split('!'))[:-1]

```

Try it online!

# Answer
> 3 votes
# brainfuck, 66 bytes

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

```

Try it online!

It's funny how much space is just taken up by constants, in this case making a space takes up more than a quarter of the code.

# Answer
> 3 votes
# Haskell, 34 bytes

```
foldr(%)""
' '%r@('!':_)=r
c%s=c:s

```

Try it online!

# Answer
> 3 votes
# ksh, 18 bytes

try it online!

```
echo ${1//+( )!/!}

```

**zsh, 32 bytes**
Since there's another **zsh** answer I changed to **ksh**. Thanks to @Gilles at unix.se for zsh help. try it online!
`setopt ksh_glob;<<<${1//+( )!/!}`

# Answer
> 3 votes
# ///, 6 bytes

```
/ !/!/

```

Try it online!

Replaces every occurrence of  `!` with `!` until it eats up all the spaces in front of the exclamation marks.

The language is a perfect match because it's built on find/replace. That's the only command you're given, and not a single special character or wild card to use in your patterns, except the `\` which only serves to escape the `/`. Yet, it's Turing complete. It's really elegant!

The language is read by slash triplets, hence the name. Each one couches a find pattern and replace pattern. We have one such pattern here doing precisely what it says at the top. The first pair of slashes says to find all  `!` and the second pair says to replace them with `!`.

# Answer
> 2 votes
# Perl 5 (`-p`), 9 bytes

```
s/ *!/!/g

```

TIO

# Answer
> 2 votes
# Python 3, 38 bytes

```
lambda s:re.sub(' +!','!',s)
import re

```

A simple regex substitution. Replaces any amount of space plus an exclamation mark with just an exclamation mark.

# Answer
> 2 votes
# PowerShell, 22 bytes

```
$args-replace' +!','!'

```

Try it online!

# Answer
> 2 votes
# Jelly, 11 bytes

```
œṣ⁾ !j”!µÐL

```

Try it online!

# Answer
> 2 votes
### Zsh with `extended_glob`, 14 bytes

```
<<<${1// #!/!}

```

Zsh with `extended_glob` is not an arbitrary whim: it's the language in which zsh completion functions are written. Inspired by roblogic's initial attempt. Try it online.

# Answer
> 2 votes
# Charcoal, 22 bytes

```
≔ ηＦ⮌Ｓ«≡ι!≔ωη ≔ηι≔ η←ι

```

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

```
≔ η

```

`h` is a variable that specifies whether a space is being cleaned or not.

```
Ｆ⮌Ｓ«

```

Loop over the string in reverse as the spaces are cleaned to the left.

```
≡ι

```

Switch over the current character.

```
!≔ωη

```

If it's a `!` then start cleaning spaces.

```
 ≔ηι

```

If it's a space then replace it with the space cleaning flag.

```
≔ η

```

Otherwise turn off space cleaning.

```
←ι

```

Print the current character leftwards.

Boring 15-byte version:

```
Ｗ№θ !≔⪫⪪θ !¦!θθ

```

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

```
Ｗ№θ !

```

Repeat while there are spaces to be cleaned.

```
≔⪫⪪θ !¦!θ

```

Clean up to one space per space cleaner.

```
θ

```

Output the result.

# Answer
> 1 votes
# Japt, 7 bytes

Recursive replacement. Could save 2 bytes if we could choose the "cleaner" character.

```
e" !"'!

```

Try it

# Answer
> 1 votes
# C (clang), 79 bytes

```
j,e;f(char*s){for(j=e=0;!e;e=!*s++)*s-32?s-=*s-33?j:0,j=0,*s&&putchar(*s):j++;}

```

Try it online!

Saved 1 thanks to @ceilingcat \*s && instead of !\*s ||

j is used to jump back if there is no "!" after spaces.

# Answer
> 1 votes
# Perl 6, 14 bytes

```
{S:g/\s+\!/!/}

```

Try it online!

Loses bytes over other regex solutions since I can't use a literal space and I have to escape the metaoperator `!`

# Answer
> 1 votes
# , 16 bytes

```
(#~1-' !'E.])^:_

```

Try it online!

# Answer
> 1 votes
# Ruby `-p`, 14 bytes

```
gsub(/ +!/,?!)

```

Unfortunately the 13-byte `gsub / +!/,?!` doesn't work because Ruby interprets the first `/` as division instead of the start of a regex statement.

Try it online!

# Answer
> 1 votes
# Java 8+, 26 bytes

Yet another regex port

```
s->s.replaceAll(" +!","!")

```

TIO

# Answer
> 1 votes
# Pip, 8 bytes

```
aRw.'!'!

```

Try it online!

concatenates the whitespace regex variable `w` with an `!` character. then replaces it with a single `!` in the string.

# Answer
> 1 votes
# Husk, 8 bytes

```
ωσ" !""!

```

Try it online!

# Answer
> 1 votes
# AWK, 16 bytes

```
gsub(" *!","!")1

```

Try it online!

Similar regex to some others that were posted, just AWK-styled. Adding a random number on the end makes sure it prints even if the input has no cleaner character.

# Answer
> 0 votes
# Vyxal, 9 bytes

```
` *!`\!øṙ

```

Try it Online!

Another one ports the regex

---
Tags: code-golf
---


# Question
Title: User Scored Code Golf - Drawing Diamonds [experimental]
This challenge will behave more or less like a traditional . The only difference is that instead of scoring answers by their number of characters or bytes, users will assign *weights* to different characters in the comments and the program with the lowest cumulative weight will win.

# Challenge

Your task is to write a program that takes a string and prints a diamond shape where the first character starts in the center and subsequent characters occupy the empty spaces orthogonal to the set of characters that were placed last. Spaces () will be used for padding.

For example inputting `CAT` would produce

```
  T
 TAT
TACAT
 TAT
  T

```

and `()` would produce

```
 )
)()
 )

```

and `desserts` would produce

```
        s
       sts
      strts
     strerts
    streserts
   stressserts
  stressesserts
 stressedesserts
stressed desserts
 stressedesserts
  stressesserts
   stressserts
    streserts
     strerts
      strts
       sts
        s

```

and `9` would produce `9`.

# Details

* The code may only contain printable ASCII and newlines. (See why below.)
* Input/output should be via stdin/stdout, or, if they aren't possible, use similar alternatives.
* You may assume the input string only contains printable ASCII (including space).
* Columns of leading spaces not containing any portion of the diamond pattern are **not** allowed in the output. Any amount and combination of trailing spaces spaces is allowed.
* There may optionally be a trailing newline in the output.
* You may edit your answer as much as you want.

# Scoring

All code must be written using only newlines and the 95 printable ASCII characters:

```
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```

(Sadly tabs are not allowed because Stack Exchange renders them as spaces in code blocks.)

Each of these 96 characters has a *weight* value associated with it. By default, all the weights are 97.

The score of a program is the sum of the weight values for each of its characters. For example, if the program were `print(4)` and the weight for `4` was 70, but unchanged for everything else, the score would be `749 = 97+97+97+97+97+97+70+97`.

Once the activity in this question settles down to almost nothing, the lowest scoring submission wins. In the presumably unlikely case of tie the wins goes to the highest voted answer.

# Changing Weights

Every user, whether they've answered or not, can change the weight of one of the 96 characters to a unique value from 1 to 96. To do this, add a comment to this question of the form `#### W -> C ####`, where W is an integer from 1 to 96 and C is the character (as itself, no quotes, no backticks). Use `\n` in place of C for newlines and `\s` for space since Stack Exchange compresses 3 spaces in a row. The `print(4)` example above would have had the comment `#### 70 -> 4 ####`.

**Each user may only make ONE comment like this, and it will only be valid if both the character and the weight value have not been used in a previously made comment.** Thus eventually, there may be 96 `#### W -> C ####` comments, all from different users, all with different weights assigned to different characters.

Users may delete their own comment if they want to, resetting their characters' weight back to 97 until they or someone else comments again. They may also edit them. Comments not following the rules about distinct users/weights/characters should be deleted or flagged as "not constructive". General comments about rules and other things are fine but should be kept at a minimum.

This stack snippet is the official leaderboard for this question. It automatically computes the scores for all submissions by gathering the weights from comments each time it is run. It does not handle ties. You can also use it to check the score a program would have.

You'll probably need to `right-click -> Open link in new tab` for the links.

```
function compute(){var e=computeScore($("#code").val());$("#score").val(e==-1?"Invalid characters":e)}function computeScore(e){var t=0;for(var n=0;n<e.length;n++){if(weights.hasOwnProperty(e[n])){t+=weights[e[n]]}else{return-1}}return t}function htmlDecode(e){var t=document.createElement("div");t.innerHTML=e;return t.childNodes.length===0?"":t.childNodes[0].nodeValue}function addLeaderboard(){validAnswers.sort(function(e,t){return e.score>t.score});var e=1;var t="";for(var n=0;n<validAnswers.length;n++){var r=validAnswers[n];t+="<tr><td>"+e+"</td><td><a href='"+r.link+"'>"+r.owner.display_name+"</a></td><td>"+r.score+"</td><td>"+r.length+"</td></tr>";if(n+1<validAnswers.length&&validAnswers[n+1].score>r.score){e++}}$("#leaderboard").append(t)}function addAnalytics(){var e="";for(var t in weights){if(weights.hasOwnProperty(t)&&weights[t]!=defaultWeight){e+=(t=="\n"?"\\n":t)+"="+weights[t]+" "}}$("#weights").val(e);var n="";for(var t in usedChars){if(usedChars.hasOwnProperty(t)&&usedChars[t]==false){n+=t=="\n"?"\\n":t}}$("#unusedc").val(n);var r="";for(var t in usedWeights){if(usedWeights.hasOwnProperty(t)&&usedWeights[t]==false){r+=t+" "}}$("#unusedw").val(r);var i="";if(invalidComments.length>0){for(var s=0;s<invalidComments.length;s++){var o=invalidComments[s];i+="<a href='#"+o.link+"'>"+o.owner.display_name+"</a> "}}else{i="none"}$("#comments").html(i);var u="";if(invalidAnswers.length>0){for(var s=0;s<invalidAnswers.length;s++){var a=invalidAnswers[s];u+="<a href='#"+a.link+"'>"+a.owner.display_name+"</a> "}}else{u="none"}$("#answers").html(u)}function checkAnswers(e){for(var t=0;t<e.items.length;t++){var n=e.items[t];var r=answerPattern.exec(n.body);if(r){var i=htmlDecode(r[1]);var s=computeScore(i);if(s==-1){invalidAnswers.push(n)}else{n.length=i.length;n.score=s;validAnswers.push(n)}}else{invalidAnswers.push(n)}}addLeaderboard();addAnalytics()}function checkComments(e){for(var t=0;t<e.items.length;t++){var n=e.items[t];var r=commentPattern.exec(htmlDecode(n.body));if(r){var i=n.owner.user_id;var s=parseInt(r[1]);var o=r[2]=="\\n"?"\n":r[2]=="\\s"?" ":r[2];if(userIDs.hasOwnProperty(i)||!usedWeights.hasOwnProperty(s)||usedWeights[s]||!usedChars.hasOwnProperty(o)||usedChars[o]){invalidComments.push(n)}else{userIDs[i]=true;usedWeights[s]=true;usedChars[o]=true;weights[o]=s}}}$.get(answersURL,checkAnswers)}function refresh(){$.get(commentsURL,checkComments)}questionID=45040;commentsURL="https://api.stackexchange.com/2.2/questions/"+questionID+"/comments?order=asc&sort=creation&site=codegolf&filter=!t)IWLXOkOvAuPe8m2xJrXOknWcw(ZqZ";answersURL="https://api.stackexchange.com/2.2/questions/"+questionID+"/answers?order=desc&sort=activity&site=codegolf&filter=!.FjsvG2LuND(frE*)WTvqQev1.lyu";commentPattern=/^#### (\d+) -> (\\(?:n|s)|[ -~]) ####$/;answerPattern=/<pre><code>((?:\n|.)*?)\n<\/code><\/pre>/;chars="\n !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";validAnswers=[];invalidAnswers=[];invalidComments=[];userIDs={};usedWeights={};usedChars={};weights={};defaultWeight=chars.length+1;for(var i=0;i<chars.length;i++){usedChars[chars[i]]=false;usedWeights[i+1]=false;weights[chars[i]]=defaultWeight}refresh()
```

```
*{font-family:Helvetica,Arial,sans-serif}table{border:3px solid green;border-collapse:collapse}button{font-size:100%}th{background-color:green;color:#fff;padding:6pt}td{border:1px solid green;padding:6pt}.large{font-size:140%}.title{font-weight:700;margin:6pt 0}textarea{font-family:"Courier New";white-space:nowrap;overflow:auto}input[readonly]{background-color:#dcdcdc}.analytics{font-size:90%;padding:4pt 0 0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class='large title'>Leaderboard</div><table id='leaderboard'> <tr> <th>Place</th> <th>Submitter</th> <th>Score</th> <th>Program Length</th> </tr></table><br><div class='title'>Compute Score</div><textarea id='code' rows='5' cols='40' placeholder='paste code here...'></textarea><br><button type='button' onclick='compute()'>Compute</button> Score: <input type='text' id='score' readonly><br><br><div class='title'>Analytics</div><div class='analytics'>Assigned weights: <input type='text' id='weights' readonly></div><div class='analytics'>Unused characters: <input type='text' id='unusedc' readonly> (all weight 97)</div><div class='analytics'>Unused weights: <input type='text' id='unusedw' readonly></div><div class='analytics'>Invalid comments (duplicate user/char/weight): <span id='comments'></span></div><div class='analytics'>Invalid answers (illegal characters or no code block): <span id='answers'><span></div><br><button type='button' onclick='refresh'>Refresh</button>
```

For this leaderboard to work, the comments must be in the exact format described above and your program's code must be in the first multi-line code block in your answer (the `<pre><code>...</code></pre>` ones). Don't use syntax highlighting or your code won't be read correctly. The snippet can take a minute or two before it updates.

I have not tested the snippet thoroughly but I'll be keeping an eye on it as this contest gets underway. If you notice any bugs please tell me. Here is an non-minified version:

```
questionID = 45040

commentsURL = 'https://api.stackexchange.com/2.2/questions/' + questionID + '/comments?order=asc&sort=creation&site=codegolf&filter=!t)IWLXOkOvAuPe8m2xJrXOknWcw(ZqZ'

answersURL = 'https://api.stackexchange.com/2.2/questions/' + questionID + '/answers?order=desc&sort=activity&site=codegolf&filter=!.FjsvG2LuND(frE*)WTvqQev1.lyu'

commentPattern = /^#### (\d+) -> (\\(?:n|s)|[ -~]) ####$/
answerPattern = /<pre><code>((?:\n|.)*?)\n<\/code><\/pre>/

chars = '\n !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'

validAnswers = []
invalidAnswers = []
invalidComments = []

userIDs = {}
usedWeights = {}
usedChars = {}
weights = {}
defaultWeight = chars.length + 1

for (var i = 0; i < chars.length; i++) {
    usedChars[chars[i]] = false
    usedWeights[i + 1] = false
    weights[chars[i]] = defaultWeight
}

function compute() {
    var score = computeScore($('#code').val())
    $('#score').val(score == -1 ? 'Invalid characters' : score)
}

function computeScore(code) {
    var score = 0
    for(var i = 0; i < code.length; i++) {
        if (weights.hasOwnProperty(code[i])) {
            score += weights[code[i]]
        } else {
            return -1
        }
    }
    return score
}

function htmlDecode(input)  {
  var e = document.createElement('div')
  e.innerHTML = input;
  return e.childNodes.length === 0 ? '' : e.childNodes[0].nodeValue
}

function addLeaderboard() {
    validAnswers.sort(function(a,b) { return a.score > b.score} )

    var place = 1
    var rows = ''

    for(var i = 0; i < validAnswers.length; i++) {
       var a = validAnswers[i]
       rows +=
           '<tr><td>' + place +
           "</td><td><a href='" + a.link + "'>" + a.owner.display_name + "</a></td><td>" +
           a.score + '</td><td>' + a.length + '</td></tr>'

       if (i + 1 < validAnswers.length && validAnswers[i + 1].score > a.score) {
           place++
       }
    }

    $('#leaderboard').append(rows)
}

function addAnalytics() {
    //assigned weights
    var assigned = ''
    for (var key in weights) {
        if (weights.hasOwnProperty(key) && weights[key] != defaultWeight) {
            assigned += (key == '\n' ? '\\n' : key) + '=' + weights[key] + ' '
        }
    }
    $('#weights').val(assigned)

    //unused chars
    var unusedc = ''
    for (var key in usedChars) {
        if (usedChars.hasOwnProperty(key) && usedChars[key] == false) {
            unusedc += key == '\n' ? '\\n' : key
        }
    }
    $('#unusedc').val(unusedc)

    //unused weights
    var unusedw = ''
    for (var key in usedWeights) {
        if (usedWeights.hasOwnProperty(key) && usedWeights[key] == false) {
            unusedw += key + ' '
        }
    }
    $('#unusedw').val(unusedw)

    //invalid comments
    var invalidc = ''
    if (invalidComments.length > 0) {
        for (var i = 0; i < invalidComments.length; i++) {
            var c = invalidComments[i]
            invalidc += "<a href='#" + c.link + "'>" + c.owner.display_name + '</a> '
        }
    } else {
        invalidc = 'none'
    }
    $('#comments').html(invalidc)

    //invalid answers
    var invalida = ''
    if (invalidAnswers.length > 0) {
        for (var i = 0; i < invalidAnswers.length; i++) {
            var a = invalidAnswers[i]
            invalida += "<a href='#" + a.link + "'>" + a.owner.display_name + '</a> '
        }
    } else {
        invalida = 'none'
    }
    $('#answers').html(invalida)
}

function checkAnswers(answers) {
    for (var i = 0; i < answers.items.length; i++) {
        var answer = answers.items[i]
        var match = answerPattern.exec(answer.body)
        if (match) {
            var code = htmlDecode(match[1])
            var score = computeScore(code)
            if (score == -1) {
                invalidAnswers.push(answer)
            } else {
                answer.length = code.length
                answer.score = score
                validAnswers.push(answer)
            }
        } else {
            invalidAnswers.push(answer)
        }
    }

    addLeaderboard()
    addAnalytics()
}

function checkComments(comments) {
    for (var i = 0; i < comments.items.length; i++) {
        var comment = comments.items[i]
        var match = commentPattern.exec(htmlDecode(comment.body))
        if (match) {
            var userID = comment.owner.user_id
            var weight = parseInt(match[1])
            var char = match[2] == '\\n' ? '\n' : (match[2] == '\\s' ? ' ' : match[2])

            //check validity
            if (userIDs.hasOwnProperty(userID) ||
                !usedWeights.hasOwnProperty(weight) || usedWeights[weight] ||
                !usedChars.hasOwnProperty(char) || usedChars[char])
            {
                invalidComments.push(comment)
            } else {
                userIDs[userID] = true
                usedWeights[weight] = true
                usedChars[char] = true
                weights[char] = weight
            }
        }
    }
    $.get(answersURL, checkAnswers)
}

function refresh() {
    $.get(commentsURL, checkComments)
}

refresh()
```

```
* {
    font-family: Helvetica, Arial, sans-serif;
}

table {
    border: 3px solid green;
    border-collapse: collapse;
}

button {
    font-size: 100%;
}

th {
    background-color: green;
    color: white;
    padding: 6pt;
}

td {
    border: 1px solid green;
    padding: 6pt;
}

.large{
    font-size: 140%;
}

.title{
    font-weight: bold;
    margin: 6pt 0 6pt 0;
}

textarea {
    font-family: "Courier New";
    white-space: nowrap; overflow: auto;
}

input[readonly]
{
    background-color: gainsboro;
}

.analytics {
    font-size: 90%;
    padding: 4pt 0 0 0;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='large title'>Leaderboard</div>
<table id='leaderboard'>
  <tr>
    <th>Place</th>
    <th>Submitter</th>
      <th>Score</th>
    <th>Program Length</th>
  </tr>
</table>
<br>
<div class='title'>Compute Score</div>
<textarea id='code' rows='5' cols ='40' placeholder='paste code here...'></textarea><br>
<button type='button' onclick='compute()'>Compute</button> Score: <input type='text' id='score' readonly>
<br>
<br>
<div class='title'>Analytics</div>
<div class='analytics'>Assigned weights: <input type='text' id='weights' readonly></div>
<div class='analytics'>Unused characters: <input type='text' id='unusedc' readonly> (all weight 97)</div>
<div class='analytics'>Unused weights: <input type='text' id='unusedw' readonly></div>
<div class='analytics'>Invalid comments (duplicate user/char/weight): <span id='comments'></span></div>
<div class='analytics'>Invalid answers (illegal characters or no code block): <span id='answers'><span></div>
<br>
<button type='button' onclick='refresh'>Refresh</button>
```

Keep in mind that this scoring system is completely new and experimental. Hopefully Stack Exchange won't mind that it involves tons of comments. :P

*Related challenge: Print this diamond*

# Answer
> 4 votes
# CJam, 144 150 bytes

```
"x*3:*3:3*::33:3:::333*::333*3::***3::**::33:3::3*:::::*3:3:3:**33*333333::33*:*333:*3*3**:**3:**:3*3:33*3:3*:333**:3**33:*3:::*:3*::3"'3/'b*3b127b:c~

```

Tried some encoding...

Updated because the weight of `b` has changed.

Another encoding which is only better in theory (140 bytes):

```
":***(*3:**3*I**:3*****:*3*******: ::::*:***II@3*******: :**I:**:***:*3***3*I3I:3***33:::*I**3I***3***:3:*I*3I"{"*:I3( **@"#1a*~0}%2b126b:c~

```

# Answer
> 5 votes
# Python 2, 120 bytes

```
T=raw_input()
L=len(T)
r=[b[::-1]+b[1:]for b in [T[-b:]+' '*(L-b)for b in range(1,L+1)]]
for b in r[:-1]+r[::-1]:print b

```

Edit: Lowered cost with some cheaper characters.

# Answer
> 3 votes
# Pyth, 21 bytes

```
L+_tbbjbymy+>zd*\ dlz

```

Try it online: Pyth Compiler/Executor

# Answer
> 2 votes
# CJam, 31 bytes

```
lW%_,:I(S*\+I*I/2%{_W%1>+z}2*N*

```

Just an adaptation of my answer to Print this diamond for now. I might tweak it when the weights have changed.

Test it here.

# Answer
> 1 votes
# J, 45 chars

```
(({~((]*]<#@[)>:@(+/~)@:|@i:@(2-#)))@(' '&,))

```

Longish solution, will golf it with some cheap chars...

Try it online. (Append input string with single quotes.)

# Answer
> 1 votes
# PHP (131 chars)

```
function f($s){for($i=-($l=strlen($s));$i<$l;$I=abs(++$i)){$t=substr($s,$I);echo str_repeat(' ',$I).strrev($t).substr($t,1)."\n";}}

```

http://3v4l.org/9Vvkm

Will optimise once the weightings are clearer.

# Answer
> 1 votes
# Vyxal `j`, 61 bytes, score 4890.

```
fK\a:-$vj:vL?Lv-\ v*$+?:L1-wifK\a:-$vjvm2v/vt\a:-p+:wRh1?L"iJ

```

Try it Online!

This was painful, especially in a language with a huge codepage that I can only use a small bit of.

Score calculation + explanation coming soon.

Thanks to lyxal for finding some clever ways for me to do various things.

# Answer
> 0 votes
## Java, 318 bytes

```
class N{public static void main(String[]a){char[]s=new java.util.Scanner(System.in).nextLine().toCharArray();int l=s.length,m=l-1,$=0,b;String t="";for(;$<l;$++,t+='\n')for(b=0;b<l+$;b++)t+=b+$<m?' ':s[b>m?m-b+$:b+$-m];for($=l-2;$>-1;$--,t+='\n')for(b=0;b<l+$;b++)t+=b+$<m?' ':s[b>m?m-b+$:b+$-m];System.out.print(t);}}

```

---
Tags: code-challenge, ascii-art, printable-ascii
---


title: Super Square Rain

text:
# Question
Title: Super Square Rain
The Scream™ Winter Sale is on and you just nabbed yourself an intense minimalist action game, Super Square. Upon playing it, you come to the realisation that either the game's just ridiculously hard or you're just *really* bad at it. In particular, there's this "rain" pattern that seems to get you every time...

Frustrated, you decide to give yourself a different challenge: Draw the rain pattern in ASCII art!

# Input

Input is a single positive integer indicating the size of the pattern `n`, given via STDIN or function argument.

# Output

Output is the rain pattern at the specified size, returned as a string or printed via STDOUT. Leading or trailing whitespace before or after the entire image is okay. Additionally, the image need not be flush to the left of the screen, but must be clearly discernible.

Here's `n = 10`:

```
 ...................
| ----------------- |
|  ...............  |
| | ------------- | |
| |  ...........  | |
| | | --------- | | |
| | |  .......  | | |
| | | | ----- | | | |
| | | |  ...  | | | |
| | | | | - | | | | |
| | | | |   | | | | |
| | | | | - | | | | |
| | | |  ...  | | | |
| | | | ----- | | | |
| | |  .......  | | |
| | | --------- | | |
| |  ...........  | |
| | ------------- | |
|  ...............  |
| ----------------- |
 ...................

```

Here's `n = 5`:

```
 ---------
  .......
 | ----- |
 |  ...  |
 | | - | |
 | |   | |
 | | - | |
 |  ...  |
 | ----- |
  .......
 ---------

```

And finally, here's `n = 1` (just the innermost two walls):

```
 -

 -

```

# Construction (for extra clarity)

The playing area is divided into two pairs of quadrants like so:

```
 AAAAAAAAA
B AAAAAAA B
BB AAAAA BB
BBB AAA BBB
BBBB A BBBB
BBBBB BBBBB
BBBB A BBBB
BBB AAA BBB
BB AAAAA BB
B AAAAAAA B
 AAAAAAAAA

```

The upper/lower quadrants should alternate between horizontal walls represented by hyphens `-`, and gaps shaded with dots `.`. The left/right quadrants should alternate between spaces  and vertical walls represented by pipes `|`. The main diagonals are empty, and should always be filled with spaces.

The rain pattern of size `n` has `2n` walls, with walls from the upper/lower quadrants closest to the centre and walls alternating between quadrants as we move away from the centre.

# Scoring

This is code-golf, so the code in the fewest bytes wins.

# Answer
> 3 votes
# CJam, ~~93 87 78 61~~ 59 bytes

```
ri:K_+){K" |"*KKI-z:I-I2%:L+<SL>\+_W%L'-'.?I2*Ig-*@I0=>N}fI

```

Takes value `n` via STDIN

Few examples:

```
1
 -

 -
2
 ...
| - |
|   |
| - |
 ...
5
 ---------
  .......
 | ----- |
 |  ...  |
 | | - | |
 | |   | |
 | | - | |
 |  ...  |
 | ----- |
  .......
 ---------
10
 ...................
| ----------------- |
|  ...............  |
| | ------------- | |
| |  ...........  | |
| | | --------- | | |
| | |  .......  | | |
| | | | ----- | | | |
| | | |  ...  | | | |
| | | | | - | | | | |
| | | | |   | | | | |
| | | | | - | | | | |
| | | |  ...  | | | |
| | | | ----- | | | |
| | |  .......  | | |
| | | --------- | | |
| |  ...........  | |
| | ------------- | |
|  ...............  |
| ----------------- |
 ...................

```

This can be golfed a lot, which I will do first thing tomorrow.

Try it online here

# Answer
> 5 votes
# Haskell 150 bytes

I realize it's not going to win, just wanted to post my first codegolf :D

```
q n=putStr$unlines$iterate(\l->let[a,b]=if l!!0!!1=='-'then"|."else" -";c=[a:s++[a]|s<-l];t=' ':[b|x<-l!!0]++" "in t:c++[t])[" - ","   "," - "]!!(n-1)

```

Use by loading into GHCi and calling `q n` where `n` is the size.

Some examples:

```
*Main> q 1
 -

 -
*Main> q 2
 ...
| - |
|   |
| - |
 ...
*Main> q 5
 ---------
  .......
 | ----- |
 |  ...  |
 | | - | |
 | |   | |
 | | - | |
 |  ...  |
 | ----- |
  .......
 ---------
*Main> q 10
 ...................
| ----------------- |
|  ...............  |
| | ------------- | |
| |  ...........  | |
| | | --------- | | |
| | |  .......  | | |
| | | | ----- | | | |
| | | |  ...  | | | |
| | | | | - | | | | |
| | | | |   | | | | |
| | | | | - | | | | |
| | | |  ...  | | | |
| | | | ----- | | | |
| | |  .......  | | |
| | | --------- | | |
| |  ...........  | |
| | ------------- | |
|  ...............  |
| ----------------- |
 ...................

```

Someone can probably do better, I'm fairly new to Haskell.

# Answer
> 3 votes
# Python, ~~204~~,~~198~~,191 bytes

```
r=lambda a,b,d=' ':d.join((a,b,a[::-1]))
def f(s,i,n):d=[r(s[:i],'.-'[(n-i)%2]*((n-i)*2-1))];return i==n and[r(s,' '*(2*(i%2)+1),'')]or d+f(s,i+1,n)+d
g=lambda n:'\n'.join(f('| '*(n/2),0,n))

```

"r" is a utility function that writes "b" surrounded by reflected "a", with an optional delimiter, (yes lambda parameters can have defaults). "f" is recursive, generating sides and middle parts for each level "g" is the rain function, which can be called with an integer to return the text requested.

# Answer
> 2 votes
# Vyxal `j`, 43 bytes

```
ʀ›ƛ?∷-½⌊‛| ?∷ßṘ*ð?∷ßðn?+∷*⁰n-›:‛.-$i*Ṡøm;øm

```

Try it Online!

A bit of a mess, but it works!

# Answer
> 1 votes
# Perl 5: 74 bytes (73 code + `-p`)

```
#!perl -p
s/.*/ /;$a=qw(- .)[$|--]x
s/.+/$"$&$"/g,s/^|\z/ $a
/g,$"^="\\"for($_)x$&

```

Takes parameter on the input (end of line character required for proper function):

```
$ perl rain.pl <<<"3"
 -----
  ...
 | - |
 |   |
 | - |
  ...
 -----

```

Ungolfed:

```
                         # Read the input line into $_ (-p)
s/.*/ /;                 # Replace the input with a space (plus the original eol), saves the parameter in $&
for(($_)x$&) {           # Iterate $& times without affecting $_
  $c=s/.+/$"$&$"/g;      # Add $" (initially space) at the start and the end of each line, stores number of lines in $c
  $a=("-",".")[$|--]x$c; # Set $a to $c times minus or dot using magic $| (which iterates over 1 and 0 on decrement)
  s/^|\z/ $a \n/g;       # Equivalent to $_=" $a \n$_ $a \n"
  $"^="\\";              # Alternate $" between space and bar using the string xor
}
                         # Print $_ (-p)

```

# Answer
> 1 votes
# Japt `-R`, 25 bytes

This ended up being longer than I expected, especially once I'd realised I'd gotten the pattern completely wrong! So I may be able to get it down smaller with a different method, but this'll do for now.

```
ôÈçXg-i.¹²Åû3wXÑÄÃûSi|)Ôê

```

Try it

```
ôÈçXg-i.¹²Åû3wXÑÄÃûSi|)Ôê     :Implicit input of integer
ô                             :Range [0,input]
 È                            :Map each X
  ç                           :  X times repeat
   Xg                         :    Index X into
     -i.                      :      "-" prepended with "."
        ¹                     :  End repeat
         ²                    :  Repeat twice
          Å                   :  Slice off the first character
           û                  :  Centre pad with spaces to length
            3w                :  Maximum of 3 and
              XÑ              :    X*2
                Ä             :    Plus 1
                 Ã            :End map
                  û           :Centre pad each to the length of the longest with
                   S          :  Space
                    i|        :  Prepended with "|"
                      )       :End padding
                       Ô      :Reverse
                        ê     :Palindromise
                              :Implicit output joined with newlines

```

# Answer
> 1 votes
# Python 3.8 (pre-release), 120 bytes

```
def f(s):W=[(~s%2+i)//2*"| "+(~s-i)%2*" "+(s-i)*"'-"[i+s&1]for i in range(s+1)];[print(i+i[-2::-1])for i in W+W[-2::-1]]

```

Try it online!

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


# Question
Title: Distinguish English and Spanish with regular expressions
The task is to to compete for the **shortest regex** (in **bytes**) in your preferred programming language which can distinguish between English and Spanish with minimum ~~**`60%`**~~ **`90%`** accuracy.

Silvio Mayolo's submission (pinned as `Best Answer`) has secured his spot as the winner of original contest against any chance of being contested. In order to provide room for further submissions, he has generously allowed the scoring requirement to be pushed to 90% accuracy.

# Links to wordlists have been replaced due to concerns voiced in the comments.

The following word lists (based on these) must be used: English, Spanish

The Spanish wordlist is already transliterated into ASCII, and there is no word present in either which is also present in the other.

A naive approach to distinguishing Spanish from English might be to match if the word ends in a vowel:

# `[aeiou]$` `i` 9 bytes

Here's a live example, where `6` of `8` words are successfully identified, for `75%` accuracy:

```
const regex = /[aeiou]$/i;

const words = [
  'hello',
  'hola',
  'world',
  'mundo',
  'foo',
  'tonto',
  'bar',
  'barra'
];

words.forEach(word => {
  const match = word.match(regex);
  const langs = ['English', 'Spanish'];
  const lang = langs[+!!match];
  console.log(word, lang);
});
```

# Answer
> 36 votes
# Any Language, 0.3677 (60.6064%, 1 byte)

```
a

```

No, I'm not joking. The single-character regular expression `a` successfully identifies Spanish words over English given your input files 60.6064% of the time, which makes it a valid submission.

Here's a complete, runnable Perl script that checks the percentage of this regular expression, assuming you've downloaded `english.json` and `spanish.json` into the same folder as the script.

```
#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my @english;
my @spanish;

my $fh;
open $fh, '<', 'english.json';
while (<$fh>) {
    push @english, $1 if /"(\w+)"/;
}
close $fh;

open $fh, '<', 'spanish.json';
while (<$fh>) {
    push @spanish, $1 if /"(\w+)"/;
}
close $fh;

my $correct = 0;
my $total = 0;

my $re = qr/a/;

for (@english) {
    $total++;
    $correct++ unless /$re/;
}
for (@spanish) {
    $total++;
    $correct++ if /$re/;
}

say "$correct / $total (@{[100*$correct/$total]}%)";

```

# Answer
> 4 votes
# 50 bytes, 90.02% accurate

`(a(d?|is|r|se?)|dor|eis|ese|je|n|[ns]te|os?|res?)$`

For 18,004 out of the 20,000 words in `es_clean.json` and `en_clean.json`, this regex matches iff the input word is Spanish.

---
Tags: code-golf, natural-language, regular-expression
---


title: Find prime gaps

text:
# Question
Title: Find prime gaps
A prime gap is the difference between two consecutive primes. More specifically, if *p* and *q* are primes with *p* \<*q* and *p*+1, *p*+2, ..., \_q\_−1 are not primes, the primes *p* and *q* define a gap of *n* = *q\_−\_p*. The gap is said to be **started** by *p*, and to have **length** *n*.

It is known that arbitrarily large prime gaps exist. That is, given *n* there exists a prime gap of length *n* or larger. However, a prime gap of length exactly *n* may not exist (but a larger one will).

# The challenge

Given a positive integer `n`, output the first prime that starts a gap of length `n` or larger.

As an example, for input `4` the output should be `7`, because 7 and 11 are the first consecutive primes that differ by at least 4 (the previous gaps are 1, from 2 to 3; 2, from 3 to 5; and 2, from 5 to 7). For input `3` the answer should also be `7` (there are no gaps of length 3).

# Additional rules

# Test cases

```
Input -> Output

1        2
2        3
3        7
4        7
6        23
10       113
16       523
17       523
18       523
30       1327
50       19609
100      370261
200      20831323

```

# Answer
# Gaia, 6 bytes

```
zṅọ⊃∆ṇ

```

This is *extremely* inefficient (the `16` test case took over an hour to compute on my machine).

Try it online!

### Explanation

The sequence seems to have the property that **a(n) \<= 2^n**.

```
z       Push 2^input.
 ṅ      Get the first 2^input prime numbers.
  ọ     Get the deltas of the list.
   ⊃∆   Find the index of the first that is greater than or equal to the input.
     ṇ  Push the index-th prime number.

```
> 3 votes

# Answer
# Jelly, ~~10, 9, 8~~ 10 bytes

```
Æn_$:ð1#»2

```

Try it online!

Two bytes saved thanks to @Dennis! (and then added back again due to edge-cases)

Explanation:

```
Æn          #   The next prime after 'P'
  _$        #   Minus 'P'
    :       #   Divided by 'N'
            #
            # This will give a falsy value unless the distance to the next prime is >= N
            #
     ð      # Treat all of that as a single dyad (fucntion with two arguments).
            # We'll call it D(P, N)
            #
      1#    # Find the first 'P' where D(P, input()) is truthy
        »2  # Return the maximum of that result and 2

```
> 9 votes

# Answer
# Mathematica, 30 bytes

```
2//.x_ /;NextPrime@x-x<#:>x+1&

```

Try it online!

# Mathematica, 35 bytes

```
(t=2;While[NextPrime@t-t<#,t++];t)&

```

Try it online!

# Mathematica, 77 bytes

```
Prime@Min@Position[s=Differences@Prime@Range[(r=#)^3+1],#&@@Select[s,#>=r&]]&

```
> 4 votes

# Answer
# Haskell, ~~106 102 93 77 73~~ 72 bytes

This generates an infinite list of primes first, then looks for the prime gaps. The prime list was taken from here. It can probably be shortened, but I haven't figured out how yet:)

Thanks to @BruceForte for -4 bytes and @Zgrab for -1 byte!

```
f n=[x|(y,x)<-zip=<<tail$[n|n<-[2..],all((>0).rem n)[2..n-1]],y-x>=n]!!0

```

Try it online!
> 4 votes

# Answer
# Pyth - 14 bytes

It filters from \[1, inf), filtering by primality(`P_`) and that the next prime filtered from (n, inf), has a different \>= to the input.

```
f&P_T<tQ-fP_Yh

```

Test Suite.
> 3 votes

# Answer
# PowerShell, ~~97~~ ~~96~~ 91 bytes

```
param($n)for($a=$b=2){for(;'1'*++$b-match'^(?!(..+)\1+$)..'){if($b-$a-ge$n){$a;exit}$a=$b}}

```

Try it online!

Takes input `$n`, sets `$a` and `$b` equal to `2`, then enters an infinite `for` loop. Inside, we loop up on `$b` until we get to the next prime. Then we check if `$b-$a` (i.e., the gap) is `-g`reaterthanor`e`qual to `$n`. If it is, we output `$a` and `exit`. Otherwise we set `$a` to be `$b` and increment `$b` and start our next search.

Warning: This is *slow* for large input. In fact, it can't complete the `50` or higher tests within the 60s timeout on TIO. Oh well.
> 3 votes

# Answer
# Husk, ~~13~~ ~~11~~ 10 bytes

```
´ȯ!V≥⁰Ẋ-İp

```

Try it online!

```
´       İp  -- with the primes
 ȯ!         -- get the value at position
      Ẋ-    -- where the difference of the current and next prime
   V≥⁰      -- is greater or equal than the input N

```
> 3 votes

# Answer
# Mathematica, 39 bytes

```
(For[i=2;p=NextPrime,i+#>p@i,i=p@i];i)&
(* or *)
(For[i=1;p=Prime,p@i+++#>p@i,];p[i-1])&

```

### 33 byte version (not valid because it only goes up to the 65535th prime)

```
p=NextPrime;2//.i_/;p@i-i<#:>p@i&

```
> 3 votes

# Answer
# Python 2, ~~96~~ 88 bytes

***\- 8 bytes Thanks to @Maltysen***

```
n,p,r=input(),3,[2]
while p-r[-1]<n:r+=[p]*all(p%i for i in range(2,p));p+=1
print r[-1]

```

Try it online!
> 2 votes

# Answer
# Perl 6, 63 bytes

```
->\d{(grep &is-prime,^∞).rotor(2=>-1).first({-d>=[-] $_})[0]}

```

Try it online!
> 2 votes

# Answer
# R + gmp, 55 bytes

Makes use of the nextprime function from the gmp library

```
s=2;n=scan();while((x=gmp::nextprime(s))-s<n)s=x;cat(s)

```
> 2 votes

# Answer
## Mathematica, 37 bytes

```
gNestWhile[p=NextPrime,2,p@#-#<g&]

```

`Function` with first argument `g`. Starting with `2`, applies the function `p=NextPrime` repeatedly as long as `p@#-#<g&` gives `True` (the gap between the current prime and the next prime is less than `g`).
> 2 votes

# Answer
## C = ~~141~~ 109 bytes ; C++, D = 141 bytes ; C#, Java = 143 bytes

**WARNING** : LOW PERFORMANCE ALGORITHM

This code was not able to calculate the prime gap for `g(200)` within 10 minutes. For `g(100)`, it needed 10 seconds ( C++ version )

C++ and D version :

```
int p(int d){for(int i=2;i<=d/2;++i){if(!(d%i))return 0;}return 1;}int g(int d){int f=2,n=3;while(n-f<d){f=n;do{++n;}while(!p(n));}return f;}

```

C# and Java version :

```
int p(int d){for(int i=2;i<=d/2;++i){if(d%i==0)return 0;}return 1;}int g(int d){int f=2,n=3;while(n-f<d){f=n;do{++n;}while(p(n)==0);}return f;}

```

C version, -32 bytes thanks to ceilingcat :

```
i;p(d){for(i=2;d/2/i;)if(!(d%i++))return 0;return 1;}f;n;g(d){for(f=2,n=3;n-f<d;)for(f=n;!p(++n););return f;}

```

Differences between the C#/Java and C/C++/D version : `!p(n)` \<==\> `p(n)==0`
> 2 votes

# Answer
# Ruby, 61 bytes

```
->g{*r,f=2,3;f+=1while r.find{|n|f%n<1}||r<<f&&g>f-z=r[-2];z}

```

Try it online!
> 2 votes

# Answer
# D, ~~127~~ ~~125~~ 122 bytes

WARNING: LOW PERFORMANCE ALGORITHM!!

```
T p(T)(T d){T r;for(T i=2;i<=d/2;)r=d%i++<1||r;return r;}T g(T)(T d){T f=2,n=3;while(n-f<d){f=n;while(p(++n)){}}return f;}

```

Try it online!

# How?

HatsuPointerKun again, but I'll do the D specific sorcery.

* Template system can infer types `T p(T)(T d)`, and is shorter than C++
* `r=d%i++<1||r`, D specific shenanigans, might work in C/C++, but I don't know.
* `p(++n)`, same as above, not sure if it works in C/C++
* `while(p(++n)){}`, here one sees why D is bad at golfing, one can't use `;` as an empty statement.
> 2 votes

# Answer
# Perl 6, ~~41~~ 37 bytes

```
{+(1...(^$_+*)>>.is-prime eqv!<<^$_)}

```

Try it online!

### Explanation

```
{                                   }  # Block taking n as $_
   1...   # Sequence 1,2,... until
       (^$_+*)  # Range [i,i+n)
              >>.is-prime  # is-prime for each
                          eqv!<<^$_  # Equals (True,False,False,False,...)?
 +(                                )  # Length of sequence

```
> 2 votes

# Answer
# Haskell, 64 bytes

```
f n=until(\p->and[any((<1).mod k)[2..k-1]|k<-[p+1..p+n-1]])(+1)2

```

Try it online!

Count up from `2` looking for a `p` such that `[p+1..p+n-1]` are all composite.

`p` itself will always be prime: otherwise `[p..p+n-1]` is a larger prime gap and we'd have returned `p-1`.
> 2 votes

# Answer
# QBIC, 28 bytes

```
{~µs||~s-r>=:|_Xr\r=s]]s=s+1

```

## Explanation

```
{         DO
~µs||     IF s is prime THEN (note, s starts as 3)
~s-r>=:   IF the gap between s (current prime) and r (prev prime) is big enough
|_Xr      THEN QUIT, printing prev prime r
\r=s      ELSE (gap too small, but s is prime), set r to prime s
]]        END IF x2, leaving us in the WHILE
s=s+1     increment s, retest for primality ...

```
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
∞<ØD¥I@Ïн

```

Try it online or verify all test cases. (Test Suite doesn't contain the last two test cases, because TIO times out for those.)

Since the other question is closed as a dupe of this one, I'm posting my answer here as well.

**Explanation:**

```
∞           # Get an infinite list in the range [1, ...]
 <          # Decrease it by one to make it in the range [0, ...]
  Ø         # Get for each the (0-indexed) n'th prime: [2,3,5,7,11,...]
   D        # Duplicate this list of primes
    ¥       # Get all deltas (difference between each pair): [1,2,2,4,2,...]
     I@     # Check for each if they are larger than or equal to the input
            #  i.e. 4 → [0,0,0,1,0,1,0,1,1,0,...]
       Ï    # Only keep the truthy values of the prime-list
            #  → [23,31,47,53,61,...]
        н   # And keep only the first item (which is output implicitly)
            #  → 23

```
> 1 votes

# Answer
# Java 8, ~~99~~ 92 bytes

```
n->{int a=2,b=3,f,k;for(;b-a<n;)for(f=0,a=b;f<2;)for(f=++b,k=2;k<f;)f=f%k++<1?0:f;return a;}

```

Try it online. (Largest test case is excluded, because it times out in TIO.)

**Explanation:**

```
n->{               // Method with integer as both parameter and return-type
  int a=2,b=3,     //  Prime-pair `a,b`, starting at 2,3
      f,           //  Prime-checker flag `f`, starting uninitialized
      k;           //  Temp integer, starting uninitialized
  for(;b-a         //  Loop as long as the difference between the current pair of primes
          <n;)     //  is smaller than the input
    for(f=0,       //   (Re)set the prime-checker flag to 0
        a=b;       //   Replace `a` with `b`, since we're about to search for the next prime-pair
        f<2;)      //   Inner loop as long as the prime-checker flag is still 0 (or 1)
                   //   (which means the new `b` is not a prime)
      for(f=++b,   //    Increase `b` by 1 first, and set this value to the prime-checker flag
          k=2;     //    Set `k` to 2
          k<f;)    //    Inner loop as long as `k` is still smaller than the prime-checker flag
        f=         //     Change the prime-checker flag to:
          f%k++<1? //      If the prime-checker flag is divisible by `k`
           0       //       Set the prime-checker flag to 0
          :        //      Else:
           f;      //       Leave it unchanged
                   //    (If any integer `k` in the range [2, `b`) can evenly divide `b`,
                   //     the prime-checker flag becomes 0 and the loop stops)
  return a;}       //  And finally after all the nested loops, return `a` as result

```
> 1 votes

# Answer
# Tidy, 33 bytes

```
{x:({v:⊟v<=-x}↦primes+2)@0@0}

```

Try it online!

Or, 28 chars/34 bytes: `{x:({v:⊟v≤-x}↦primes+2)@0@0}`

I'll explain this using an equivvalent, ASCII equivalent:

```
{x:({v:(-)over v<=-x}from primes+2)@0@0}
{x:                                    }    lambda w/ parameter `x`
                          primes+2          overlapping pairs of primes
                                            [[2, 3], [3, 5], [5, 7], ...]
    {v:             }from                   select prime pairs `v = [a, b]`...
       (-)over v                            ...where `a` - `b`...
                <=-x                        is <= `x`
   (                              )@0@0     select the first element of the first pair

```
> 1 votes

# Answer
# APL(NARS), 36 char, 72 bytes

```
∇r←h w;k
r←2
→0×⍳w≤r-⍨k←1πr⋄r←k⋄→2
∇

```

1π is the function "next prime"; test:

```
  h¨1 2 3 4 6 10 16 17 18 30 50 100 200
2 3 7 7 23 113 523 523 523 1327 19609 370261 20831323

```
> 1 votes

# Answer
# Japt, 14 bytes

```
@§XnÈj}aX+j}a2

```

Try it or run all test cases (except `200` \- seriously, don't even try it! If you want to verify that `200` returns the correct result, you can increase the starting value of `2` at the end to something closer to the expected output.)

```
@§XnÈj}aX+j}a2     :Implicit input of integer U
@                  :Function taking an integer X as argument
 §                 :  Is U <= ...
  Xn               :  Subtract X from
    È              :    Function taking an integer as input
     j             :      Is prime?
      }            :    End function
       a           :    Get the first integer that returns true when passed through that function starting at
        X+j        :      X plus is X prime
           }       :End function
            a2     :Get the first integer that returns true when passed through that function starting at 2

```
> 1 votes

---
Tags: code-golf, math, number, arithmetic, number-theory
---


title: When's my weekend finally here?

text:
# Question
Title: When's my weekend finally here?
I like my job, but sometimes it can get a bit tedious and boring. As motivation, I want to know how many hours of work are left before I finally get my two days of weekend and relaxation.

* I work **every day** from Monday to Friday, totalling **38.5 hours**, starting at **9am** and ending at **6pm**.
* Every day - except Friday - I get a lunch break from **1:00pm** to **1:30pm**. On Fridays I do not get a lunch break, but get off at **1:30pm** instead. Note that these lunch breaks do not add to work time.
* If I check the time during the weekend (Friday after 1:30pm, Saturday or Sunday), I don't want to know about next week yet - it should tell me that **zero** hours are remaining instead.

---

Given an input date, calculate the number of work hours remaining until the weekend is here (on Friday at 1:30pm). You can assume that the input hours will range from **0** to **23**, and the minutes will only ever be **0** or **30**, which means that you will not have to calculate fractions other than **.5**.

## Rules

* This is , the shortest answer, in bytes, wins.
* As usual, standard loopholes are forbidden.
* **Input** may be received in any reasonable *datetime format*. Timestamps, date strings, date objects, et cetera are all allowed. You can also directly take the input as the day of the week (indexed with Sunday as 0), the hours and the minutes.
* **Output** may be written directly to `stdout` or returned as a string or numeric. Printing with trailing newlines is allowed.

## Test Cases

```
Fri May 21 2021 09:00:00 -> 4.5
Sun Jul 25 2021 16:00:00 -> 0
Mon Aug 23 2021 04:00:00 -> 38.5
Sat Nov 06 2021 08:00:00 -> 0
Thu Oct 14 2021 10:30:00 -> 11.5
Tue Dec 07 2021 14:30:00 -> 25
Fri Jan 21 2022 00:00:00 -> 4.5

```

Formatted as full date strings for convencience - you do not need to use *this* format, check the input rules.

# Answer
> 4 votes
# Python 2, 108 bytes

```
d,h,m=input()
t=0
while((h,m)<(13,1))+4>d%7:t+=8<h<18>13!=h*-~m*(d!=4);h+=m>0;m=30-m;d+=h/24;h%=24
print.5*t

```

Try it online!

-2 bytes thanks to EliteDaMyth
-5 bytes thanks to Arnauld
-5 bytes thanks to ovs

Monday = 0, Sunday = 6

# Answer
> 2 votes
# JavaScript (ES6),  ~~84 79 78~~  73 bytes

*Saved 1 byte thanks to @l4m2*

Expects `(d,h,m)` where `d` is the day of the week as described in the challenge.

```
(d,h,m)=>d%6?(g=k=>k--?g(k)-(k/18&(d-5?k!=26:k<27)):94-17*d)(h*2+!!m)/2:0

```

Try it online!

### Commented

```
(d, h, m) =>        // d = day of week, h = hours, m = minutes
d % 6 ?             // if this is not the week-end:
  ( g = k =>        //   g is a recursive function that iterates over
                    //   the whole day with a 30 minutes granularity
    k-- ?           //     decrement k; if it was not 0:
      g(k) -        //       do a recursive call and decrement the final
      (             //       result if:
        k / 18 &    //         it's between 9 AM and 5.30 PM
                    //         (i.e. floor(k / 18) = 1)
        (           //         and:
          d - 5 ?   //           if this is not Friday:
            k != 26 //             it's not 1 PM
          :         //           else:
            k < 27  //             it's less than 1.30 PM
        )           //
      )             //
    :               //     else (end of recursion):
      94 - 17 * d   //       add 38.5 hours minus 8.5 hours per full day,
                    //       which gives 77 - 17 * (d - 1) in half hours
  )(h * 2 + !!m)    //   initial call with h and m converted to half hours
  / 2               //   half the result
:                   // else:
  0                 //   just return 0

```

# Answer
> 1 votes
# Charcoal, ~~53~~ ~~52~~ ~~49~~ 47 bytes

```
Ｉ⊘Σ✂”~∨‽lＣ⎚À›t⟧κⅉ←eδQ﹪GÀ*¡_∧⌊⮌θμ⟧>”⁺×⁴⁸⊖Ｎ⁺⊗Ｎ¬¬Ｎ

```

Try it online! Link is to verbose version of code. Explanation: I couldn't find a better way of expressing the working hours than a giant compressed lookup table (especially now I've golfed 10% off).

```
    ”...”               Compressed lookup table of half hours
   ✂                    Sliced starting at position
              Ｎ         Input day of week
             ⊖          Decremented
          ×⁴⁸           Multiplied by 48 (half hours in day)
         ⁺              Plus
                 Ｎ      Input hour of day
                ⊗       Doubled (convert to half hours)
               ⁺        Plus
                    Ｎ   Input minute of day
                  ¬¬    Is not zero
  Σ                      Count half hours left to work
 ⊘                      Divide by 2 (convert to hours)
Ｉ                       Cast to string
                        Implicitly print

```

Edit: Saved 1 byte by using `Sum()` instead of `Count(..., "1")`, allowing me to save a further 3 bytes by using `Sum(Slice(...))` instead of `Minus(77, Sum(CycleChop(...)))`, allowing me to save a further 2 bytes by removing the now unnecessary `Modulo(..., 7)`.

# Answer
> 1 votes
# , 59 56 bytes

```
1-:@#.,@(30|."1(|:48{.0(8})18 4$1),9$1)}.~30%~7 24 60&#.

```

Try it online!

Takes input as `day hour minute`.

## the idea

* View the entire week as series of 30 minute chunks, where `1` represents work time and `0` represents free time. The five relevant week days look like:

```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```
* Find how many 30 minute chunks away from Sunday midnight the input is.
* Delete that many elements.
* Sum the remaining ones, and divide by 2.

## J details

* `30%~7 24 60&#.` Converts to the input to minutes, then divides by 30.
* `,@(30|."1(|:48{.0(8})18 4$1),9$1)` Returns the grid above, but flattened.
* `1-:@#.` Sum and divide by 2.

# Answer
> 0 votes
# Perl 5, 84 bytes

```
sub f{$_=pop;$_>51300||$_<1e4?0:(/(09|1[0-7])..$/-/[1-4]1300/)*.5+f($_+30+40*/3.$/)}

```

Try it online!

The function takes one numeric argument: `day*10000 + hour*100 + minute` where Monday is 1, Tuesday is 2, ... and Sunday is 0 (if Sunday=7 is allowed 8 bytes can be saved). Example input: 51300 = Friday 13:00.

# Answer
> 0 votes
# JavaScript (Node.js), 95 bytes

```
f=d=>(h=d.getHours(),d+0)[0]!='S'&&(h>8&h<13+5*(d+0>'G')^/13:0/.test(d))/2+f(new Date(+d+18e5))

```

Try it online!

# JavaScript (Node.js), 75 bytes from Arnauld's

```
(d,h,m)=>d%6&&(g=k=>k--?g(k)-(k>17&k<(d-5?36:26)^k==26):94-17*d)(h*2+!!m)/2

```

Try it online!

---
Tags: code-golf, date
---


title: Compiling English for your Boss

text:
# Question
Title: Compiling English for your Boss
Your boss has recently learned of this interesting programming language called English. He has had this "revolutionary" idea, he wants to code with you to double code production rates! Since he is not a tech savvy, he wants you to write a compiler for it so that he can code too!

Now, you are an evil lazy programmer and obviously will not write a program to compile this ridiculously complex language. Instead, you are going to make sure there is always an error in your boss's code, so that he never gets to the actual compilation and is stuck fixing grammar errors instead of coding.

The challenge is to write a program that can be run from the terminal, and accepts a file path as an argument. The program has to:

1. modify the file input by introducing a typo.
2. Pretend to fail compilation due to encountering the typo you introduced.
3. Running the program on copies of the same file should not introduce the same typo twice in a row.

To illustrate the challenge, running your program on this file:

```
Take an array as input.
Sort the array.
Output the array.

```

should output something along the lines of

```
Error on line 1:
'Take an arqay as input.'
         ^
arqay is not a valid identifier.

```

and the file that you told the program to compile should now look like:

```
Take an arqay as input.
Sort the array.
Output the array.

```

Here are some more details on the specs of the program:

Your program is allowed to assume that swapping any character in the program your boss inputs for a different random character will cause a grammar error. Your program should not use non alphabetical characters to create errors in your bosses code. Your boss would never use a number or symbol, and he would find out that something is afoot. Your program should only introduce errors to the words in your boss's program. Do not change the spaces in the sentences, or the punctuation. Your program should not alter the case of the program your boss tries to compile, meaning errors like `arQay` are invalid. This prevents errors like `take` instead of `Take` happening, or `Array` instead of `array`. Your program should output the error by first stating what line the error is at:

```
Error on line <insert line number here>:

```

It should then print out the line with the error inside `'` symbols. On the next line it should place a `^` symbol under the *word* with the error, and finally it should have some text describing the error (this part is up to you, you can say whatever you want there as long as it describes an error).

You can assume that the input file exists and it is not empty. You can also assume the input file has no grammatical errors before you add one.

Bonuses:

-60 bytes if the errors your code introduces are not completely random, but typo-based as in this question.

-60 bytes for at least 5 different error messages, randomly alternating.

-60 bytes if your program has a 1 in 100 chance or less to output some demotivational message to your boss.

**EDIT: The byte count of the messages do not count towards your score.** (Thanks to Martin Büttner for this good idea)

This is code-golf, shortest byte count wins. Please do not golf the error message content, your boss wont be happy if he can't understand the error messages, and will ask you to fix them for him.

# Answer
> 3 votes
# TI-BASIC, 77 - 34 (error text) = 43

*In case he wants to do in on his TI-83/84 calculator ;)*

As standard for functions, file string should be in `Ans` so it can return and display the output.

```
Ans->Str1:If 1=inString(Ans,"A
Then:"B
Else:"A
End:Disp "ERROR ON LINE 1","'"+Ans+sub(Str1,2,-1+length(Str1))+"'"," ^ INVALID

```

Note that many tokens are one byte.

# Answer
> 2 votes
# JavaScript, ~~484~~ 458 bytes

```
F=process.argv[2]
C=console.log
r=require('fs')
l=r.readFileSync(F,'utf-8').replace(/\r/g,'').split`
`
S=b=>b[H=Math.random()*b.length|0]
L=S(l)
y=H
C(`Error on line ${y+1}:`);
while(/[^a-z]/.test(S(R=L.split` `)));
Y=H
R[Y]=R[Y].replace(t=S(R[Y]),(J=_=>(Z=S('abcdefghijklmnopqrstuvwxyz'))==t?J():Z)(t))
j=R.join` `
C(`'${j}'`)
C(' '.repeat(1+R.reduce((a,e,i)=>a+=i<Y&&e.length,Y))+'^')
C('Unexpected '+R[Y])
r.writeFileSync(F,l.map((e,i)=>i==y?j:e).join`
`)

```

No TIO link, but it takes in a path like `./test.txt` as input via command line arguments and outputs the error like so:

```
Error on line 1:
'Take an mrray as input.'
         ^
Unexpected mrray

```

I'm a little unsure about how to count the error message length. Is it the length of `Unexpected`  (with the space)?

Anyway, this took a while. Basically selects a line at random, then a word at random, replaces a random letter of that word with another random letter that is not the same, then outputs line number, modified line, then the caret after a number of spaces. Then outputs `Unexpected <word>` where is the aforementioned word.

Then uses `writeFileSync` to replace the content.

# Answer
> 1 votes
# Python 3, ~~245~~ 239 bytes

```
import sys,time
t=time.time
p=sys.argv[1]
f=open(p).read()
a=f[0]
f=chr(ord(a)+int(-t()if a in"yzYZ"else t())%2+1)+f[1:]
open(p,"w").write(f)
n="\n"
s=f.split
print(f"Error on line 1:\n'{s(n)[0]}'\n ^\n{s()[0]} is not a valid identifier.")

```

Slightly bending the rules in a few ways:

* It always makes the error on the first character, which it assumes to be a valid character, since otherwise it would be an English syntax error
* It only ever outputs two different typos for any given input: for A-X it shifts either +1 or +2, for Y-Z it shifts either -1 or -2.
* It uses `int(time.time())` as its PRNG, so running the program several times within a second will output the same typo.

Output on the sample input:

```
Error on line 1:
'Uake an array as input.'
 ^
Uake is not a valid identifier.

```

I'm unsure about how long the error message is, anyone have any ideas?

---
Tags: code-golf
---


title: How to convert HEX2 to RGBA?

text:
# Question
Title: How to convert HEX2 to RGBA?
The world of art is full of colour, but the world of the network is even fuller than the world of art of diferent colours and it's renderings. That's why we need to know how to convert one type of colour format to another.

### The challenge is self-evident:

Write a program / function than converts an given HEX code (`#00ff0080`, for instance) to RGBA (like `rgba(0, 255, 0, 0.5)`).

# Rules:

* External libraries/ built-ins for converting HEX to RGBA are disallowed. However, jQuery and syntax replacers like that are acceptable.
* Standard Input/Output rules apply.
* Format of the alpha can be between (1 == 100%) or the other (100 == 100%) that's not really important.
* The output *is flexible*, as long as it returns the 4 converted values (as a String, Array, List, your choice).
* You may choose to take the input without the `#` in the beginning. Hence, you can take input as either `#RRGGBBAA` or `RRGGBBAA`. You can assume that the hex code (excluding the `#`) will always be 8 characters long.
* You should divide all the values by 255, including the alpha. The minimum decimal precision (for the alpha will be 2 decimal places).

# Test Cases

```
Input:  00ff0080
Output: 0, 255, 0, 0.5

```

# Scoring

, the code with the least amount of bytes wins.

# Answer
> 5 votes
# JavaScript (ES6), ~~73~~ ~~54~~ 50 bytes

(Saved some bytes thanks to @LeakyNun, the edited challenge, and @CraigAyre.)

```
s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))

```

```
let f=

s=>s.match(/../g).map((c,i)=>('0x'+c)/(i-3?1:255))

console.log(f('00ff0080'));
```

# Answer
> 4 votes
# Japt v2.0a0, ~~13~~ 10 bytes

Takes input as a string, without the leading `#`. Outputs the rgba value as an array.

```
ò mnG o÷#ÿ

```

Try it

```
ò mnG o÷#ÿ     :Implicit input of string
ò              :Partitions of length 2
  m            :Map
   n           :  Convert to integer from base
    G          :  16
      o        :Modify last element
       ÷       :  Divide by
        #ÿ     :  255

```

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
2ôH`255/)

```

Try it online!

At least we have supporters like Emigna to often use some common sense...(that's what you get for golfing all day and then you start producing stuff like `2ô16öRć255/¸ìR` ಠ\_ಠ)

# Answer
> 3 votes
# PHP, 63 bytes

Output as array

```
$h=array_map(hexdec,str_split($argn,2));$h[3]/=255;print_r($h);

```

Try it online!

# PHP, 80 bytes

Output as rgba value, Input without `#`

```
$h=array_map(hexdec,str_split($argn,2));$h[3]/=255;echo"rgba(",join(",",$h),")";

```

Try it online!

# PHP, 88 bytes

Output as rgba value, Input with `#`

```
for(;$i<7;)$h[]=hexdec($argn[++$i].$argn[++$i]);$h[3]/=255;echo"rgba(",join(",",$h),")";

```

Try it online!

# Answer
> 3 votes
# C (gcc), 139 bytes

```
C(x){x=x>57?x-87:x-48;}
#define Z C(h[i])*16+C(h[++i]))
i;f(char*h){printf("rgba(");for(i=0;i<6;i++)printf("%i, ",Z;printf("%g)",(Z/256.);}

```

Try it online!

My other attempt clocked in at 145 bytes. I'm not much of a C golfer, so this could probably be shorter.

# Answer
> 3 votes
# Vim, 46 bytes

```
:s/../$((16#&)) /g␊iecho ␛$hhi*100/255␛:w !sh␊

```

Takes input without the `#` and returns by printing on the screen.

# Answer
> 2 votes
# Jelly, ~~15~~ 14 bytes

```
Øhi$€’s2ḅ⁴÷4¦⁹

```

Try it online!

**How it Works**

```
Øhi$€’s2ḅ⁴÷4¦⁹ - main link, takes input without # and all lowercase
   $€             - to each input character:
  i               - return its 1-based index in
Øh                - the string "0123456789abcdef"
     ’            - decrement (otherwise 0 is mapped to 1 and f to 16)
      s2          - split the characters into groups of two
        ḅ⁴        - convert from base 16 to decimal
           4¦     - on the fourth element:
          ÷       - divide by
             ⁹    - 256

```

*-1 byte thanks to @EricTheOutgolfer*

# Answer
> 2 votes
# PHP, 72 bytes

Jörg´s array output version is unbeatable; but there are other options:

```
<?=($a=hexdec($argn))>>24,",",255&$a>>16,",",255&$a>>8,",",(255&$a)>256;

```

Run as pipe with `-F`. `#` does not matter, plain csv output

or **73 bytes** (run with `-R`):

```
for($a=hexdec($argn);$i++<4;)echo(255&$a>>32-8*$i)/($i<4?:256),","[$i>3];

```

**74 bytes** with the spaces:

```
<?=($a=hexdec($argn))>>24,$c=", ",255&$a>>16,$c,255&$a>>8,$c,(255&$a)>256;

```

not so plain, **81 bytes**:

```
rgba(<?=($a=hexdec($argn))>>24,$c=", ",255&$a>>16,$c,255&$a>>8,$c,(255&$a)/256?>)

```

# Answer
> 2 votes
# Stacked, ~~47~~ ~~45~~ 41 bytes

```
[2#<$unhexmap(1::256)/', '#`'rgba(@id)'!]

```

Try it online!

# Answer
> 2 votes
# Excel, 99 bytes

```
=HEX2DEC(LEFT(A1,2))&","&HEX2DEC(MID(A1,3,2))&","&HEX2DEC(MID(A1,5,2))&","&HEX2DEC(RIGHT(A1,2))/256

```

# Answer
> 2 votes
# SmileBASIC, 50 bytes

```
INPUT H$RGBREAD VAL("&H"+H$)OUT R,G,B,A?R,G,B,A/#L

```

The hexadecimal string is converted to a number using VAL(), then RGBREAD extracts each byte. #L is a constant with the value 256.

RGBREAD is designed to extract the channels from an ARGB color, but really it just splits a 4 byte integer into 4 separate bytes, so the order doesn't matter.

# Answer
> 2 votes
# PowerShell Core, ~~73~~ 62 bytes

```
$args-split'(..)'-ne''|%{"0x$_"/(1,1,1,256)[$i++]}|% *g "0.##"

```

-11 bytes thanks to Mazzy

Try it online!

# Answer
> 1 votes
## JS ES2015, 84 bytes

```
$=>{a=[1,3,5,7].map(b=>eval("0x"+$.substr(b,2)));a[3]=(a[3]/256);return a.join(",")}

```

this is a function. Run it using

```
( CODE )("#00ff0080")

```

# Answer
> 1 votes
# q/kdb+, 43 bytes

**Solution:**

```
{(16 sv'(.Q.n,6#.Q.a)?/:2 cut x)%1 1 1 256}

```

**Example:**

```
q){(16 sv'(.Q.n,6#.Q.a)?/:2 cut x)%1 1 1 256}"00ff0080"
0 255 0 0.5

```

**Explanation:**

```
{                                         } / anonymous lambda function
                        2 cut x             / split input into 2-char length lists
                     ?/:                    / returns index where (each-right) item is found in 'the list'
        (           )                       / 'the list'
              6#.Q.a                        / Q.a is lowercase alphabet, 6# takes first 6 chars
         .Q.n,                              / Q.n is "012..89", so prepend this onto the "abcdef"
  16 sv'                                    / converts each index from base 16 to base 10
 (                            )%1 1 1 256   / divide this output by 1,1,1,256 to get alpha in 0..1 range

```

# Answer
> 1 votes
# APL (Dyalog), 24 bytes

Requires `⎕IO←0` which is default on many systems. Prompts for input as uppercase without `#`.

```
256÷⍨@3⊢16⊥⍉4 2⍴⍞⍳⍨⎕D,⎕A

```

Try it online!

`⎕D,⎕A`**D**igits followed by **A**lphabet

`⍞⍳⍨` prompt for text input (mnemonic: console with quote) and find the **ɩ**ndex of each letter in that

`4 2⍴`**r**eshape as four row two column matrix

transpose (because base conversion works columnwise)

`16⊥` evaluate as **base** sixteen

yield (serves to separate 3 and 16)

`256÷⍨@3` divide the 4th element by 256

# Answer
> 1 votes
# Yabasic, 96 bytes

Yet another answer; Takes input as string and outputs to the console.

```
Input""a$
For i=1To 7Step 2
?Dec(Mid$(a$,i,2))/(j+1);
If i=5Then j=255Fi
If i<7Then?", ";Fi
Next

```

Try it online!

# Answer
> 1 votes
# Excel VBA, 90 bytes

An anonymous VBE immediate window function that takes input from the range `[A1]` and outputs to the VBE immediate window.

```
For i=1To 7Step 2:[B1]=i:?[Hex2Dec(Mid(A1,B1,2))]/IIf(i=7,256,1)&""+IIf(i<7,", ","");:Next

```

# Answer
> 1 votes
# Batch, 150 bytes

```
@for /f "tokens=2-5 delims=. " %%a in ('ping/n 1 0x%1^|find "h"')do @echo/%%a,%%b,%%c&set/ay=%%d*100/255@set y=0.%y%@if %y%==0.100 set y=1@echo/%y%

```

# Answer
> 0 votes
# Perl 6, 42 bytes

```
{m:g/../.map({:16(~$_)}) »/«(1,1,1,255)}

```

Try it online!

# Answer
> 0 votes
# Python 3, 62 bytes

```
lambda h:[int(h[x:x+2],16)for x in(0,2,4)]+[int(h[6:],16)/255]

```

Try it online!

# Answer
> 0 votes
# Python 2, 54 bytes

```
lambda h:[int(h[i-2:i],16)/2.**(8&i)for i in(2,4,6,8)]

```

Try it online!

---
Tags: code-golf, base-conversion, conversion, hexadecimal, color
---