title: Unfold in all directions

text:
# Question
Title: Unfold in all directions
### Input:

A string

### Output:

1) First we take remove character at the end of the input-string until we are left with a length that is a square (i.e. 1, 4, 9, 16, 25, 36, etc.)
So `abcdefghijklmnopqrstuvwxyz` (length 26) becomes `abcdefghijklmnopqrstuvwxy` (length 25).

2) Then we put this in a square, one line at a time, left to right:

```
abcde
fghij
klmno
pqrst
uvwxy

```

3) We fold it in all four directions, like this (we keep unfolding until the outer folded 'block' has no inner characters to unfold anymore):

```
      m
     qrs
     l n
     ghi
    abcde
 ihgf   jihg
mn lk   on lm
 srqp   tsrq
    uvwxy
     qrs
     l n
     ghi
      m

```

Some things to note, when we fold outward, we basically mirror like this (numbers added as clarification, which represents the 'indexes' in these examples):

When we fold out the left side:

```
 123    to:   321 123
fghij         ihgf   j

```

When we fold the right side:

```
 123    to:    123 321
fghij         f   jihg

```

When we fold upwards:

```
            3q
            2l
            1g
  b   to:    b
 1g         1
 2l         2
 3q         3
  v          v

```

When we fold downwards:

```
 b          b
1g         1
2l         2
3q         3
 v   to:    v
           3q
           2l
           1g

```

### Challenge rules:

* You can assume the input will always have at least 1 character (which will also be the output).
* Output format is flexible, so you can print to STDOUT or STDERR; return as string-array/list or character 2D-array; single string with new-lines; etc.
* The input will only contain alphanumeric characters (`a-zA-Z0-9`)
* You can also use a non-alphanumeric character to fill up the spaces in and/or around the ASCII-art output, like a dot `.`.
* Trailing spaces and a single trailing new-line are optional.
* We continue unfolding until the outer folded 'block' has no more centers to unfold.

### General rules:

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

### Test cases:

```
Input: abcdefghijklmnopqrstuvwxy
Output:
      m
     qrs
     l n
     ghi
    abcde
 ihgf   jihg
mn lk   on lm
 srqp   tsrq
    uvwxy
     qrs
     l n
     ghi
      m

Input: A
Ouput:
A

Input: ThisIsATest
Output:
  I
 Thi
Is sI
 ATe
  I

Input: HowAboutAVeryLongExampleWhichIsAlsoAnEvenSquareInsteadOfOddOneAndExceeds64Chars
Output:

               An
               ch
              xamp
              i  I
              o  E
              quar
             steadO
             S    e
             s    v
             h    s
             E    l
             VeryLo
            HowAbout
      oLyreVA      noLyreV
  xampl    Eg      el    Examp
hci  Is    hW      As    hi  Ihc
nAo  Ev    sl      ev    so  EnA
  quare    Sn      Ie    Squar
      Odaetsn      fOdaets
            OddOneAn
             steadO
             S    e
             s    v
             h    s
             E    l
             VeryLo
              xamp
              i  I
              o  E
              quar
               An
               ch

Input: Lenght7
Output:
Le
ng

Input: abc
Output:
a

```

# Answer
> 6 votes
# SOGL V0.12, 75 bytes

```
l√u²m√lH»{ā;l⁾:A∫Ba{bIwFIWhFbž;FIbI@ž}};}¹K⁴{ē2\⌡±e{@Κ};⁴┼┼};0E{ē2\⌡№:h++}╚

```

Try it Here!

This expects the input on the stack, so for ease-of-use I added `,` at the start. That can cause issues if the input contains only numbers so here is a a test-suite for that.

70 bytes `√lH»{ā;l⁾:A∫Ba{bIwFIWhFbž;FIbI@ž}};}¹K⁴{ē2\⌡±e{@Κ};⁴┼┼};0E{ē2\⌡№:h++}╚` works too, but as I only now implemented on strings and the documentation didn't mention that it would floor the length I won't count it.

Explanation:

```
creating a square from the input

l       get the length of the input
 √      get its square root
  u     floor that
   ²    square it
    m   mold the input to that length
     √  convert it to a square

creating the unfoldings of the square - the idea is to cut out the inner squares to a new array

lH»{                              } (length-1)//2 times do
    ā;                                push an empty array below ToS
      l⁾                              push ToS.length - 2 (ToS here is the square or the previous unfolding)
        :A                            save a copy of that in the variable A
          ∫B                    }     repeat that amount of times, saving iteration on B - cutting the inner square to the empty array
            a{                 }        variable A times do
              bIw                         get the b+1th row of the previous unfolding
                 FIW                      get the (current loops iteration + 1)th character of that
                    h                     swap the 2 items below ToS - so the stack now is [..., prevUnfolding, newArray, character]
                     Fbž                  at [current loops iteration; b] insert that character in the array
                        ;                 swap the top 2 items - the stack now is [..., newArray, prevUnfolding]
                         FIbI@ž           at [current loops iteration+1; b+1] insert a space
                                 ;    get the now not empty array ontop of the stack

add the horizontal unfoldings

¹                    wrap the stack in an array
 K                   push the 1st item of that, which will function as the canvas
  ⁴{              }  iterate over a copy of the remaining items
    ē2\⌡               repeat (e++ divides by 2) times (default for the variable E is the input, which defaults to 0)
        ±                reverse the array horizontally
         e{  }         repeat e times
           @Κ            add a space before ToS
              ;⁴┼┼     add that horizontally before and after the canvas

add the veertical unfoldings

;                get the copy of the foldings above the canvas
 0E              reset the variable E to 0
   {         }   iterate the copy of the foldings
    ē2\⌡           repeat (e++ divides by 2) times (default for the variable E is the input, which defaults to 0)
        №            reverse the array vertically
         :h++      add that vertically before and after the canvas
              ╚  center the canvas vertically

```

# Answer
> 5 votes
# Charcoal, ~~120~~ 109 bytes

```
ＡＩ§⪪ＩＸＬθ⁰·⁵.⁰ηＦη⊞υ✂θ×ιηＦ⁴«ＡυεＪ⁰¦⁰Ｆ÷⁺¹η²«Ｆ⁴«Ｆ⁻η⁺κκ§§εκ⁺μκ↷Ａ⮌ＥεＥε§ξνε¶»Ａ⎇﹪ι²Ｅε⮌λ⮌εεＡ⎇‹ι²⁻⁺²⁺κκη⁻η⁺κκκ¿﹪ι²Ｍκ¹Ｍ¹κ

```

Try it online! Note that  has since been changed to  and the link reflects this. Explanation:

```
       θ          Input string
      Ｌ           Length
     Ｘ  ⁰·⁵       Raise to the power 0.5
    Ｉ             Cast to string
   ⪪       .      Split on the decimal point
  §         ⁰     Take the first element (integer part)
 Ｉ                Cast to integer
Ａ            η    Assign to h

```

Calculates `h = int(sqrt(len(q)))`. (`Floor` was yet to be implemented...)

```
Ｆη⊞υ✂θ×ιη

```

Extracts the `h` slices of length `h` from the input. (Actually I don't bother truncating the slices to length `h`.) I use a `for` loop rather than a `Map` because I need to `Assign` the result of the `Map` somewhere and this is nontrivial when dealing with a `Slice`.

```
Ｆ⁴«

```

The unfolding happens 4 times, once for each direction (down, right, up, left as coded). The loop variable for this loop is `i`.

```
   Ａυε

```

Take a copy of the sliced string.

```
   Ｊ⁰¦⁰

```

Jump back to the origin of the canvas so that each unfold starts with the `h`-by-`h` square in the same place.

```
   Ｆ÷⁺¹η²«

```

Repeat `(h+1)/2` times; once for each unfold, plus once for the original square. The loop variable for this loop is `k`.

```
          Ｆ⁴«

```

Repeat 4 times, once for each side of the unfolded square. (I don't use the loop variable `l`.)

```
             Ｆ⁻η⁺κκ         Loop h-2k times, loop variable `m`
                    §εκ     Take the `k`th row
                   §   ⁺μκ  Take the `k+m`th column
                            Implicitly print the character

```

Print one side of the unfolded square. Since this is the `k`th unfold, the square's side is `h-2k`, and takes characters `k` away from the edge of the original square.

Pivot ready to print the next side of the square.

```
               Ｅε       Map over the array (element `m`, index `n`)
                 Ｅε     Map over the array (element `x`, index `p`)
                   §ξν  Take the `n`th element of `x`
              ⮌         Reverse
             Ａ        ε Replace the array with the result

```

Rotate the sliced string. (Yes, that's a `ξ`. I don't get to use it often!) `Ｅη` would also work for the outer `Map`. The rotation also has the convenient side-effect of truncating the array's width to `h`.

```
             ¶»

```

After printing the side, the cursor moves off the edge of the square. Printing one character fewer fails for squares of side 1 and is less golfy anyway. Having previously pivoted, printing a newline conveniently moves the cursor back to the corner.

```
            ﹪ι²         Take `i` modulo 2
           ⎇            Choose either
                   ⮌ε   Reverse the array
               Ｅε       Map over the array (element `l`, index `m`)
                 ⮌λ     Reverse each element
          Ａ          ε  Replace the array with the result

```

Flip the square vertically or horizontally as appropriate.

```
           ⎇‹ι²                 If `i` < 2
                  ⁺κκ           Double `k`
                ⁺²              Add 2
               ⁻     η          Subtract `h`
                        ⁺κκ     Else double `k`
                      ⁻η        Subtract from `h`
          ≔                κ    Assign back to `k`.

```

Calculate the displacement to the next unfold.

```
           ﹪ι²          Take `i` modulo 2
          ¿             If not zero
              Ｍκ¹       `k` across and 1 down
                 Ｍ¹κ    Else 1 across and `k` down

```

Move horizontally or vertically to the next unfold as appropriate.

Here's a link to the 97-byte version obtained by making use of all the latest Charcoal features including `Floor`: Try it online! Link is to verbose version of code.

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


title: Quining a Pristine World

text:
# Question
Title: Quining a Pristine World
This challenge is based off of Helka Homba's question Programming a Pristine World. From that question, the definition of a pristine program is:

> Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where `1 <= N < program length`.
>
> For example, the three character Python 2 program
>
> ```
> `8`
>
> ```
>
> is a pristine program <sup>(thanks, Sp)</sup> because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
>
> ```
> 8`
> ``
> `8
>
> ```
>
> and also all the programs resulting from removing substrings of length 2 cause errors:
>
> ```
> `
> `
>
> ```
>
> If, for example, ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error.
>
> **Notes:**
>
> * Compiler warnings do not count as errors.
> * The erroring subprograms can take input or give output or do anything else as long as they error no matter what eventually.

Your task is to create a program of non-zero length that prints its own source code exactly, follows the rules for a proper quine, and is pristine.

Shortest answer in bytes for each language wins.

# Answer
> 6 votes
# Haskell, 132 bytes

```
q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"q x=if length x==132then putStr x else fail[];main=q$(++)<*>show$"

```

Try it online!

This is an extension of the quine

```
main=putStr$(++)<*>show$"main=putStr$(++)<*>show$"

```

which works by concatenating the data string with a quoted version (by using `show`) of itself and printing the result. However, this is not pristine as any characters in the data string can be removed without failing and also the `$(++)<*>show$` or `(++)<*>` part could be dropped without the program breaking.

To fix this, a custom print function `q` is defined which checks the length of the given string and calls `fail` if it's shorter than 132. This catches the removing of any sequence from the data string and also the removals of `$(++)<*>show$` or `(++)<*>`, as in both cases the resulting string passed to `q` is shorter.

In `q` the number `132` could be shortened to `1`, `13`, `32` or `2`, but in each case again `fail` is called.

As far as I can tell, the removal of any other substring causes either an syntax or type error, so the program does not even compile in the first place. (Haskell's strict type system comes in handy here.)

**Edit:** Thanks to Ørjan Johansen and Shelvacu for pointing out a flaws!

# Answer
> 4 votes
# Python 3, 113 bytes

```
for[]in{113:[]}[open(1,"w").write((lambda s:s%s)('for[]in{113:[]}[open(1,"w").write((lambda s:s%%s)(%r))]:a'))]:a

```

Try it online!

### How it works

We can’t easily use multiple statements since the second one could be deleted, so we start with a single-expression quine:

```
print((lambda s:s%s)('print((lambda s:s%%s)(%r))'))

```

To protect it against substring deletions, we use `open(1,"w").write` instead of `print`. In Python 3, `write` returns the number of written characters, which we will verify is `113` to ensure that no part of the string was deleted. We do this by looking up the return value in the dictionary `{113:[]}`, and looping over the result with `for[]in…:a`, which will fail if we didn’t get an empty iterable or if the `for` statement is deleted.

# Answer
> 4 votes
# Standard ML (MLton), ~~204~~ ~~182~~ 189 bytes

```
val()=hd[(fn s=>let val$ =s^"\""^String.toString s^"\"]"val(189,%)=(size$,$)in print%end)"val()=hd[(fn s=>let val$ =s^\"\\\"\"^String.toString s^\"\\\")\"val(189,%)=(size$,$)in print%end)"]

```

Try it online!

For MLton, full SML programs are either expressions delimited and terminated by `;` (e.g. `print"Hello";print"World";`) or declarations with the `var` and `fun` keywords (e.g. `var _=print"Hello"var _=print"World"`) where `_` is a wild card which could also be replaced by any variable name.

The first option is useless for pristine programming because `;` on its own is a valid program (which does nothing, but doesn't error either). The problem with the second approach is that declarations like `var _=print"Hello"` can be shortened to just `var _="Hello"` (or even `var _=print`) because the declaration with `var` works as long as the right-hand side is a valid SML expression or value (SML is a functional language, so functions can be used as values too).

At this point, I was ready to declare pristine programming in SML impossible, when by chance I stumbled upon *pattern matching* in `val`-declarations. It turns out that the syntax for declarations is not `val <variable_name> = <expression>` but `val <pattern> = <expression>`, where a pattern can consist of variable names, constants and constructors. As the `print` function has type `string -> unit`, we can use a pattern match on the `unit`-value `()` to enforce that the print function is actually applied to the string: `val()=print"Hey"`. With this approach, removing either `print` or `"Hey"` results in a `Pattern and expression disagree`-error.

With this way of pristine printing at hand, the next step is to write a quine, before finally some more save-guarding needs to be added. I previously used an easy SML quine technique (see the revision history), but Anders Kaseorg pointed out a different approach which can save some bytes in his case. It uses the built-in `String.toString` function to handle string escaping and is of the general form `<code>"<data>"`, where `"<data>"` is an escaped string of the `code` before:

```
val()=(fn s=>print(s^"\""^String.toString s^"\""))"val()=(fn s=>print(s^\"\\\"\"^String.toString s^\"\\\"\"))"

```

This is a working quine but not yet pristine. First of all Anders Kaseorg found out that MLton accepts a single quote `"` as code without producing errors, which means we cannot have code ending in a quote as above. The shortest way to prevent this would be to wrap everything after `val()=` in a pair of parenthesis, however then the code could be reduced to `val()=()`. The second shortest way I found is to use `val()=hd[ ... ]`, that is we wrap everything into a list and return its first element to make the type checker happy.

To make sure that no part of the data string can be removed without being noticed, the pattern-matching in `val`-declarations comes in handy again: The length of the final string to be printed (and thus the program length) should equal 195, so we can write `let val t=... val 195=size t in print t end` in the body of the `fn` abstraction instead of `print(...)`. Removing a part of the string results in a length less than 189, thus causing a `Bind` exception to be thrown.

There is still an issue left: the whole `val 195=size t` check could simply be dropped. We can prevent this by expanding the check to match on a tuple: `val t=... val(216,u)=(n+size t,t)in print u end`, such that removing the check results in an unbound variable `u`.

Altogether, this yields the following 195 byte solution:

```
val()=hd[(fn s=>let val t=s^"\""^String.toString s^"\")"val(195,u)=(size t,t)in print u end)"val()=hd[(fn s=>let val t=s^\"\\\"\"^String.toString s^\"\\\")\"val(195,u)=(size t,t)in print u end)"]

```

Applying the golfing trick of using operator variable names like `!`, `$` and `%` instead of `n`, `t` and `u` in order to save some white space (see this tip) leads to the final 182 byte version.

All other substring-removals which where not explicitly stated in the explanation should result in a syntax or type error.

*Edit 1:* `length(explode t)` is just `size t`.
*Edit 2:* Thanks to Anders Kaseorg for a different quine approach and pointing out a "vulnerability".

# Answer
> 3 votes
## Ruby, 78 bytes

```
eval(*[($>.write((s=%{eval(*[($>.write((s=%%{%s})%%s)-78).chr])})%s)-78).chr])

```

I wrote this when I thought of the challenge to make sure it was possible. It uses the same "wrapper" from one of my answers to the original pristine challenge.

Explanation:

* `eval(*[` *expr* `])`

This evaluates whatever *code* returns as a ruby program. This effectively tests that the string that *code* returns is a valid ruby program. Conveniently, ruby programs can be blank, or only consist of whitespace.

The "splat" operator `*` allows you to use an array as arguments to a function. This also means that if `eval` is removed, the resulting program is `(*[` *expr* `])`, which is not valid ruby.
* `($>.write(` *str* `)-78).chr`

`$>` is a short variable for STDOUT.

`$>.write(foo)` writes foo to STDOUT and, importantly for this code, returns the number of bytes written.

`$>.write(foo)-78`: Here `78` is the length of the program, and so if the program is not mangled, will also be the number of bytes written. Therefor, in the unmangled case, this will return zero.

`num.chr` returns num as a character, eg `0.chr` will return a string containing a single null byte. In the unmangled program, this will give a string with a single null byte to `eval`, which is a valid ruby program that is a no-op.

Also, the program can have a substring removed such that it's just `eval(*[(78).chr])` or `eval(*[(8).chr])`, which means that the numeric constant cannot end with any of the numbers (0, 4, 9, 10, 11, 12, 13, 26, 32, 35, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 64, 95) because they are ascii codes for valid single-character ruby programs.
* `%{` str `}`

This is a lesser-known syntax for string literals in ruby. The reason it's used here is that balanced pairs of `{}` can be used within the string, which means this syntax can contain itself. For example, `%{foo{bar}}` is the same as `"foo{bar}"`.
* `(s=%{` *data* `})%s`

This defines the variable `s` which is the data of this quine, as a printf string.

Assignments in ruby return what was assigned, so this is the same as first assigning `s` and then running `s%s`

`%` on a string is syntatic sugar for ruby's equivalent of sprintf. The `%s` signifies where within the data the data itself should be embedded.

This bit of code defines the data portion of the quine and embeds it within itself to create the full code.

---
Tags: code-golf, restricted-source, quine, pristine-programming
---


title: Twice as long, half the price

text:
# Question
Title: Twice as long, half the price
Related: I double the source, you double the output!

---

When *Steve Jobs* launched the iPhone 3G, the slogan said

> Twice as fast, half the price

I changed the word *fast* to *long* to better represent this challenge.

### Objective

Write a program that outputs a non-zero, **even** integer. If the source code is doubled, the value of the output must be cut off by half.

To double the source in a Unix shell (with Core Utilites):

```
cat source.txt source.txt > doubled-source.txt

```

### Rules & Requirements

Now the requirement has changed and the task has been even more challenging!

* You must build **a full program**.
* The initial source is **no longer required** to be at least 1 byte long. An empty program qualifies as long as the output is correct.
* Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden), and must **not** be zero. The integer is no longer required to be positive, so if you like a negative number, it's OK.
* Your program must not take input (or have an unused, empty input) and must not throw any error (compiler warnings are not considered errors). Exit code must be zero.
* Outputting the integers with trailing / leading spaces / newlines is allowed, as long as only one integer is output.
* You can't assume a newline between copies of your source. If you need one, **clarify it**. See the Unix shell command above.
* Standard loopholes are forbidden.

Because this is a , the shortest (original, undoubled) code in each language wins!

### Extras

Please give description / explanation to your code if possible.

# Answer
> 5 votes
# Brain-Flak, 12 bytes

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

```

Outputs 2. Try it online!

The doubled program outputs 1. Try it online!

### Explanation

This code pushes 2 + stack height - top of stack. Initially, this is 2 + 0 - (implicit) 0 = 2. When this code is run again, it pops the existing 2 and pushes 2 + 1 - 2 = 1.

# Answer
> 5 votes
# Python 2, 35 34 bytes

Uses a concept similar to that of Wheat Wizard in the double challenge with an improvement I found to his original code. Here I use the fact that the length of the file is 34 bytes long. Meaning it is equal to 4 modulo 6. (`34%6 = 4`). The double source code would have a length of 68. And `68%6 = 2`, which is exactly what we want.

```
print open(__file__,"a").tell()%6#

```

Try it online!

Double source code

# Explanation

This opens the source code file in append mode

```
open(__file__,"a")
```

We then find the current position in the file, this will be at the end of the file due to opening in append mode

```
open(__file__,"a").tell()
```

We print this length modulo 6

```
print open(__file__,"a").tell()%6
```

And add a comment, so that doubling the source code does not execute more code

```
print open(__file__,"a").tell()%6#
```

# Answer
> 4 votes
# Jelly, 2 bytes

```
¬‘

```

Outputs 2, **Try it online!**

While

```
¬‘¬‘

```

Outputs 1, **Try it online!**

### How?

The default input to a monadic chain is zero...

```
¬‘   - Main link: no arguments
¬    - logical not -- not the implicit input of 0 to yield 1
 ‘   - increment   -- increment 1 to yield 2
     - implicit print if this is the end of the program, otherwise...
     ...
  ¬‘ - continues the monadic chain:
  ¬  - logical not -- not the 2 to yield 0
   ‘ - increment   -- increment 0 to yield 1
     - implicit print if this is the end of the program

```

---

The two byters:

```
Ị‘ - insignificant (abs(z)<=1); increment
Ṇ‘ - non-vectorising logical not; increment

```

would work too.

# Answer
> 2 votes
# Ly, 7 bytes

```
2y1-+-N

```

Try it online!

Simple port of the Brain-Flak answer.

# Answer
> 1 votes
# 05AB1E, 3 bytes

Outputs **4**

```
6rÍ

```

Try it online!

**Doubled Source**

Outputs **2**

```
6rÍ6rÍ

```

Try it online!

**Explanation**

```
6      # push 6
 r     # reverse the stack (does nothing)
  Í    # subtract 2

```

With the doubled source we continue with

```
6      # push 6
 r     # reverse the stack (puts 4 on top)
  Í    # subtract 2

```

# Answer
> 0 votes
# sh, 50 bytes

```
#!/bin/sh
expr 200 / `wc -c $0 | cut -c 1-3`
exit

```

# Answer
> 0 votes
# Jelly, 7 bytes

```
®‘!İ©Ḥµ

```

Try it online!

Outputs 2.

Duplicated Source:

```
®‘!İ©Ḥµ®‘!İ©Ḥµ

```

Try it online!

Outputs 1.

---
Tags: code-golf, source-layout
---


# Question
Title: My program knows your language. Does yours?
Given a list of production rules and start symbol of a proper finite context-free grammar (CFG) of printable characters, your program or function must output its formal language (the set of all sentences which can be constructed from it).

## Task

A context-free grammar is formally defined as a 4-tuple of a few parts. Here, they are defined for you to solve this challenge.

For the purposes of the challenge, a production rule is of the form `{begin, {end-1, end-2, end-3, ..., end-n}}` or equivalent. The `begin` part is always one printable character (`0x20` to `0x7E`), and the `end-i` are all strings of printable characters.

Your program will receive as input a list of production rules and a start symbol. The start symbol is a single printable character.

An iteration takes an input list of strings and is defined as follows: To each string `s` in the input list, look at the first character `c` in it which is found as the `begin` of a production rule. To each `end-i` on the right side of that rule, add to the list the string `s` but where the first instance of `c` is replaced by the string `end-i`. Then remove the original string `s` if and only if there is a character `c`.

The program would repeat applying iterations, beginning with the start symbol, until an iteration does not affect the list of strings, at which point it outputs the list of strings (with repeats removed).

This is equivalent to the following pseudo-code:

```
rules = input()
start_symbol = input()

define iteration(string_list,rules):
  for each string in string_list:
    c = first char in string which is the first element of a rule in rules
    // ^^ This is a Mathematica builtin, right? ^^
    if(c exists):
      ends = the second element of that rule
      for each end in ends:
        // replace the first instance of c with end.
        string_list.append(string.replace(c,end))
      string_list.remove(string)
      // make sure you don't remove the original string if
      // there does not exist a c

  return string_list

current_string = start_symbol

// Clearly this is inefficient to apply iteration twice
// but hey, this is code golf. As long as it runs in less than 60 seconds on TIO!
while(iteration(current_string)!=current_string):
  current_string = iteration(current_string)

print remove_repeats(current_string)

```

Note that you do not need to follow this exact pseudo-code as long as your program yields correct output.

## Example

Given the start symbol `S` and production rules:

```
{S:{aE,bE,c}}
{E:{ab,aC}}
{C:{a,b,c}}

```

We do:

```
{S} // start
{aE,bE,c} // apply first rule to the first element
{aab,aaC,bab,baC,c} // apply second rule to the first and second element
{aab,aaa,aab,aac,bab,baa,bab,bac,c}             // apply third rule to the second and fourth elements
{aab,aaa,aac,bab,baa,bac,c} // remove repeats

```

## Input restrictions

This should only matter to people who care.

The CFG ...

* has no recursion.
* has no cycles.
* has no unreachable symbols.
* has no unproductive symbols.

The list of production rules ...

* may have productions resulting in an empty string.
* may be taken in any format, as long as it encodes **only** a begin character and a list of alternatives as `end-i` for each rule.
* has no duplicate `begin` characters.
* has no duplicate `end` characters within a production rule

## Test Cases

start symbol, {rule1, rule2, ...}, expected output
S, {S: {aE,bE,c}, E: {ab,aC}, C: {a,b,c}}, {aab,aaa,aac,bab,baa,bac,c}
S, {S: {a,B}, B: {g,k}}, {a,g,k}
A, {A: {B,C,D}, B: {c,d}, C:{b,d}, D:{b,c}}, {c,b,d}
~, {~: {`,^,/}, /:{`^,``}, ^:{``,```}}, {`,``,```,````}
+, {A: {1,2,3}, +:{A,B,C}}, {1,2,3,B,C}
</code></pre>

## Notes

* The input will be taken in *any convenient format* as long as it gives no information other than the production rules and start symbol.
* The output should be given such that the list of strings as output is clearly encoded and unique.
* Please specify what format your list of production rules are taken in.
* This is , so shortest code in **each language** wins. Do not be discouraged from posting by answers in golfing languages.

# Answer
# JavaScript, 118 bytes

```
m=>g=c=>(i=0,c=[...new Set([].concat(...c.map(n=>[...n].find(x=>k=m[o=x])?k.map(t=>n.replace(o,t,i=1)):n)))],i?g(c):c)

```

<pre><code>f=

m=>g=c=>(i=0,c=[...new Set([].concat(...c.map(n=>[...n].find(x=>k=m[o=x])?k.map(t=>n.replace(o,t,i=1)):n)))],i?g(c):c)

print = x => console.log(JSON.stringify(x))
print(f({S:['a','B'],B:['g','k']})(['S']))
print(f({S:['aE', 'bE', 'c'], E:['ab', 'aC'], C:['a', 'b', 'c']})(['S']))
print(f({A:['B','C','D'],B:['c','d'],C:['b','d'],D:['b','c']})(['A']))
print(f({'~':['`','^','/'],'/':['`^','``'],'^':['``','```']})(['~']))
print(f({A:['1','2','3'], '+':['A','B','C']})(['+']))

> 4 votes

# Answer
# Python 2, 124 bytes

```
def f(s,r,i=0):
 while s[i:]:
	if s[i]in r:return list(set(s[:i]+l+s[i+1:]for v in r[s[i]]for l in f(v,r)))
	i+=1
 return[s]

```

Try it online!
> 2 votes

---
Tags: code-golf, grammars
---


title: Slice, Slice, Maybe

text:
# Question
Title: Slice, Slice, Maybe
Everyone loves slicing in python, as in `array[5]` to access the fifth element or `array[:5]` to access the zero through fourth element or `array[::-1]` to reverse an array. However, these all have seemingly distinct notations. When and where should the colons and integers be placed?

# Task

Your task is to change any valid slice syntax into a slice with as many colons and integers as possible. To help with that, we will make some definitions. Valid slice syntax is anything directly after "Given a slice" in this section.

Define `<POS>` to be any positive integer, that is any digit `1-9` followed by any amount of digits `0-9`.

Define `<NEG>` to be any negative integer, that is a `-` followed by `<POS>`

Define `<INT>` to be `<POS>`, `<NEG>`, or `<ZERO>`

Define `sgn(a)` to be the sign of `a`: 1 for positive `a`, -1 for negative `a`, and 0 for `a=0`.

For all of the following, `a` and `b` are `<INT>` and `c` is `<POS>` or `<NEG>` unless otherwise specified.

* Given a slice `[]`, your program may have undefined behavior.
* Given a slice `[a]`, your program or function must return `[a:a+k:c]` for some `<POS>` or `<NEG>` value of `c` and `0 < abs(k) <= abs(c)` and (`a+k < 0` if `c < 0`) and (`a+b > 0` if `c > 0`)
* Given a slice `[:]`, your program must return `[0::1]`.
* Given a slice `[a:]`, your program must return `[a::1]`.
* Given a slice `[:b]`, your program must return `[0:b:1]`.
* Given a slice `[a:b]` where `a < b` and `sgn(a)+sgn(b) != 0` your program must return `[a:b:1]`.
* Given a slice `[::]`, your program must return `[0::1]`.
* Given a slice `[a::]`, your program must return `[a::1]`.
* Given a slice `[:b:]`, your program must return `[0:b:1]`.
* Given a slice `[::c]`, your program must return `[0::c]` if `c` is `<POS>` and `[-1::c]` otherwise.
* Given a slice `[a:b:]` where `a < b` and `sgn(a)+sgn(b) != 0`, your program must return `[a:b:1]`.
* Given a slice `[a::c]`, your program must return `[a::c]`.
* Given a slice `[:b:c]`, your program must return `[0:b:c]` if `c` is `<POS>` and `[-1:b:c]` otherwise.
* Given a slice `[a:b:c]` your program must return `[a:b:c]`.

# Example

The "slice" `[5]` gives the fifth element of an array.

Your program or function can output `[5:6:1]` or `[5:7:2]` or `[5:1000:1000]` or `[5:4:-1]` or `[5:0:-5]`.

The program **cannot** output `[5:7:1]` or `[5:-6:1]` or `[5:-6:-1]` or `[5:6:-1]`.

# Test Cases

```
Input     Output
[1]       [1:2:1]     [Output may vary]
[-1]      [-1:-2:-1]  [Output may vary]
[:]       [0::1]
[1:]      [1::1]
[-1:]     [-1::1]
[0:3]     [0:3:1]
[-3:-1]   [-3:-1:1]
[::]      [0::1]
[0::]     [0::1]
[:5:]     [0:5:1]
[::2]     [0::2]
[::-2]    [-1::-2]
[2:4:]    [2:4:1]
[2::3]    [2::3]
[:2:1]    [0:2:1]
[:2:-1]   [-1:2:-1]
[1:2:3]   [1:2:3]

```

# Rules

* You do not have to do any input validation.
* The output and input may include or exclude the brackets `[]`.
* The output and input may be a 3-tuple instead of a `:`-delimited string.
* This is , so shortest code **in each language** wins.

# Answer
# Python 2, ~~101~~ ~~96~~ ~~90~~ ~~85~~ 82 bytes

```
def f(r):l=len(r);b=r[l>1]+'1'*(l<2);c=(r+[0,b])[2]or'1';print r[0]or~-('.'<c),b,c

```

Try it online!

**Explanation:**

Basically a golfed version of:

```
f(r):
 if len(r)==1:return [r[0],r[0]+'1',r[0]+'1']            # [a, a1, a1] where a1 is further from 0 than a
 if len(r)==2:return [r[0]or'0',r[1],'1']                # [a or 0, b, 1]
 if len(r)==3:return [r[0]or -1*(r[2]<0),r[1],r[2]or'1'] # [a or 0|-1, b, c or 1]

```
> 2 votes

# Answer
# Kotlin ~~354~~ 330 bytes

## Submission

```
fun f(i:List<Int?>):List<Int?>?{
val N=null
val Z=mutableListOf(0,N,1)
if(i.none{it!=N})return Z
val v:Int=i[0]?:0
val z:Int=if(i.size==3)i[2]?:1 else 1
val p=if(v<0)-1 else 1
return when(i.size){1->listOf(v,v+p,p)
2->listOf(v, i[1], z)
3->{if(i[0]==N&&i[2]!=N&&i[2]!!<0)Z[0]=-1
return i.zip(Z).map{it.first?:it.second}}
else->N}}

```

## Beautified

```
fun f(input: List<Int?>): List<Int?> {
    if (input.none { it != null }) return listOf(0, null, 1)
    val item0: Int = input[0] ?: 0
    val step: Int = if (input.size == 3) input[2] ?: 1 else 1
    val direction = if (item0 < 0) -1 else 1
    return when (input.size) {
        1 -> listOf(item0, item0 + direction, direction)
        2 -> {
            listOf(item0, input[1], step)
        }
        3 -> {
            val D = mutableListOf(0, null, 1)
            if (input[0] == null && input[2] != null && input[2]!! < 0) D[0] = -1
            return input.zip(D).map { it.first ?: it.second }
        }
        else -> listOf()
    }
}

```

## TryItOnline

Link
> 1 votes

# Answer
# Python 3, 268 bytes

```
import re
w='([^:]*)'
def f(x):
	(a,b,c,d,e)=re.findall('\[%s(?:(:)%s(?:(:)%s)?)?\]'%(w,w,w),x)[0]
	g=int(a)if a else(-1if e and int(e)<0else 0)
	return'[%s:%s:%s]'%(g,c if c else(g+(1if g>0else-1)if not(b or d)else''),e if e else((1if g>0else-1)if not(b or d)else 1))

```

Try it online!
> 1 votes

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


title: Decimal Time of Day Conversion

text:
# Question
Title: Decimal Time of Day Conversion
# Introduction

Time is confusing. Sixty seconds to a minute, sixty minutes to an hour, twenty-four hours to a day (and not to mention that pesky am/pm!).

There's no room for such silliness nowadays, so we've decided to adopt the only sensible alternative: decimal days! That is to say, each day is considered 1 whole unit, and anything shorter is written as a decimal fraction of that day. So, for example: "12:00:00" would be written as "0.5", and "01:23:45" might be written as "0.058159".

Because it will take time to get used to the new system, you are tasked with writing a program that can convert between them in both directions.

# Challenge

Write a program in the language of your choice, that given a modern time in the ISO-8601 format of "hh:mm:ss", will return the equivalent decimal fraction unit. Likewise, given a decimal fraction, the program should return the time in the modern format initially specified.

You can make the following assumptions:

* The modern time input and output can range from "00:00:00" to "24:00:00"
* The decimal time input and output can range from "0" to "1", and should be able to accept/output up to at least 5 decimal places (such as "0.12345"). More precision is acceptable
* The program should be able to know which conversion direction to perform based on input
* You cannot use time related functions/libraries

The winner will be determined by the shortest code that accomplishes the criteria. They will be selected in at least 7 decimal day units, or if/when there have been enough submissions.

# Examples

Here's a(n intentionally) poorly written piece of JavaScript code to be used as an example:

```
function decimalDay(hms) {
    var x, h, m, s;
    if (typeof hms === 'string' && hms.indexOf(':') > -1) {
        x = hms.split(':');
        return (x[0] * 3600 + x[1] * 60 + x[2] * 1) / 86400;
    }
    h = Math.floor(hms * 24) % 24;
    m = Math.floor(hms * 1440) % 60;
    s = Math.floor(hms * 86400) % 60;
    return (h > 9 ? '' : '0') + h + ':' + (m > 9 ? '' : '0') + m + ':' + (s > 9 ? '' : '0') + s;
}
decimalDay('02:57:46'); // 0.12344907407407407
decimalDay('23:42:12'); // 0.9876388888888888
decimalDay(0.5); // 12:00:00
decimalDay(0.05816); // 01:23:45

```

# Answer
> 6 votes
# CJam, ~~58 56~~ 42 bytes

I am sure this is too long and can be golfed a lot. But here goes for starters:

```
86400q':/:d_,({60bd\/}{~*i60b{s2Ue[}%':*}?

```

Try it online here

# Answer
> 3 votes
# Python 2, ~~159~~ ~~150~~ 141 + 2 = 143 Bytes

Straightforward solution, can probably be much shorter. Will work on it.

*Added two bytes to account for input needing to be enclosed in "s. Also, Sp3000 pointed out an issue with eval() interpreting octals, and showed a way to shorten formatting, use map() and remove one print.*

```
n=input();i=float;d=864e2
if':'in n:a,b,c=map(i,n.split(':'));o=a/24+b/1440+c/d
else:n=i(n);o=(':%02d'*3%(n*24,n*1440%60,n*d%60))[1:]
print o

```

Check it out on ideone here.

# Answer
> 2 votes
# Javascript (*ES6*), 116 110 bytes

```
f=x=>x[0]?([h,m,s]=x.split(':'),+s+m*60+h*3600)/86400:[24,60,60].map(y=>('0'+~~(x*=y)%60).slice(-2)).join(':')

// for snippet demo:
i=prompt();
i=i==+i?+i:i; // convert decimal string to number type
alert(f(i))
```

**Commented:**

```
f=x=>
    x[0] ? // if x is a string (has a defined property at '0')
        ([h, m, s] = x.split(':'), // split into hours, minutes, seconds
        +s + m*60 + h*3600) // calculate number of seconds
        / 86400 // divide by seconds in a day
    : // else
        [24, 60, 60]. // array of hours, minutes, seconds
        map(y=> // map each with function
            ('0' + // prepend with string zero
                ~~(x *= y) // multiply x by y and floor it
                % 60 // get remainder
            ).slice(-2) // get last 2 digits
        ).join(':') // join resulting array with colons

```

# Answer
> 2 votes
# Julia, ~~152~~ ~~143~~ 142 bytes

Well, I updated my approach to be less "Julian," as they say, for the sake of golfing. For a better (though less concise) approach, see the revision history.

```
x->(t=[3600,60,1];d=86400;typeof(x)<:String?dot(int(split(x,":")),t)/d:(x*=d;o="";for i=t q,x=x÷i,x%i;o*=lpad(int(q),2,0)*":"end;o[1:end-1]))

```

This creates an unnamed function that accepts a string or a 64-bit floating point number and returns a 64-bit floating point number or string, respectively. To call it, give it a name, e.g. `f=x->...`.

Ungolfed + explanation:

```
function f(x)
    # Construct a vector of the number of seconds in an hour,
    # minute, and second
    t = [3600, 60, 1]

    # Store the number of seconds in 24 hours
    d = 86400

    # Does the type of x inherit from the type String?
    if typeof(x) <: String
        # Compute the total number of observed seconds as the
        # dot product of the time split into a vector with the
        # number of seconds in an hour, minute, and second
        s = dot(int(split(x, ":")), t)

        # Get the proportion of the day by dividing this by
        # the number of seconds in 24 hours
        s / d
    else
        # Convert x to the number of observed seconds
        x *= d

        # Initialize an output string
        o = ""

        # Loop over the number of seconds in each time unit
        for i in t
            # Set q to be the quotient and x to be the remainder
            # from x divided by i
            q, x = divrem(x, i)

            # Append q to o, padded with zeroes as necessary
            o *= lpad(int(q), 2, 0) * ":"
        end

        # o has a trailing :, so return everything up to that
        o[1:end-1]
    end
end

```

Examples:

```
julia> f("23:42:12")
0.9876388888888888

julia> f(0.9876388888888888)
"23:42:12"

julia> f(f("23:42:12"))
"23:42:12"

```

# Answer
> 2 votes
## Python 3: 143 Bytes

```
i,k,l,m=input(),60,86400,float
if'.'in i:i=m(i)*l;m=(3*':%02d'%(i/k/k,i/k%k,i%k))[1:]
else:a,b,c=map(m,i.split(':'));m=(a*k*k+b*k+c)/l
print(m)

```

Same byte count as the python 2 solution but it seems we took different approaches to the maths.

# Answer
> 2 votes
# C, 137 bytes

Full C program. Takes input on stdin and outputs on stdout.

```
main(c){float a,b;scanf("%f:%f:%d",&a,&b,&c)<3?c=a*86400,printf("%02d:%02d:%02d",c/3600,c/60%60,c%60):printf("%f",a/24+b/1440+c/86400.);}

```

Ungolfed and commented:

```
int main() {
    // b is float to save a . on 1440
    float a,b;
    // c is int to implicitly cast floats
    int c;

    // If the input is hh:mm:ss it gets splitted into a, b, c
    // Three arguments are filled, so ret = 3
    // If the input is a float, it gets stored in a
    // scanf stops at the first semicolon and only fills a, so ret = 1
    int ret = scanf("%f:%f:%d", &a, &b, &c);

    if(ret < 3) {
        // Got a float, convert to time
        // c = number of seconds from 00:00:00
        c = a * 86400;
        printf("%02d:%02d:%02d", c/3600, c/60 % 60, c%60);
    }
    else {
        // a = hh, b = mm, c = ss
        // In one day there are:
        // 24 hours
        // 1440 minutes
        // 86400 seconds
        printf("%f", a/24 + b/1440 + c/86400.);
    }
}

```

# Answer
> 2 votes
# J, 85 bytes

Results:

T '12:00:00'
0.5

T 0.5
12 0 0

T '12:34:56'
0.524259

T 0.524259
12 34 56

```
T=:3 :'a=.86400 if.1=#y do.>.(24 60 60#:y*a)else.a%~+/3600 60 1*".y#~#:192 24 3 end.'

```

Total 85

# Answer
> 1 votes
# Javascript, ~~194~~ ~~192~~ ~~190~~ 188 bytes

```
function(z){if(isNaN(z)){x=z.split(':');return x[0]/24+x[1]/1440+x[2]/86400}h=(z*24)|0;h%=24;m=(z*1440)|0;m%=60;s=(z*86400)|0;s%=60;return""+(h>9?'':0)+h+':'+(m>9?'':0)+m+':'+(s>9?'':0)+s}

```

# Answer
> 1 votes
# JavaScript ES6, ~~98~~ 130 bytes

```
s=>s==+s?'246060'.replace(/../g,l=>':'+('0'+~~(s*=+l)%60).slice(-2)).slice(1):s.split`:`.reduce((a,b)=>+b+(+a)*60)*1/864e2;f(0.5);

```

# Answer
> 1 votes
# C, ~~156~~ 152 bytes

I thought it is going to be easy for C. But still ended up quite large. :(

```
n,m=60;d(char*s){strchr(s,58)?printf("%f",(float)(atoi(s)*m*m+atoi(s+3)*m+atoi(s+6))/m/m/24):printf("%02d:%02d:%02d",(n=atof(s)*m*m*24)/m/m,n/m%m,n%m);}

```

Test Program:

```
#include <stdio.h>
#include <stdlib.h>

int n,m=60;
d(char*s)
{
    strchr(s,':') ?
        printf("%f",(float)(atoi(s)*m*m+atoi(s+3)*m+atoi(s+6))/m/m/24):
        printf("%02d:%02d:%02d",(n=atof(s)*m*m*24)/m/m,n/m%m,n%m);
}

int main()
{
    d("01:23:45");
    printf("\n");
    d("02:57:46");
    printf("\n");
    d("23:42:12");
    printf("\n");
    d("12:00:00");
    printf("\n");
    d("0.5");
    printf("\n");
    d("0.05816");
    printf("\n");
    d("0");
    printf("\n");
    d("1");
    printf("\n");
    return 0;
}

```

Output:

```
0.058160
0.123449
0.987639
0.500000
12:00:00
01:23:45
00:00:00
24:00:00

```

# Answer
> 1 votes
# PHP, ~~70~~ 69 bytes

```
<?=strpos($t=$argv[1],58)?strtotime($t)/86400:date("H:i:s",$t*86400);

```

takes input from command line argument, prints to STDOUT:

If input contains a colon, convert to unix time and divide by (seconds per day),
else multply numeric value with (seconds per day) and format unix time to `hh:mm:ss`.

# Answer
> 1 votes
# Perl, ~~109~~ ~~108~~ 101 + 6 (`-plaF:` flag) = 107 bytes

```
$_=$#F?($F[0]*60+$F[1]+$F[2]/60)/1440:sprintf"%02d:%02d:%02d",$h=$_*24,$m=($h-int$h)*60,($m-int$m)*60

```

Using:

```
perl -plaF: -e '$_=$#F?($F[0]*60+$F[1]+$F[2]/60)/1440:sprintf"%02d:%02d:%02d",$h=$_*24,$m=($h-int$h)*60,($m-int$m)*60' <<< 01:23:45

```

Try it on Ideone.

# Answer
> 0 votes
# Excel, 178 bytes

```
=IF(LEFT(A1,2)="0.",TEXT(FLOOR(A1*24,1),"00")&":"&TEXT(MOD(FLOOR(A1*1440,1),60),"00")&":"&TEXT(MOD(FLOOR(A1*86400,1),60),"00"),((LEFT(A1,2)*60+MID(A1,4,2))*60+RIGHT(A1,2))/86400)

```

---
Tags: code-golf, string, date, floating-point
---


# Question
Title: Playing Darts: become an amateur with the most efficient prioritizing
### Introduction:

I think most people will know how darts work. But since some might not, here are the rules of playing Darts in a nutshell:

* Amount of players: 2
* Starting points: 501
* Goal: Get your points to 0 first
* Darts per player: 3
* Available numbers on the board: 1 through 20, and Bulls-eye

Here is the layout of a Dartboard:

* Each number is worth an equal amount of points
* Each triple (the inner red-green circle) is 3x the number
* Each double (the outer red-green circle) is 2x the number
* The red center is called the Bulls-eye or Double-Bull, which is worth 50 points
* And the outlined part of the center around the Bulls-eye (also known as Single-Bull) is worth 25 points

Some other rules:

* You'll have to finish to 0 exactly
* The very last dart that puts your points to 0 must be a double or the Bulls-eye
* If a dart would leave your remaining total on 1 or less than 0, the entire set of three darts of which it forms a part is discarded (since you aren't able to finish 1 or less than 0 with a double)
* Once you've reached (exactly) 0, you won't have to throw any remaining darts of the three you throw in a single turn

### Relevant information regarding this Challenge:

Although every player has of course preferred doubles to finish with (Double-20 is preferred by some of the pros for example), in general - and for the sake of this challenge - this will be the order of prioritization on finishing doubles:

```
16, 8, 20, 12, 4, 18, 14, 10, 6, 2, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1, Bulls-Eye

```

Why? Let's compare a double-16 and double-17 finish. If you want to throw the double-16, but throw in the 16 instead by accident, you can continue to double-8. If you want to throw the double-17, but throw in the 17 instead, you must first throw an odd number (like 1 or 3), before you can try your best on a finishing double again. If we look at the following, you can see the next move in case you accidentally throw a single instead of a double:

```
Bulls-eye
20-10-5
19
18-9
17
16-8-4-2-1
15
14-7
13
12-6-3
11

```

Clearly 16 is your best bet, hence the given order of prioritizing above. (And since the Bulls-eye is the smallest, that has the lowest preference for the sake of this challenge.)

### Challenge:

So, those are the rules of playing Darts. As for this challenge:

Given an input integer in the range of 2-170 (excluding 169, 168, 166, 165, 163, 162, 159; these cannot be finished within 3 darts), output the steps required to finish it following these rules in this exact order of precedence:

1. You must try to finish it in as few darts as possible
2. You must keep the prioritizing in mind when doing so for your finishing darts
3. When multiple options are available with the same priority, we pick the option with the highest number. I.e. 1.) For `131` the expected result is `T20, T13, D16` instead of `T19, T14, D16` or `T18, T15, D16` or `T17, T14, D16` etc., because `T20` is the highest number. 2.) For `109` the expected result is `17, T20, D16` instead of `20, T19, D16`, because `T20` is the highest number.
4. If exactly three darts must be thrown to finish, sort the first two throws by Single, Triple, Double, Bulls-Eye, Single-Bull

Keeping the rules above in mind, these will be your strict input-output pairs (format of both input and output is flexible, though):

```
Legend: D = Double; T = Triple; BE = Bulls-eye; SB = Single-Bull

Points left:   Darts to throw (in exact order)
2              D1
3              1, D1
4              D2
5              1, D2
6              D3
7              3, D2
8              D4
9              1, D4
10             D5
11             3, D4
12             D6
13             5, D4
14             D7
15             7, D4
16             D8
17             1, D8
18             D9
19             3, D8
20             D10
21             5, D8
22             D11
23             7, D8
24             D12
25             9, D8
26             D13
27             11, D8
28             D14
29             13, D8
30             D15
31             15, D8
32             D16
33             1, D16
34             D17
35             3, D16
36             D18
37             5, D16
38             D19
39             7, D16
40             D20
41             9, D16
42             10, D16
43             11, D16
44             12, D16
45             13, D16
46             14, D16
47             15, D16
48             16, D16
49             17, D16
50             BE
51             19, D16
52             20, D16
53             T7, D16
54             D11, D16
55             T13, D8
56             T8, D16
57             SB, D16
58             D13, D16
59             T9, D16
60             D14, D16
61             T15, D8
62             T10, D16
63             T13, D12
64             D16, D16
65             T11, D16
66             D17, D16
67             T17, D8
68             T12, D16
69             T15, D12
70             D19, D16
71             T13, D16
72             D20, D16
73             T19, D8
74             T14, D16
75             T17, D12
76             T20, D8
77             T15, D16
78             D19, D20
79             T13, D20
80             T16, D16
81             T19, D12
82             BE, D16
83             T17, D16
84             T20, D12
85             T15, D20
86             T18, D16
87             T17, D18
88             T16, D20
89             T19, D16
90             BE, D20
91             T17, D20
91             T17, D20
92             T20, D16
93             T19, D18
94             T18, D20
95             T19, D19
96             T20, D18
97             T19, D20
98             T20, D19
99             7, T20, D16
100            T20, D20
101            T17, BE
102            10, T20, D16
103            11, T20, D16
104            T18, BE
105            13, T20, D16
106            14, T20, D16
107            T19, BE
108            16, T20, D16
109            17, T20, D16
110            T20, BE
111            19, T20, D16
112            20, T20, D16
113            T20, T7, D16
114            T20, D11, D16
115            T19, D13, D16
116            T20, T8, D16
117            T20, SB, D16
118            T20, D13, D16
119            T20, T9, D16
120            T20, D14, D16
121            T19, D16, D16
122            T20, T10, D16
123            T19, D17, D16
124            T20, D16, D16
125            T20, T11, D16
126            T20, D17, D16
127            T19, D19, D16
128            T20, T12, D16
129            T19, D20, D16
130            T20, D19, D16
131            T20, T13, D16
132            T20, D20, D16
133            T17, BE, D16
134            T20, T14, D16
135            T19, D19, D20
136            T18, BE, D16
137            T20, T15, D16
138            T20, D19, D20
139            T19, BE, D16
140            T20, T16, D16
141            T17, BE, D20
142            T20, BE, D16
143            T20, T17, D16
144            T18, BE, D20
145            T20, T15, D20
146            T20, T18, D16
147            T19, BE, D20
148            T20, T16, D20
149            T20, T19, D16
150            T20, BE, D20
151            T20, T17, D20
152            T20, T20, D16
153            T20, T19, D18
154            T20, T18, D20
155            T20, T19, D19
156            T20, T20, D18
157            T20, T19, D20
158            T20, T20, D19
160            T20, T20, D20
161            T20, T17, BE
164            T20, T18, BE
167            T20, T19, BE
170            T20, T20, BE

```

*NOTE: Test cases are done by hand, so if you see any mistakes, please comment down below.<br>Multiple fixed thanks to @JohanKarlsson, @JonathanAllan, and @Sebastian*

### Challenge rules:

* Input and output format are flexible. Can be a list of Strings, array of Objects, single STDOUT-printline, your call. You can also choose your own formatting regarding the Triples, Doubles, Bulls-Eye and Single-Bull. Please state what you've used in your answer.

### General rules:

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

# Answer
# Python 3, 987 1,003 586 bytes

*Edit: Fixed problem with T20's using some hacky code.*

*Edit: Added in golfed version.*

```
from itertools import*
def d(i):
 f={v*2:"D"+str(v) for v in [16,8,20,12,4,18,14,10,6,2,19,17,15,13,11,9,7,5,3,1]}
 f[50]="BE"
 t={3*i:"T"+str(i) for i in range(20,6,-1)}
 t.update({i:str(i) for i in range(20,0,-1)})
 t.update({2*i:"D"+str(i) for i in range(20,10,-1) if i%3!=0})
 t.update({50:"BE", 25:"SB"})
 if i in f:
  return f.get(i)
 else:
  for n,x in product(f,t):
   r=i-n
   if r in t:
    return ' '.join((t.get(r),f.get(n)))
  for n,x,y in product(f,t,t):
   r=i-n
   if x+y==r:
    b=x!=60 or y>20
    return ' '.join((t.get(x if b else y),t.get(y if b else x), f.get(n)))

```

Try it online! Ungolfed version:

```
from itertools import product
def darts(inp):
    list_finishes = [16, 8, 20, 12, 4, 18, 14, 10, 6, 2, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]
    finishes = {finish*2:"D"+str(finish) for finish in list_finishes}
    finishes.update({50:"BE"})
    throws = {3*i:"T"+str(i) for i in range(20,6,-1)}
    throws.update({i:str(i) for i in range(20,0,-1)})
    throws.update({2*i:"D"+str(i) for i in range(20,10,-1) if i%3!=0})
    throws.update({50:"BE", 25:"SB"})

    if inp in finishes:
        return finishes.get(inp)
    else:
        for finish, x in product(finishes, throws):
            remaining = inp - finish
            if remaining in throws:
                return ', '.join((throws.get(remaining), finishes.get(finish)))
        for finish, x, y in product(finishes, throws, throws):
            remaining = inp - finish
            if x + y == remaining:
                    return ', '.join((throws.get(x if x!= 60 or y>20 else y), throws.get(y if x!= 60 or y>20 else x), finishes.get(finish)))

```

Little effort has gone into golfing this code, as I intended it to be a reference solution more than anything. Anyone who wants to improve this code is free to post it as their own solution or edit my answer. I have also created a function to test your function against the given values (Try it online with my function):

```
def test_func(func, has_comma=True):
    answers  =  """
2              D1
3              1, D1
4              D2
5              1, D2
6              D3
7              3, D2
8              D4
9              1, D4
10             D5
11             3, D4
12             D6
13             5, D4
14             D7
15             7, D4
16             D8
17             1, D8
18             D9
19             3, D8
20             D10
21             5, D8
22             D11
23             7, D8
24             D12
25             9, D8
26             D13
27             11, D8
28             D14
29             13, D8
30             D15
31             15, D8
32             D16
33             1, D16
34             D17
35             3, D16
36             D18
37             5, D16
38             D19
39             7, D16
40             D20
41             9, D16
42             10, D16
43             11, D16
44             12, D16
45             13, D16
46             14, D16
47             15, D16
48             16, D16
49             17, D16
50             BE
51             19, D16
52             20, D16
53             T7, D16
54             D11, D16
55             T13, D8
56             T8, D16
57             SB, D16
58             D13, D16
59             T9, D16
60             D14, D16
61             T15, D8
62             T10, D16
63             T13, D12
64             D16, D16
65             T11, D16
66             D17, D16
67             T17, D8
68             T12, D16
69             T15, D12
70             D19, D16
71             T13, D16
72             D20, D16
73             T19, D8
74             T14, D16
75             T17, D12
76             T20, D8
77             T15, D16
78             D19, D20
79             T13, D20
80             T16, D16
81             T19, D12
82             BE, D16
83             T17, D16
84             T20, D12
85             T15, D20
86             T18, D16
87             T17, D18
88             T16, D20
89             T19, D16
90             BE, D20
91             T17, D20
91             T17, D20
92             T20, D16
93             T19, D18
94             T18, D20
95             T19, D19
96             T20, D18
97             T19, D20
98             T20, D19
99             7, T20, D16
100            T20, D20
101            T17, BE
102            10, T20, D16
103            11, T20, D16
104            T18, BE
105            13, T20, D16
106            14, T20, D16
107            T19, BE
108            16, T20, D16
109            17, T20, D16
110            T20, BE
111            19, T20, D16
112            20, T20, D16
113            T20, T7, D16
114            T20, D11, D16
115            T19, D13, D16
116            T20, T8, D16
117            T20, SB, D16
118            T20, D13, D16
119            T20, T9, D16
120            T20, D14, D16
121            T19, D16, D16
122            T20, T10, D16
123            T19, D17, D16
124            T20, D16, D16
125            T20, T11, D16
126            T20, D17, D16
127            T19, D19, D16
128            T20, T12, D16
129            T19, D20, D16
130            T20, D19, D16
131            T20, T13, D16
132            T20, D20, D16
133            T17, BE, D16
134            T20, T14, D16
135            T19, D19, D20
136            T18, BE, D16
137            T20, T15, D16
138            T20, D19, D20
139            T19, BE, D16
140            T20, T16, D16
141            T17, BE, D20
142            T20, BE, D16
143            T20, T17, D16
144            T18, BE, D20
145            T20, T15, D20
146            T20, T18, D16
147            T19, BE, D20
148            T20, T16, D20
149            T20, T19, D16
150            T20, BE, D20
151            T20, T17, D20
152            T20, T20, D16
153            T20, T19, D18
154            T20, T18, D20
155            T20, T19, D19
156            T20, T20, D18
157            T20, T19, D20
158            T20, T20, D19
160            T20, T20, D20
161            T20, T17, BE
164            T20, T18, BE
167            T20, T19, BE
170            T20, T20, BE
"""
    if not has_comma:
        answers = answers.replace(',','')
    answers_dict = {int(answer.split('  ')[0]):answer.split('  ', 1)[1].lstrip() for answer in answers.split('\n')[1:-1]}
    all_valid = True
    for key in answers_dict.keys():
        try:
           assert func(key)==answers_dict.get(key)
        except:
            print("Failure on {}: Your answer '{}' != Given answer '{}'".format(key, func(key), answers_dict.get(key)))
            all_valid = False
    if all_valid:
        print("All tests completed successfully.")

```
> 3 votes

---
Tags: code-golf, number, arithmetic, game, integer
---


title: The Original Number (II)

text:
# Question
Title: The Original Number (II)
*This challenge is essentially identical to this one with just one difference: it is now allowed to shuffle letters anywhere in the string.*

## Scenario

John has an important number, and he doesn't want others to see it.

He decided to encrypt the number, using the following steps:

His number is always a non-decreasing sequence (ie. `"1123"`)

He converted each digit into English words. (ie. `"123" -> "ONETWOTHREE"`)

And then, rearrange the letters randomly. (ie. `"ONETWOTHREE" -> "EEWOOHRNTET"`)

John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(

---

## Task

Given the encrypted string s, your task is to decrypt it and return the original number.

---

## Rules

* This is code golf, so the shortest answer in bytes wins
* You can assume that the input string is always valid
* The input string only contains uppercase letters
* The original numbers are always arranged in ascending order
* You may return the number in string or integer format
* ~~The letters will only be shuffled between one word, not between the whole string.~~ The letters can be shuffled anywhere in the string.
* The numbers will only be from 1 to 9 inclusive (`ONE` to `NINE`)

---

## Possible Unscrambled String

Here is a list of the strings just after they have been converted to strings from the numbers:

```
 1 -> ONE
 2 -> TWO
 3 -> THREE
 4 -> FOUR
 5 -> FIVE
 6 -> SIX
 7 -> SEVEN
 8 -> EIGHT
 9 -> NINE

```

---

## Examples

`"NEO" -> 1`

`"NWEOOT" -> 12`

`"TOEERWNEHOT" -> 123`

`"IHNEVGENNEISTE" -> 789`

`"WEETVTRFSVUHNEEFRHIXEOINSNIEGTOONIEE" -> 123456789`

`"EWHEWROETOTTON" -> 1223`

`"ONEWESTV" -> 27` (thanks, ETHproductions!)

# Answer
# Python 2, 123 bytes

```
c=map(input().count,"OWHUFXSGIQ")
i=4
for j in"71735539994":c[i*2]-=c[int(j)];i=-~i%5
s=""
for n in c:i+=1;s+=`i`*n
print s

```

A full program taking quoted input and printing John's number.

**Try it online!** or see a test-suite

### How?

Let's work with the example "NEONSEXTOWNII" (to yield 1269, and be somewhat Leisure Suite Larry-esque!)

First `c=map(input().count,"OWHUFXSGIQ")` takes input and counts the number of each of `OWHUFXSGIQ` \- these are letters that appear in each number in ascending order, with 2,4,6, and 8 having their "own" letters (`WUXG`), plus an extra letter, `Q` to append a zero to the the end and make the length of the resulting list even. For the example:

```
[2,1,0,0,0,1,1,0,2,0] <- c
 O W H U F X S G I Q  <- is the counts of these letters
 1 2 3 4 5 6 7 8 9 0  <- which "relate to" these digits in John's number
   2   4   6   8   0  <- these will be correct as the letters are unique to their words

```

The entries for 1, 3, 5, 7, and 9 need adjusting to correct the abundance of the other letters. This is performed by the next loop:

```
i=4
for j in"71735539994":c[i*2]-=c[int(j)];i=-~i%5

```

Note that the entries to adjust are alternate ones (1,3,5,7,9,1,3,5,...), so we can add two to an index variable at each step and modulo by 10 to stay in range if we need to traverse more than once (which we do). To save some bytes we can increment by one and modulo by 5 and use double the index.
Since the adjustments for 9 require the most work we start there - it resides at index 8 so we start at `i=4`. The string `"71735539994"` then gives the indexes, `j`, of the values to remove at each stage (where we have ensured the ninth index will contain zero by using `"Q"` when creating `c`); `c[i*2]-=c[int(j)]` performs each individual adjustment and `i=-~i%5` moves `i` to the next index (where `-~i` is `-(-1-i)` or `i+1` saving parentheses `(i+1)%5`) keeping `i*2` within the bounds of `c`.
Thus we first subtract the number at index `j=7` from that at index `i*2=8`, subtracting the number of "G"s counted from the number of "I"s, adjusting the "NINE" count down by the (correct) number of "EIGHT"s (which also has an "I"). We then move onto `i=0` (`-~4%5 = (4+1)%5 = 0`), referencing index `i*2 = 0` which is for "ONE" and subtract the value found at index `j=1` the entry counting "W" and hence "TWO", adjusting the count of "O"s down. By the end of the loop we have the corrected counts:

```
[1,1,0,0,0,1,0,0,1,0] <- c   (for 1223333448 it would be: [1,2,4,2,0,0,0,1,0,0])
 1 2 3 4 5 6 7 8 9 0

```

so all that remains is to print out what `c` now represents (`1269`). `i` is now back at `0`, so we increment it at the start of the loop and use it as our digit:

```
s=""
for n in c:i+=1;s+=`i`*n
print s

```

The back ticks, ``i``, are Python2 shorthand for `repr(i)` which gets a string representation of an object (the digit character in question as a string) and multiplying a string by a number creats a new string of that many repeats (here we only show `n=0` turning ``i`` from say `"5"` to `""` and `n=1` turning keeping say `"6"` as `"6"`, but it also works for larger positive integers, so `"3"*4` becomes `"3333"` for example.)
> 9 votes

# Answer
# 05AB1E, 31 bytes

```
[{‘Z€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘#NSèJ{Q#

```

Try it online!

**Explanation**

```
[                                   # start loop
 {                                  # sort input
  ‘Z€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š‘#            # push the list ['Z','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE']
                        N           # push the current iteration counter
                         S          # split to list of digits
                          è         # index into the list with each
                           J{       # join to string and sort
                             Q#     # if the strings are equal, exit loop
                                    # implicitly print iteration counter

```

Very inefficient for large input.
> 8 votes

# Answer
# Retina, ~~112~~ 97 bytes

```
O`.
}`GH
8
X
6
H
3
+`F(.*)O(.*)U
4$1$2
+`O(.*)W
2$1
+`F(.*)V
5$1
+`N(.*)V
7$1
}`NO
1
NN
9
T`L
O`.

```

Try it online!

*-12 bytes thanks to @Neil*

*-3 bytes by use of L character classes in transposition*

**How it Works**

Basically, this relies on the fact that letters are only used in certain number names. For example `SIX` is the only name which contains an `X`. This gets trickier with the fact that some words overlap in letters, such as both `FIVE` and `SEVEN` using `V`. This could be corrected for by identifying `FIVE` with `F(.*)V`.
> 8 votes

# Answer
# Kotlin 1.1, ~~359~~ ~~352~~ ~~331~~ ~~327~~ 325 bytes

## Submission

```
fun r(r:String):String{var s=""
val f=r.split(s).groupingBy{it}.eachCount()
val c=Array(10,{0})
c[8]=f["G"]?:0
c[6]=f["X"]?:0
c[4]=f["U"]?:0
c[2]=f["W"]?:0
c[1]=(f["O"]?:0)-c[2]-c[4]
c[3]=(f["R"]?:0)-c[4]
c[7]=(f["S"]?:0)-c[6]
c[5]=(f["V"]?:0)-c[7]
c[9]=((f["N"]?:0)-c[1]-c[7])/2
for(i in 1..9)for(x in 1..c[i])s+=i
return s}

```

**Does not work on TryItOnline due to Kotlin 1.1 not being supported**

## Test

```
fun r(r:String):String{
val f=r.split("").groupingBy{it}.eachCount()
val c=Array(10,{0})
c[8]=f["G"]?:0
c[6]=f["X"]?:0
c[4]=f["U"]?:0
c[2]=f["W"]?:0
c[1]=(f["O"]?:0)-c[2]-c[4]
c[3]=(f["R"]?:0)-c[4]
c[7]=(f["S"]?:0)-c[6]
c[5]=(f["V"]?:0)-c[7]
c[9]=((f["N"]?:0)-c[1]-c[7])/2
var s=""
for(i in 1..9)for(x in 1..c[i])s+=i
return s}

data class TestData(val input: String, val output: String)

fun main(vararg args:String) {
    val items = listOf(
    TestData("NEO" , "1"),
    TestData("NWEOOT" , "12"),
    TestData("TOEERWNEHOT" , "123"),
    TestData("IHNEVGENNEISTE" , "789"),
    TestData("WEETVTRFSVUHNEEFRHIXEOINSNIEGTOONIEE" , "123456789"),
    TestData("EWHEWROETOTTON" , "1223")
    )
    for (item in items) {
        val out = r(item.input)
        if (out != item.output) {
            throw AssertionError("Bad result: $item : $out")
        }
    }
}

```

# Logic

I used the sheet above to work out the simplest way to solve each letter

* Green = Solve by itself
* Blue = Needs greens to solve
* Orange = Needs blues to solve
* Red = Needs oranges to solve

# Edits

* -7 - Whitespace changes by w0lf
* -21 - Shrank listOf to Array
* -4 - Removed unneeded brackets
* 0 - Added logic in
* -2 - Re-using empty string thanks to kevin-cruijssen
> 5 votes

# Answer
# Jelly, 37 bytes

```
1ðDị“©ȯ¿w¶&ÇhṆỌƘ#Ȯʋ~¢CNẓ_»ŒuḲ¤ẎŒ!ċð1#

```

Try it online!

-1 thanks to Jonathan Allan.
> 4 votes

# Answer
# Java 8, ~~248~~ 234 bytes

```
s->{int x=0,a[]=new int[10];for(String t:"2WO;4UORF;6XSI;8GI;5FI;7S;3R;1O;9I".split(";"))for(;s.indexOf(t.charAt(1))>=0;a[t.charAt(0)-48]++)for(String z:t.split(""))s=s.replaceFirst(z,"");for(s="";x++<9;)for(;a[x]-->0;)s+=x;return s;}

```

**Code Explanation:**

```
s->{
    // Array to count how often which number appears
    int a[]=new int[10];
    // The first character behind the number serves the identification
    // the other characters get removed to identify the other numbers later
    for(String t:"2WO;4UORF;6XSI;8GI;5FI;7S;3R;1O;9I".split(";"))
        // Check if the string contains the id
        for(;s.indexOf(t.charAt(1))>=0;a[t.charAt(0)-48]++)
            // Remove the relevant charcters
            for(String z:t.split(""))
                s=s.replaceFirst(z,"");
    // Clear the string to write the output
    s="";
    // write the numbers sequential into the output
    for(int x=0;x++<9;)
        for(;a[x]-->0;)
            s+=x;
    return s;
}

```

-14 Thanks to Olivier Grégoire
> 3 votes

# Answer
# Perl 5, 100 bytes

99 bytes code + 1 byte for `-n` switch.

```
${$_}++for/./g;@a=($O-$W-$U,$W,$H-$G,$U,$F-$U,$X,$S-$X,$G,$I-$F+$U-$X-$G);print$_ x$a[$_-1]for 1..9

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~346~~ ~~345~~ ~~344~~ ~~336~~ 327 bytes

```
s->{int g=c(s+=" ","G"),u=c(s,"U"),w=c(s,"W"),x=c(s,"X"),f=c(s,"F")-u,h=c(s,"H")-g,v=c(s,"V")-f,o=c(s,"O")-u-w,i=c(s,"I")-f-x-g;return d(s=d(s=d(s=d(s=d(s=d(s=d(s=d(s=d("",o,1),w,2),h,3),u,4),f,5),x,6),v,7),g,8),n,9);}int c(String...s){return~-s[0].split(s[1]).length;}String d(String s,int i,int n){for(;i-->0;s+=n);return s;}

```

Try it here.

**General explanation:**

I've looked at the occurrences of each character in the alphabet:

```
E 13357789
F 45
G 8
H 38
I 5689
N 1799
O 124
R 34
S 67
T 238
U 4
V 57
W 2
X 6

```
* I first counted all occurrences of the single-matches characters: `G=8; U=4; W=2; X=6`.
* Then all occurrences of two-matched characters, which also match one of the four above, which I can subtract from their counts: `F=5; H=3`.
* Then I did the same again for `V=7` (by subtracting `F=5`).
* Then the same for all three-matches characters that were left: `O=1; N=9`.
    + But because `N` has two occurrences in `NINE`, I had to do an additional `-1` for every occurrence of `N`, so I've used `I=9` instead (by subtracting three previous matches instead of two).

**Code Explanation:**

```
s->{                    // Method with String as parameter and return-type
  int g=c(s+=" ","G"),  //  Amount of 8s (and append a space to `s` first, for the .split)
      u=c(s,"U"),       //  Amount of 4s
      w=c(s,"W"),       //  Amount of 2s
      x=c(s,"X"),       //  Amount of 6s
      f=c(s,"F")-u,     //  Amount of 5s
      h=c(s,"H")-g,     //  Amount of 3s
      v=c(s,"V")-f,     //  Amount of 7s
      o=c(s,"O")-u-w,   //  Amount of 1s
      i=c(s,"I")-f-x-g; //  Amount of 9s
  return d(             //  Return the result by:
   s=d(
    s=d(
     s=d(
      s=d(
       s=d(
        s=d(
         s=d(
          s=d("",       //   Making the input String `s` empty, since we no longer need it
                 o,1),  //   Append all 1s to `s`
         w,2),          //   Append all 2s to `s`
        h,3),           //   Append all 3s to `s`
       u,4),            //   Append all 4s to `s`
      f,5),             //   Append all 5s to `s`
     x,6),              //   Append all 6s to `s`
    v,7),               //   Append all 7s to `s`
   g,8),                //   Append all 8s to `s`
  i,9);                 //   And then returning `s` + all 9s
}                       // End of method

int c(String...s){  // Separate method with String-varargs parameter and int return-type
                    //  `s[0]` is the input-String
                    //  `s[1]` is the character to check
  return~-s[0].split(s[1]).length;
                    //  Return the amount of times the character occurs in the String
}                   // End of separated method (1)

String d(String s,int i,int n){
               // Separate method with String and two int parameters and String return-type
  for(;i-->0;  //  Loop from the first integer-input down to 0
      s+=n     //   And append the input-String with the second input-integer
  );           //  End of loop
  return s;    //  Return the resulting String
}              // End of separated method (2)

```
> 2 votes

# Answer
# Python 3, 225 bytes

```
def f(s):
	r=[]
	for i,w in zip([2,4,6,8,3,5,7,1,9],["WTO","UFOR","XSI","GEIHT","HTREE","FIVE","VSEEN","ONE","NINE"]):
		while s.count(w[0]):
			r+=[i]
			for l in w:s="".join(s.split(l,1))
	return "".join(sorted(map(str,r)))

```

Try it online!

Straightforward: remove the digits which are identified by a specific letter first.
> 1 votes

# Answer
# Python 3, 125 bytes

```
lambda s:''.join(min(w)*(2*sum(map(s.count,w[:2]))-sum(map(s.count,w)))for w in"O1WU W2 H3G U4 F5U X6 S7X G8 IUFXG9".split())

```

Try it online!

After reading the linked challenge I realized this is a variation on mdahmoune's Python solution, which is itself based on Draco18s's ES6 solution, but hey, at least we golfed off two bytes.

Like that solution, we compute the answer through a linear combination of the number of occurrences of certain letters. We encode the linear combinations briefly by writing them as words where the first two letters are to be added and everything afterwards is to be subtracted. Sometimes a character is needed to pad the first two characters; we use this to hide the digit we want to output (which will never occur in the input, so won't affect our algorithm), which we extract with `min`.
> 1 votes

# Answer
## R, 154

```
u=utf8ToInt(s)-71
m=sum
b=m(u==16)
d=m(u==14)
f=m(u==17)
a=m(u==8)-b-d
g=m(u==12)-f
cat(rep(1:9,c(a,b,m(u==11)-d,d,m(u==15)-g,f,g,m(!u),(m(u==7)-a-g)/2)))

```

Try it online!
> 1 votes

# Answer
# Axiom, 351 bytes

```
s:="GXUWRFVIONETHS";e:EqTable(CHAR,INT):=table();v:=[8,6,4,2,3,5,7,9,1];z:=[k for k in 1..46|prime?(k)];F(x,y)==>for i in 1..#x repeat y;F(z,e.(s.i):=z.i);t:=[1787026,2451,16445,5957,16036207,130169,20372239,495349,20677];h(a)==(r:=1;F(a,r:=r*e.(a.i));j:=[];F(v,while r rem z.i=0 repeat(r:=r quo t.i;j:=cons(v.i,j)));j:=sort j;k:=0;F(j,k:=k*10+j.i);k)

```

ungolfed commented results

```
s:="GXUWRFVIONETHS" -- tutte le lettere di ONE..NINE in ordine di importanza
e:EqTable(Character,Integer):=table()
v:=[8,6,4,2,3,5,7,9,1]              -- numeri da controllare in quell'ordine di apparizione di v
z:=[k for k in 1..46|prime?(k)]     -- 14 numeri primi da associare a s
F(x,y)==>for i in 1..#x repeat y
F(z,e.(s.i):=z.i)                   -- riempie la tavola associando numeri primi alle lettere "GXUW..."
t:=[1787026,2451,16445,5957,16036207,130169,20372239,495349,20677]  -- prodotto di numeri primi 1787026 dovrebbe essere HEIGHT
h(a)==
     r:=1 ;F(a,r:=r*e.(a.i))        -- calcola il numero associato alla stringa a
     j:=[];F(v,while r rem z.i=0 repeat(r:=r quo t.i;j:=cons(v.i,j)));j:=sort j  -- leva il nome dei numeri che man mano trova, aggiunge a j
     k:=0 ;F(j,k:=k*10+j.i)         -- costruisce il numero decimale k, da j vettore ordinato
     k                              -- ritorna tale numero k
------------------------------------------------------
(8) -> h("IHNEVGENNEISTE")
   (8)  789
                                                    Type: PositiveInteger

```
> 1 votes

---
Tags: code-golf, permutations
---


title: What's my name?

text:
# Question
Title: What's my name?
Given a PPCG User ID, output that user's current username.

# Examples

```
Input -> Output
61563 -> MD XF
2     -> Geoff Dalgas
12012 -> Dennis
foo   ->
-3    ->

```

# Rules

* Input/output can be taken via any allowed means.
* The output must be the full username with proper capitalization and spacing, nothing more and nothing less.
* If the input is not a valid UserID, or the user does not exist, your program should output nothing or error output.
* Your program must work for any valid user, even one created after this challenge.
* Your program does not have to work for the Community user.
* Your program does not have to work for deleted users.
* URL shorteners are disallowed.

# Scoring

Shortest code in each language wins.

# Answer
> 4 votes
# 05AB1E, ~~35~~ 34 bytes

Doesn't work online because of internet restrictions.

### Code

```
’ƒËŠˆ.Â‚‹º.ŒŒ/†š/ÿ’.w'>¡4è5F¦}60F¨

```

### Explanation

The compressed string:

```
’ƒËŠˆ.Â‚‹º.ŒŒ/†š/ÿ’

```

pushes the following string:

```
codegolf.stackexchange.com/users/<input>

```

Whereas `<input>` is the user input. After this, we read all data using `.w` and do some string manipulation tricks on the data:

```
'>¡4è5F¦}60F¨

'>¡             # Split on '>' (Usernames aren't allowed to have '>' so we're safe)
   4è           # Take the 5th element (which is in the header of the HTML page)
     5F¦}       # Remove the first 5 characters, which is "User "
         60F¨   # Remove the last 60 characters, which is:
                  " - Programming Puzzles & Code Golf Stack Exchange</title"
                # Implicitly output the username

```

When run locally, I get the following output:

# Answer
> 8 votes
# Bash, ~~120~~ ~~112~~ ~~106~~ ~~102~~ ~~80~~ ~~76~~ 74 bytes

-8 bytes because `wget` is smart enough to redirect HTTP to HTTPS when necessary
-6 bytes thanks to another `sed` suggestion from Cows quack
-26 bytes thanks to Digital Trauma
-4 bytes thanks to Gilles - `codegolf.stackexchange.com/u/123` redirects
-2 bytes thanks to Digital Trauma's answer's `wget` flags

```
wget -qO- codegolf.stackexchange.com/u/$1|sed -nr 's/.*>User (.*) -.*/\1/p'

```

No TIO link since the TIO arenas can't access the internet.

Thanks to the answers here and the people in chat for helping me with this. I used an approach similar to HyperNeutrino's.

1. `wget -qO- codegolf.stackexchange.com/users/$1` downloads the user's profile page and prints the file to STDOUT. `-q` does it quietly (no speed information).
2. `sed -nr 's/.*User (.*) -.*/\1/p'` searches for the first string `User<space>`, then prints up until it reaches the end of the name, found using `sed` magic.

---

Previous answer that I wrote more independently (102 bytes):

```
wget codegolf.stackexchange.com/users/$1 2>y
sed '6!d' <$1|cut -c 13-|cut -d '&' -f1|sed 's/.\{23\}$//'

```
1. `wget codegolf.stackexchange.com/users/$1 2>y` saves the user profile HTML to a file titled with their UserID and dumps STDERR to `y`.
2. `cat $1` pipes the file into the parts that cut away the useless HTML.
3. `sed '6!d'` (in the place of `head -6 | tail -1`) gets the sixth line by itself.
4. `cut -c 13-` strips away the first 13 characters, getting the username to start at the first character of the string.
5. `cut -d '&' -f1` cuts everything after the `&`. This relies on the fact that an ampersand is not allowed to be in a username, nor an HTML title.
Now the string is `<username> - Programming Puzzles`
6. `sed 's/.\{23\}$//'` was a suggestion from cows quack to remove the last 15 bytes of a file. This gets the username by itself.

Here's a full bash script.

# Answer
> 7 votes
# Bash + GNU utilities, 66

* 3 bytes saved thanks to @Arnauld.
* 4 bytes saved thanks to @Gilles.

```
wget -qO- codegolf.stackexchange.com/u/$1|grep -Po '"User \K[^"]+'

```

Uses `-P`CRE regex flavour to do a `\K` match start reset for much shorter output filtering.

---

If your system already has `curl` installed, we can use @Gilles' suggestion:

# Bash + curl + GNU utilities, 64

```
curl -L codegolf.stackexchange.com/u/$1|grep -Po '"User \K[^"]+'

```

# Answer
> 6 votes
# Python 2 + requests, 108 bytes

```
from requests import*
t=get('http://codegolf.stackexchange.com/u/'+input()).text
print t[49:t.index('&')-23]

```

### note

once SE goes fully `https`, the `http` needs to be changed to `https`, which will make this 113 bytes.

The beginning of a user profile looks like this:

```
<!DOCTYPE html>
<html>

<head>

<title>User MD XF - Programming Puzzles & Code Golf Stack Exchange</title>

```

The username starts at index 49 and the ampersand occurs 23 characters to the right of where it ends ( `- Programming Puzzles`)

-3 bytes thanks to StepHen/Mego by removing the unused `re` import
-1 byte thanks to Uriel
-4 bytes thanks to Makonede

# Answer
> 5 votes
# JavaScript (ES6), ~~111~~ 75 bytes

Only works when run through the PPCG domain. Returns a `Promise` object containing the username.

```
i=>fetch("/users/"+i).then(r=>r.text()).then(t=>t.slice(44,t.search`&`-23))

```
* Thanks to Downgoat for confirming that the alternative method I was toying with was valid, thus allowing me to save 36 bytes.

# Answer
> 4 votes
# Cubically \+ Bash, ~~1654~~ ~~1336~~ 1231 bytes

-423 bytes thanks to TehPers

This needs three Cubically scripts (named `1`, `2` and `3`) and 1 bash script.

The Cubically scripts are *really* long because I haven't thought of a good way to implement loops yet.

Bash (84 bytes):

```
ln -s rubiks-lang /bin/r
r 1 <<<$1 2>y|xargs wget 2>y
cat $1|r 2 2>y|rev|r 3 2>y|rev

```

This pipes the first Cubically script into `wget`, then the saved file into the second Cubically script, then reverses that output, pipes it into the third Cubically script, then reverses it.

`1` (385 bytes):

```
+5/1+551@6:5+3/1+552@66:4/1+552@6:5+2/1+552@6:4/1+51@6:2/1+5@66:5+51@6:3/1+552@6:1/1+551@6:2/1+551@6:4/1+551@6:3/1+552@6:5+52@6:3/1+551@6:1/1+5@6:5+2/1+552@6:5+3/1+552@6:5+2/1+55@6:5+51@6:5+3/1+551@6:2/1+551@6:3/1+553@6:5+51@6:5/1+551@6:5+2/1+55@6:2/1+552@6:4/1+551@6:2/1+551@6:1/1+5@6:5+51@6:3/1+552@6:1/1+552@6:2/1+5@6:5+53@6:5+2/1+552@6:2/1+551@6:5+1/1+552@6:5+2/1+552@6:2/1+5@6$7%7

```

This prints `https://codegolf.stackexchange.com/users/`, then the first integer of input.

`2` (~~680~~ 505 bytes):

```
~7777777777777777777777777777777777777777777777777
F1R1
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6

```

This reads the unnecessary data from the saved file as input, then prints up until the ampersand in `Programming Puzzles & Code Golf`.

`~7@7` reads a character and prints it. `F1R1` and `:5=7` check if the input is the ampersand. `&6` exits if it is.

`~7@7:5=7&6` is repeated 45 times because there are 15 bytes of unnecessary data and a 30-byte max StackExchange username.

3 (~~505~~ ~~446~~ 342 bytes):

```
U3D1R3L1F3B1U1D3
~777777777777777777777777
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7

```

Very similar to the last script, this reads the first few unnecessary bytes, then `cat`s until EOF. This also works due to the max SE username.

# Answer
> 4 votes
# Swift 3, 233 bytes

```
import Foundation;func f(i:String){let s=try!String(contentsOf:URL(string:"http://codegolf.stackexchange.com/users/"+i)!,encoding:.utf8);print(s[s.index(s.startIndex,offsetBy:44)...s.index(s.characters.index(of:"&")!,offsetBy:-24)])}

```

Sample runs:

```
f(i:"8478") // Martin Ender
f(i:"12012") // Dennis
f(i:"59487") // Mr. Xcoder

```

# Answer
> 3 votes
# Python 2, 116 bytes

Just thought it's nice to have a standard library answer (that's actually quite decent in length).

```
from urllib import*
f=urlopen('http://codegolf.stackexchange.com/users/'+input()).read()
print f[49:f.index('&')-23]

```

When SE goes fully `https`, we need to add 1 more byte, switching `urlopen('http://...` with `urlopen('https://...`.

# Answer
> 3 votes
# Stack Exchange Data Explorer, 47 bytes

```
SELECT DISPLAYNAME FROM USERS WHERE ID=##N##--N

```

Try it online!

# Answer
> 2 votes
# Powershell, ~~165~~ ~~142~~ ~~137~~ 127 bytes

*~~23~~ ~~28~~ 38 bytes saved thanks to AdmBorkBork!*

Creates a file named `0` as a side effect.

```
((iwr"codegolf.stackexchange.com/u/$args").AllElements|?{$_.class-like"user-c*"})[1].innerhtml-match"(.+?) ?<|.+">0
$matches[1]

```

Works by going to the proper webpage, and selecting the "user-card-name" element, then extracting the proper text out of the innerhtml.

## Testing

```
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 61563
MD XF
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 2
Geoff Dalgas
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 12012
Dennis
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 foo
Invoke-WebRequest : current community chat Programming Puzzles & Code Golf
Programming Puzzles & Code Golf Meta your communities Sign up or log in to customize your list. more stack
exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour
Start here for a quick overview of the site Help Center
Detailed answers to any questions you might have Meta
Discuss the workings and policies of this site About Us
Learn more about Stack Overflow the company Business
Learn more about hiring developers or posting ads with us
Programming Puzzles & Code Golf Questions Tags Users Badges Unanswered Ask Question
 Page Not FoundWe're sorry, we couldn't find the page you requested.
Try searching for similar questions
Browse our recent questions
Browse our popular tags
If you feel something is missing that should be here, contact us.
about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback
Technology Life / Arts Culture / Recreation Science Other
Stack Overflow
Server Fault
Super User
Web Applications
Ask Ubuntu
Webmasters
Game Development
TeX - LaTeX
Software Engineering
Unix & Linux
Ask Different (Apple)
WordPress Development
Geographic Information Systems
Electrical Engineering
Android Enthusiasts
Information Security
Database Administrators
Drupal Answers
SharePoint
User Experience
Mathematica
Salesforce
ExpressionEngine® Answers
Blender
Network Engineering
Cryptography
Code Review
Magento
Software Recommendations
Signal Processing
Emacs
Raspberry Pi
Programming Puzzles & Code Golf
Ethereum
Data Science
Arduino
more (26)
Photography
Science Fiction & Fantasy
Graphic Design
Movies & TV
Music: Practice & Theory
Worldbuilding
Seasoned Advice (cooking)
Home Improvement
Personal Finance & Money
Academia
Law
more (17)
English Language & Usage
Skeptics
Mi Yodeya (Judaism)
Travel
Christianity
English Language Learners
Japanese Language
Arqade (gaming)
Bicycles
Role-playing Games
Anime & Manga
Puzzling
Motor Vehicle Maintenance & Repair
more (32)
MathOverflow
Mathematics
Cross Validated (stats)
Theoretical Computer Science
Physics
Chemistry
Biology
Computer Science
Philosophy
more (10)
Meta Stack Exchange
Stack Apps
Area 51
Stack Overflow Talent
site design / logo © 2017 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution
required rev 2017.8.1.26652
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:1 char:3
+ ((Invoke-WebRequest -URI("codegolf.stackexchange.com/users/"+$args[0])).AllEleme ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], We
   bException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Cannot index into a null array.
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:2 char:1
+ $matches[1]
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 -3
Invoke-WebRequest : current community chat Programming Puzzles & Code Golf
Programming Puzzles & Code Golf Meta your communities Sign up or log in to customize your list. more stack
exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour
Start here for a quick overview of the site Help Center
Detailed answers to any questions you might have Meta
Discuss the workings and policies of this site About Us
Learn more about Stack Overflow the company Business
Learn more about hiring developers or posting ads with us
Programming Puzzles & Code Golf Questions Tags Users Badges Unanswered Ask Question
 Page Not FoundWe're sorry, we couldn't find the page you requested.
Try searching for similar questions
Browse our recent questions
Browse our popular tags
If you feel something is missing that should be here, contact us.
about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback
Technology Life / Arts Culture / Recreation Science Other
Stack Overflow
Server Fault
Super User
Web Applications
Ask Ubuntu
Webmasters
Game Development
TeX - LaTeX
Software Engineering
Unix & Linux
Ask Different (Apple)
WordPress Development
Geographic Information Systems
Electrical Engineering
Android Enthusiasts
Information Security
Database Administrators
Drupal Answers
SharePoint
User Experience
Mathematica
Salesforce
ExpressionEngine® Answers
Blender
Network Engineering
Cryptography
Code Review
Magento
Software Recommendations
Signal Processing
Emacs
Raspberry Pi
Programming Puzzles & Code Golf
Ethereum
Data Science
Arduino
more (26)
Photography
Science Fiction & Fantasy
Graphic Design
Movies & TV
Music: Practice & Theory
Worldbuilding
Seasoned Advice (cooking)
Home Improvement
Personal Finance & Money
Academia
Law
more (17)
English Language & Usage
Skeptics
Mi Yodeya (Judaism)
Travel
Christianity
English Language Learners
Japanese Language
Arqade (gaming)
Bicycles
Role-playing Games
Anime & Manga
Puzzling
Motor Vehicle Maintenance & Repair
more (32)
MathOverflow
Mathematics
Cross Validated (stats)
Theoretical Computer Science
Physics
Chemistry
Biology
Computer Science
Philosophy
more (10)
Meta Stack Exchange
Stack Apps
Area 51
Stack Overflow Talent
site design / logo © 2017 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution
required rev 2017.8.1.26652
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:1 char:3
+ ((Invoke-WebRequest -URI("codegolf.stackexchange.com/users/"+$args[0])).AllEleme ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], We
   bException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Cannot index into a null array.
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:2 char:1
+ $matches[1]
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

PS C:\Users\Conor O'Brien\Documents\powershell>

```

# Answer
> 2 votes
## PHP, 163 bytes

---

```
<?php $a=new DOMDocument;@$a->loadHTML(implode(0,file("http://codegolf.stackexchange.com/users/$argv[1]")));echo$a->getElementsByTagName('h2')->item(0)->nodeValue;

```

# Answer
> 1 votes
# Python \+ `requests`, 126 bytes

```
lambda n:get('http://api.stackexchange.com/users/%d?site=codegolf'%n).json()['items'][0]['display_name']
from requests import*

```

Accessing the API is longer than reading the actual page apparently...

# Answer
> 1 votes
# Jelly, 37 bytes

A port of HyperNeutrino's Python 2 answer \- go give credit!

```
“3¬ẋṙẉṀḷo°ɓẏ8YyŒÇḣðk¦»;ŒGṾṫ51ṣ”&Ḣḣ-23

```

A monadic link taking a number and returning a list of characters; as a full program prints the result.

Note: not sure quite why the result of `ŒG` needs to be forced to become a string (done here with ) :/

### How?

```
“3¬ẋṙẉṀḷo°ɓẏ8YyŒÇḣðk¦» = compression of:
                         "code"+"golf"+"."+"stack"+"exchange"+".com/"+"user"+"s/"

```

codegolf.stackexchange.com/users/

```
“...»;ŒGṾṫ51ṣ”&Ḣḣ-23 - Main link: number, n
“...»                - "codegolf.stackexchange.com/users/"
     ;               - concatenate with n
      ŒG             - GET request (should be to string & looks like it on output)
        Ṿ            - uneval (force to a string - shrug)
         ṫ51         - tail from index 51 (seems the ŒG result is quoted too, so 51 not 50)
            ṣ”&      - split on '&'
               Ḣ     - head (get the first chunk)
                ḣ-23 - head to index -23 (discard the last 23 characters)

```

# Answer
> 0 votes
# Mathematica, 126 bytes

```
StringTake[#&@@StringCases[Import["https://codegolf.stackexchange.com/users/"<>ToString@#,"Text"],"r "~~ __ ~~" - P"],{3,-4}]&

```

**input**

> \[67961\]

**output**

> Jenny\_mathy

# Answer
> 0 votes
# Stratos, 22 bytes

```
f"¹⁸s/%²"r"⁷s"@0s"³_⁴"

```

Try it!

Explanation:

```
f"¹⁸s/%?"               Read the data from the URL:
                        http://api.stackexchange.com/users/%?site=codegolf
                        where % is replaced with the input
         r              Get the JSON array named
          "⁷s"          items
              @0        Get the 0th element
                 s"³_⁴" Get the string "display_name"

```

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


title: The greedy regex (robbers)

text:
# Question
Title: The greedy regex (robbers)
*This is the robbers' post. The cops' is here.*

Your challenge is to take a cop's post and find an input that the regex matches but the program returns a falsey value.

Once you have cracked a cop's post, comment in a link to your crack. (If you don't have enough rep to comment, please say so, and someone will do it for you.) The robber with the most cracks wins.

## Example

Let's say a cop's regex is (all of the flavors):

```
/^[0-9]$/

```

And the program is (JS):

```
x=>Boolean(parseInt(x))

```

Than a valid crack would be `0`, because the regex matches `0` but `0` is falsey.

# Answer
> 2 votes
# Python 3, pperry

```
İ

```

Try it online!

The lower case variant  of this character is created by a an `i` and a ċȯṁḃi̇̇ṅi̇̇ṅġ ḋȯṫ which results in a length of 2.

# Answer
> 2 votes
# Python, ppperry

```
\n

```

Try it online!

`.` doesn't match newline by default.

# Answer
> 1 votes
# JavaScript, ThePirateBay

Solution:

Try it online!

# Answer
> 0 votes
# Java, Roman Gräf

```
is.is.is.is.

```

Try it online!

Most things which match the regex crack it, so I'm not sure if the regex is what was intended

---
Tags: string, code-challenge, cops-and-robbers, regular-expression
---