title: Rest of the path

text:
# Question
Title: Rest of the path
Consider this file path:

```
C:/Users/Martin/Desktop/BackupFiles/PC1/images/cars/new.png

```

Your goal is to write a program that will return the file path starting from the folder after the last folder that contains a number till the filename. So, for the above file path, the program should return `images/cars/new.png`.

One or more of the folder names may also contain spaces:

```
C:/Users/User1/Documents/Books/eBooks/PM2.4/ref/Project Management.pdf

```

should return `ref/Project Management.pdf`.

Also this filepath:

```
C:/Users/John/Videos/YouTube/3D/Animations/52.Tricky.Maneuvers/video234.png

```

should return `video234.png`.

Your answer should work with the above given three examples and all other examples that match the criteria described here.

This is , so the answer with the lowest number of bytes yields victory.

I am new to the site, so feel free to modify my post and/or add relevant tags.

# Answer
> 2 votes
# Retina, 9 bytes

```
.*\d.*?/

```

Regex is ported from *@Arnauld*'s JavaScript answer, so make sure to upvote him!

Try it online.

**Explanation:**

```
.*\d.*?/    # Main regex:
.*          #  Zero or more characters (as much as possible)
  \d        #  Followed by a digit
    .*?     #  Followed by zero or more optional characters (as few as possible)
       /    #  Followed by a slash

            # Replace the match with:
            #  Nothing (so basically remove that leading part)

```

# Answer
> 7 votes
# JavaScript (ES6), ~~29~~ 28 bytes

*Saved 1 byte thanks to @tsh*

```
s=>s.replace(/.*\d.*?\//,'')

```

Try it online!

### How?

```
                                             /.*\d.*?\//
                                              \/\/\_/\/
                                              | |  | |
match the longest possible string (greedy) ---+ |  | |
match a digit ----------------------------------+  | |
match the shortest possible string (lazy) ---------+ |
match a slash ---------------------------------------+

```

# Answer
> 7 votes
# Gema, 8 bytes

```
*<D>*\/=

```

Sample run:

```
bash-4.4$ gema '*<D>*\/=' <<< 'C:/Users/Martin/Desktop/BackupFiles/PC1/images/cars/new.png'
images/cars/new.png

bash-4.4$ gema '*<D>*\/=' <<< 'C:/Users/User1/Documents/Books/eBooks/PM2.4/ref/Project Management.pdf'
ref/Project Management.pdf

bash-4.4$ gema '*<D>*\/=' <<< 'C:/Users/John/Videos/YouTube/3D/Animations/52.Tricky.Maneuvers/video234.png'
video234.png

```

Try it online!

# Answer
> 4 votes
# sed, 17 bytes

```
s:.*[0-9][^/]*/::

```

Try it online.

# Answer
> 4 votes
# 05AB1E, 23 bytes

```
'/©¡RćUηí®ýʒþd_}®«õš¤X«

```

Try it online or verify all test cases.

05AB1E has no regexes, so this is not the kind of challenge it will do very good, in comparison to non-verbose languages that have a strength in regexes like Retina or Pyth.
Can probably still be golfed by at least a few bytes, though.

**Explanation:**

```
'/              # Push a "/"
  ©             # Store it in the register (without popping)
   ¡            # Split the (implicit) input on slashes
                #  i.e. "C:/Desktop3/Stuff/F0/images/new1.png"
                #   → ["C:","Desktop3","Stuff","F0","images","new1.png"]
    R           # Reverse this list
                #  i.e. ["C:","Desktop3","Stuff","F0","images","new1.png"]
                #   → ["new1.png","images","F0","Stuff","Desktop3","C:"]
     ć          # Head extracted
                #  i.e. ["new1.png","images","F0","Stuff","Desktop3","C:"]
                #   → ["images","F0","Stuff","Desktop3","C:"] and "new1.png"
      U         # Pop the extracted head, and store it in variable `X`
       η        # Take the prefixes of the list
                #  i.e. ["images","F0","Stuff","Desktop3","C:"]
                #   → [["images"],["images","F0"],["images","F0","Stuff"],["images","F0","Stuff","Desktop3"],["images","F0","Stuff","Desktop3","C:"]]
        í       # Reverse each inner list again
                #  i.e. [["images"],["images","F0"],["images","F0","Stuff"],["images","F0","Stuff","Desktop3"],["images","F0","Stuff","Desktop3","C:"]]
                #   → [["images"],["F0","images"],["Stuff","F0","images"],["Desktop3","Stuff","F0","images"],["C:","Desktop3","Stuff","F0","images"]]
         ®ý     # And join them by slashes
                #  i.e. [["images"],["F0","images"],["Stuff","F0","images"],["Desktop3","Stuff","F0","images"],["C:","Desktop3","Stuff","F0","images"]]
                #   → ["images","F0/images","Stuff/F0/images","Desktop3/Stuff/F0/images","C:/Desktop3/Stuff/F0/images"]
ʒ   }           # Now filter this list by:
 þ              #  Leave only the digits of this suffix
                #   i.e. "images" → ""
                #   i.e. "Stuff/F0/images" → 0
  d             #  Check if its >= 0
                #   i.e. "" → 0 (falsey)
                #   i.e. 0 → 1 (truthy)
   _            #  Inverse the boolean (0→1; 1→0)
     ®«         # Append a slash to each remaining suffix
                #  i.e. ["images"] → ["images/"]
       õš       # Prepend an empty string as list
                # (work-around when there are no valid suffices left)
                #  i.e. [] → [""]
                #  i.e. ["images/"] → ["","images/"]
         ¤      # Take the last suffix
                #  i.e. ["","images/"] → "images/"
          X«    # Append variable `X` (and implicitly output the result)
                #  i.e. "images/" and "new1.png" → "images/new1.png"

```

# Answer
> 3 votes
# Powershell 42 39 45 30 26 bytes

Find the last decimal before a /, fetch all after the slash as the new path

```
($args-split'.*\d.*?/')[1]

```

Try it out!

\- many bytes by tips from @mazzy
\- 1 byte by removing non-required regex escape
\- 4 bytes as the regex with -split didn't require a group
\- added greedy decimal search

# Answer
> 3 votes
# Java (JDK 10), 26 bytes

```
s->s.split(".*\\d.*?/")[1]

```

Try it online!

# Answer
> 3 votes
# Ruby, 22 bytes

```
->s{s=~/.*\d.*?\//;$'}

```

Try it online!

Same trick as Arnauld and everybody else after him.

# Answer
> 2 votes
# Jelly, 16 bytes

```
”/ɓṣṖf€ØDTṀ‘ṫ@ṣj

```

A monadic Link accepting a list of characters which returns a list of characters.

**Try it online!**

### How?

```
”/ɓṣṖf€ØDTṀ‘ṫ@ṣj - Link: list of characters X
”/               - literal '/' character
  ɓ              - start a new dyadic chain with swapped arguments - i.e. f(X,'/')
   ṣ             - split (X) at ('/')
    Ṗ            - pop (removes the rightmost)
       ØD        - yield digit characters
      €          - for each: (of the parts of X after the split & pop)
     f           -   filter keep (digit characters)
         T       - truthy indices (1-indexed indices of parts containing any digit(s))
          Ṁ      - maximum (rightmost, zero if not found)
           ‘     - increment
              ṣ  - split (X) at ('/') (...again)
             @   - with swapped arguments:
            ṫ    -   tail (the split X) from index (the incremented maximum...)
               j - join with ('/')

```

# Answer
> 2 votes
# Python 2, 74 bytes

```
r='';k=1
for c in input():
 r+=c;k-=c.isdigit()
 if'/'==c:r*=k;k=1
print r

```

Try it online!

---

# Python 2, 42 bytes

```
lambda n:re.sub(".*\d.*?/","",n)
import re

```

Try it online!

# Answer
> 2 votes
# Red, 79 bytes

```
func[s][d: charset"0123456789"parse s[any[to d thru"/"]copy t to end(print t)]]

```

Try it online!

# Answer
> 2 votes
## Pyth, 14 bytes

The same regex solution that everybody else is using:

```
:z"^.*\d.*?/""

:                     regex replace
 z                    in the input() string
  "^.*\d.*?/"         the file path up until the last path with a number
             "        with an empty string (Pyth terminates this string at end of program)

```

# Answer
> 2 votes
# Pip, 12 bytes

```
a@`\d.*?/`$'

```

Takes input as a command-line argument. Verify all test cases: Try it online!

### Explanation

Does ***not*** use the same regex as everyone else! (Well, okay, it's pretty similar.)

```
a             1st command-line argument
  `\d.*?/`    Regex matching a digit, as few characters as possible, and then a slash
 @            Find all matches
          $'  Special variable: the portion of the string after the last match
              Autoprint

```

---

The shortest solutions using the standard regex were all 13 bytes:

```
aRM`.*\d.*?/`   Remove
a|>`.*\d.*?/`   Left-strip
aR`.*\d.*?/`x   Replace with empty string

```

# Answer
> 1 votes
## Matlab, 68 bytes

```
function[r]=f(s),[~,b]=regexp(s,'/[^/;]+\d[^/;]+/');r=s(b+1:end);end

```

Try it Online!

# Answer
> 1 votes
## PHP 4 (42 chars)

Given *$argv\[1\]*, it will silence the **end**'s “*Only variables should be passed by reference*” notice.

```
echo@end(preg_split(';\d.*?/;',$argv[1]));

```

# Answer
> 1 votes
# C, ~~103~~ ~~100~~ 88 bytes

```
*a(b,l)char*b;{for(b+=l;!isdigit(*b);b--);for(;*b-47&&*b;b++);for(;*b-47;b--);return b;}

```

Try online!

-22 bytes thanks to @ceilingcat

Note: the function may have undefined behavior if the string doesn't contain a number and a "/" character!

## Ungolfed version

```
*a(b,l)char*b; /* b:the string, l:the length of the string */
{
    for(b += l; !isdigit(*b); b--); /* start from the end of the string and decrement pointer until a number is found */
    for(; *b-47 && *b; b++); /*increment pointer until '/' (ascii value 47) is found*/
    for(; *b-47; b--); /* decrement pointer until '/' is found */
    return b;
}

```

# Answer
> 0 votes
# Perl 5 `-p`, 13 bytes

*12 bytes for code; +1 for -p switch*

```
s!.*\d.*?/!!

```

Try it online!

I solemnly swear I came up with my own solution before reading other answers.

---
Tags: code-golf, file-system
---


title: Output two numbers (Cops' thread)

text:
# Question
Title: Output two numbers (Cops' thread)
> This is the cops' thread to a challenge. Click the link to find the robbers' thread.

The challenge here is very simple. Create two programs of the same size, in the same language, which output (using 1 standard output method) two different natural numbers, \\$x\\$ and \\$y\\$. Submit both programs, both numbers and the language used in an answer on this thread.

Robbers will then attempt to find a program in the same language which outputs a number in between \\$x\\$ and \\$y\\$, and is the same length as or shorter than your programs. If they do, they will post it to the robbers' thread, and it is "cracked".

For example If I post:

> # Haskell, \\$9-7 = 2\\$, 12 bytes
>
> ```
> main=print 7
>
> ```
>
> ```
> main=print 9
>
> ```

Then robbers must find a program that prints `8` in 12 bytes or fewer.

Unlike many challenges in cop's do not need to have an answer in mind when posting. It is perfectly valid to post an answer which *cannot* be cracked at all. In fact that is incentivized. However the scoring means that the better you score the harder it will be to prevent a crack.

## Scoring

Your score will be the difference between \\$x\\$ and \\$y\\$. So in the example answer it was \\$2\\$. Higher score is better. If your answer is cracked it's score is automatically set to 0.

Since there is no hidden information that needs to be revealed, answers will not be marked as safe. You get your score as soon as you post the answer and it will remain your score until someone cracks it.

# Answer
> 27 votes
# Zsh, 1 byte, score 124, provably uncrackable

Programs output via exit code.

```
/
```

Outputs 126 ("permission denied"). Attempt This Online!

```
[
```

Outputs 2 ("invalid argument"). Attempt This Online!

Here is a script which tests all 256 possible 1-byte programs, which you can use to verify that this is uncrackable (and unbeatable for 1-byters):

```
{ for c ({0..255}) ( zsh -c ${(#)c} &>/dev/null; echo $? ) } | sort -n
```

Attempt This Online!

The empty program exits with 0.

# Answer
> 13 votes
# Malbolge, 7 bytes. Score: 3 - 1 = 2. Cracked.

```
D'<;_L"

```

Outputs 3.

```
(&a%M"o

```

Outputs 1.

# Answer
> 8 votes
# , 5 bytes, score: 10^307

```
1e308

```

Try it online!

```
9e307

```

Try it online!

`2e308` overflows 's numeric type, and outputs `Inf`, so I suppose that `1e308` is the highest number that we can output using 5 bytes.

---

# , 4 bytes, score: 9 x 10^98, cracked, almost instantly

```
1e99

```

Try it online!

```
1e98

```

Try it online!

Note after crack: Well, that was pretty stupid of me.

# Answer
> 8 votes
# C, 24 bytes, score 33482810471

Output format is *decimal*.

```
main(){printf("%o",~9);}

```

Outputs 37777777766. Try it online!

```
main(){printf("%u",-1);}

```

Outputs 4294967295. Try it online!

Uncrackable?

# Answer
> 8 votes
# Excel, 10 bytes, score (145!)-(144!) 0 Cracked!

I'm interested to see how this can be cracked.

```
=FACT(145)
```

Outputs 8.04792605747199E+251 (actually prints every digit when in "Number" format and a very wide column/merged columns, the most I could get it to print before they became ##### or #NUM!

```
=FACT(144)
```

Outputs 5.55029383273931E+249 (again, actually prints every digit \[although it does turn most to 0's\])

But... if you think it's okay if I can use un-printable numbers (likely not)

# Excel, 10 bytes, score (999999999!)-(999999998!)

```
=FACT(999999999)

```

Output is approximately 1e8448735636

```
=FACT(999999998)

```

Output is approximately (1e8448735636)/999999999

# Answer
> 6 votes
# Charcoal, 2 bytes, score: 1000 - 99 = 901

```
Ｉφ

```

Outputs 1000. Try it online! Link is to verbose version of code.

```
99

```

Outputs 99. Try it online!

# Answer
> 6 votes
# Vyxal 2.8.1, online edition, Score: \\$no\\$, 102 bytes - cracked

Our two programs are:

```
kḭkḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(kḭ(↵

```

which is equivalent to:

```
stack.append(4294967296)
for i in range(4294967296):
  for j in range(4294967296):
     for l in range(4294967296):
         ...
           stack.append(10 ** stack.pop())

```

and

```
k×k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(k×(↵

```

```
stack.append(2147483648)
for i in range(2147483648):
  for j in range(2147483648):
     for l in range(2147483648):
         ...
           stack.append(10 ** stack.pop())

```

These both output really big numbers, which I need to calculate. Online edition here means that it should be able to work on the online version of the interpreter if given enough resources and time.

# Answer
> 6 votes
# Jelly, \\$1000 - 256 = 744\\$, 1 byte

This is provably uncrackable. Our programs are

```
ȷ

```

Try it online!

and

Try it online!

These are the following one byte programs in Jelly that output a number:

```
¤¥¬®µ½×ðȷ !$&*+-.0123456789<=>ACEHLNOPSX^_aceghinoquvw|~°¹²³⁴⁵⁹⁻⁼ẠḄḌẸḤỊṂṆẒȦḂĊḞḢṀṠṪạḅḍịḳḷṇṛ§ẉỵẓȧċḋėġṅȯẇẏ«»‘’

```

Try it online!

The two largest outputs are \\$1000\\$ with `ȷ`, then \\$256\\$ with . Nothing else outputs something in between, and the empty program outputs `0`.

# Answer
> 5 votes
# Zsh, 13 bytes, score \\$ \approx 10^{(21 \times 10^6)} \\$, cracked by lynn

```
tr<=go -c 9 9

```

Outputs 13061918 `9`s. Try it online!

```
tr<=z3 -c 1 1

```

Outputs 21366224 `1`s. Try it online!

Exact score:

$$ \frac{10^{21366225} - 1}9 - 10^{13061919} + 1 $$

---

## Explanation

* `<=go`: load the program `go`, as a file
* `tr -c 9 9`: replace all characters except `9`, with `9`s

The other program is similar.

`z3` and `go` are the largest 2-character programs available on TIO, at about 22MB and 14MB respectively. We can use them as an easy source of very long "strings", and by converting all the bytes to digits, very large numbers.

I used TIO instead of ATO because it has much bigger binaries available, and also because ATO is too frequently updated, changing the binaries, so the score would change over time.

I'm not intending for this to be cracked, but I haven't tried very hard to ensure there aren't any cracks.

# Answer
> 4 votes
## Seed 4791 bytes, 9^9^9^9^9^9^9^9^9^9^9 - 9^999

9^999:

```
36                                                                                [encoded data, 4460 characters]

```

This generates the following befunge programs:

```
 "cb 0=HTGNEL_ENIL_CB|'999^9' ohce"=@

```

Thanks to @null for reminding me I know how to program Seed.

The second program becomes:

```
53 [encoded data, 4788 characters]

```

The first one can be padded with spaces to it's length. It expands to the following:

```
"cb 0=HTGNEL_ENIL_CB|'9^9^9^9^9^9^9^9^9^9^9' ohce"=@

```

The score:

\\$10^{10^{10^{10^{10^{10^{10^{10^{10^{8.567841344463465}}}}}}}}}\\$

# Answer
> 4 votes
# Brainf\*ck, 25 bytes. Score = 7 - 4 = 3, cracked by Fmbalbuena

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

```

^ Outputs 7

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

```

^ Outputs 4

I just learned Brainf\***, I think it's going to be an easy crack.

# Answer
> 3 votes
# Brachylog, 5 bytes, score = 61803398875 - 14159265359 = 47644133516

```
φṫb₂ị

```

Try it online!

```
πṫb₂ị

```

Try it online!

### Explanation

Not sure this is crackable:

```
φ        Take Phi = 1.61803398875
π        Or Pi = 3.14159265359
 ṫ       Convert to string
  b₂     Remove the first digit and the decimal separator
    ị    Convert back to integer

```

# Answer
> 3 votes
# MathGolf, 1 byte, score 100000000-10000000=90000000

100,000,000:
10,000,000:

Try it online.

I would be surprised if this is crackable..

# Answer
> 3 votes
# Python 3, 63 bytes, score \\$2\rightarrow12\rightarrow(9^{99}-1)-2\rightarrow11\rightarrow(9^{99}-1)\\$

Program 1:

```
A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
print(A(9**99,8))

```

Try it online!

Program 2:

```
A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
print(A(9**99,9))

```

Try it online!

This just calculates the difference between two nearby invocations of the Ackermann function.

# Answer
> 2 votes
# JavaScript (Node.js), 22 bytes, Score=\\$\frac 19\times 10^{10000000}-\frac 19\\$, cracked

```
x=>'8'.repeat(9999999)

x=>'9'.repeat(9999999)

```

Try it online!

# brainfuck, 19 bytes, Score=\\$3\times 10^{254}\\$, unlikely crackable

```
+[+++++>+<]+[>.<+]

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

```

Try it online!

# Answer
> 2 votes
# Lexurgy, score \\$11111111111111111\\$, 121 bytes

Both programs use the following method:

1. Output a string of 26 digits
2. Make 16 copies of those digits and append them to the end.

### Program 1:

Outputs `9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999988888888888888888` (425 `9`s then 17 `8`s).

```
a:
*=>\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\8
b:
[]$1=>$1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1

```

### Program 2:

Outputs `9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999` (442 `9`s).

```
a:
*=>\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9\9
b:
[]$1=>$1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1 $1

```

## Minimal answer: score \\$9-8=1\\$, 8 bytes

```
# program 1
a:
*=>\8
# program 2
a:
*=>\9

```

# Answer
> 1 votes
# !@#$%^&\*()\_+, 6 bytes, score: 1001001, Cracked by emanresu

```
(#)

```

The first three bytes are char code 127.

Try it online!

```
~~~(#)

```

Try it online!

> You can't see the solution, But this is easy

# Answer
> 1 votes
# MATLAB, 1.797693e+308 - 1.797047e+308 = 6.463132e+304, 7 bytes

```
realmax

```

outputs 1.797693e308

```
5175^83

```

outputs 1.797047e+308

Try it online!

# Answer
> 0 votes
# Python3, 41 bytes, score=\\$2.82×10^{456573}-2.82×10^{446573}\\$, Cracked

```
import math
print(math.factorial(100000))

```

Try it online!

```
import math
print(math.factorial(99999))

```

Try it online!

This is embarrassing i forgot that you can just do 3\*10\**456573

# Answer
> 0 votes
## PHP4, score ≈ 0.011 × 10^1000

**Program 1** (23 chars) output `999` times `9` :

```
echo str_repeat(9,999);

```

**Program 2** (23 chars) output `999` times `8` :

```
echo str_repeat(8,999);

```

Output of both PHP4 scripts is a 999 digits integer in decimal form.

```
var_dump(chop($out_1, '0..9') === ''); // bool(true)
var_dump(chop($out_2, '0..9') === ''); // bool(true)

```

*BC Math is only available if PHP was configured with `--enable-bcmath`, by default there is not.*

---
Tags: number, cops-and-robbers, busy-beaver
---


title: Length-terminated sequences

text:
# Question
Title: Length-terminated sequences
We all know the age-old debate - should strings be length-prefixed or should they be null-terminated? Well, you've run into a blob of binary data and apparently whoever made it decided that the best solution would be a compromise and length-terminated their strings.

For the purposes of this challenge, a length-terminated sequence is a series of one or multiple integers such that the last item in the sequence is equal to the number of items in the sequence, and no prefix of the sequence is also a valid length-terminated sequence. For example, `[1]`, `[15, 2]`, and `[82, 19, 42, 111, 11, 6]` are all valid length-terminated sequences. `[15]` is *not* a valid length-terminated sequence (it hasn't been terminated), and neither is `[15, 2, 3]` (it should have ended at the `2`).

Your task is to write a program or function that takes a list of integers, and outputs all the valid length-terminated sequences within that list. For example, for the input list `[7, 6, 5, 4, 3, 2, 1]`, valid length-terminated sequences would be `[1]`, `[3, 2]`, `[5, 4, 3]` and `[7, 6, 5, 4]`.

* You must output *all* valid length-terminated sequences found in the input, in any order. The order may vary between runs of your program. You must output *no* length-terminated sequences not found within the input, and *no* sequences found within the input that aren't valid length-terminated sequences.
* If some length-terminated sequence occurs multiple times within the input, it should also be output multiple times. The sequence `[9, 8, 3]` occurs twice in the input `[9, 8, 3, 9, 8, 3]` (once starting with the first number, and again starting at the fourth number) and should thus be output twice.
* A number may be part of more than one length-terminated sequence. For example, the input `[9, 9, 2, 4]` contains both the length-terminated sequences `[9, 9, 2, 4]` and `[9, 2]` and they should both be output.
* You may assume all numbers are between 0 and 127 (both inclusive).
* You may assume the input contains no more than 126 numbers.
* You may *not* make any further assumptions about the input, including the assumption that the input contains at least one valid length-terminated sequence.
* You may take input or produce output by any of the default methods. Input and output formats are flexible (within reason) and the input format need not be the same as the output format. However, the your input and output formats must not depend on the input, and must not vary between runs of your program.
* This is - make your code as small as possible.

# Examples

```
[input] -> [output], [output], ...
[7, 6, 5, 4, 3, 2, 1] -> [7, 6, 5, 4], [5, 4, 3], [3, 2], [1]
[90, 80, 70] -> (no output)
[1, 2, 3, 4, 5] -> [1]
[100, 0, 2, 2, 2, 0, 0, 2, 4] -> [0, 2], [2, 2], [2, 2], [0, 0, 2, 4], [0, 2]
[] -> (no output)
[54, 68, 3, 54, 68, 3] -> [54, 68, 3], [54, 68, 3]
[4, 64, 115, 26, 20, 85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30, 83, 70] -> [85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14], [118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37], [109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19], [84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13], [14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30], [45, 118, 45, 51, 91, 116, 7]

```

# Answer
> 9 votes
# Python 2, 67 bytes

```
f=lambda l:l and[l[:x]for i,x in enumerate(l)if-~i==x][:1]+f(l[1:])

```

Try it online!

# Answer
> 8 votes
# Jelly, 9 bytes

```
Ẇ=J$Ḅ⁼ɗƇ1

```

A monadic Link accepting a list of integers which yields a list of lists of integers.

**Try it online!**

Or `ẆĖE€Ḅ⁼ʋƇ1` \- Try it.

### How?

```
Ẇ=J$Ḅ⁼ɗƇ1 - Link: list of integers
Ẇ         - all sublists
        1 - set right argument to 1
       Ƈ  - filter keep those (sublists) for which:
      ɗ   -   last three links as a dyad - i.e. f(sublist, 1):
   $      -     last two links as a monad i.e. g(sublist)
  J       -       range of length = [1,2,3,...,length]
 =        -       (sublist) equals (that)? (vectorises)
    Ḅ     -     from binary
     ⁼    -     (that) equals (1)?

```

# Answer
> 8 votes
# JavaScript (V8), 65 bytes

Prints the results.

```
a=>a.map((_,i)=>a.every((v,j)=>j<i|v-++j+i||print(a.slice(i,j))))

```

Try it online!

### Commented

```
a => a.map((_, i) => // for each value at position i in a[]:
  a.every((v, j) =>  //   for each value v at position j in a[]:
    j < i |          //     yield true and go on with the next iteration if j < i
    v - ++j + i      //     or v is not equal to j - i + 1 (increment j)
    || print(        //     otherwise, print ...
      a.slice(i, j)  //       ... the sublist of a[] from i to j - 1
    )                //     and break (print() returns undefined)
  )                  //   end of every()
)                    // end of map()

```

# Answer
> 8 votes
# Python, 62 bytes

```
f=lambda l:l and[l[:x]for x in l if[x]==l[x-1:x]][:1]+f(l[1:])

```

Try it online!

This is a subtle improvement on @xnor's solution.

The solution we wish we could use is

```
f=lambda l:l and[l[:x]for x in l if x==l[x-1]][:1]+f(l[1:])

```

However, this will crash on an out-of-bounds index. xnor avoided this problem by using the index at which the value `x` appeared rather than actually indexing into `l`, but this required using the expensive `enumerate` function.

Instead, I used `[x-1:x]` to slice out the length-1 slice including the index we're interested in. Slicing in Python is much more permissive with respect to out of bounds errors. Now, we only need to check that the part of the list sliced out is `[x]`.

Works in Python 2 or 3.

# Answer
> 7 votes
# Brachylog, 12 bytes

```
a₁ᶠ{a₀.l~t}ˢ

```

Try it online!

```
a₁ᶠ{      }ˢ    For every suffix of the input, if possible,
    a₀.         find the shortest prefix
       l        the length of which is
      . ~t      its last element.

```

An alternate generator solution using `s`, taking inspiration from Jonathan Allan's Jelly solution:

# Brachylog, ~~13~~ 12 bytes

```
s.i₁ᶠ=ˢ~gh~l

```

Try it online!

```
 .              The output is
s               any substring of the input
  i₁ᶠ           such that a list of all elements paired with their 1-indices
     =ˢ         filtered by equality
       ~g       has only one element, of which
         h      the first element
          ~l    is the length of the output.

```

# Answer
> 5 votes
## Haskell, ~~69~~ 64 bytes

```
((1#)=<<).scanr(:)[]
l#(a:b)|l==a=[[a]]|m<-l+1=(a:)<$>m#b
_#_=[]

```

Edit: -5 bytes thanks to @Sriotchilism O'Zaic

Try it online!

# Answer
> 5 votes
# Prolog (SWI), 67 bytes

```
X-Y:-X+Y+1.
[_|X]-Y:-X-Y.
[H|T]+[H|X]+N:-X=[],N=H,!;M is N+1,T+X+M.

```

Try it online!

Uses the `-/2` predicate.

There are two parts to the code.

```
[H|T]+[H|X]+N:-X=[],N=H,!;M is N+1,T+X+M.

```

Essentially computes the shortest prefix that end in its length. However it only does this when called with `X+Y+1`.

Then we have the main predicate `-/2`

```
X-Y:-X+Y+1.
[_|X]-Y:-X-Y.

```

This matches all the prefixes of `X` than end in their length:

```
X-Y:-X+Y+1.

```

and anything that matches the tail of `X`.

```
[_|X]-Y:-X-Y.

```

That turns our predicate over prefixes to a predicate over sublists.

# Answer
> 5 votes
# Haskell, 59 bytes

```
(>>= \l->take 1[take x l|(i,x)<-zip[1..]l,i==x]).scanr(:)[]

```

Try it online!

**60 bytes**

```
f l@(h:t)=take 1[take x l|(i,x)<-zip[1..]l,i==x]++f t
f _=[]

```

Try it online!

# Answer
> 4 votes
# Perl 5, 59 bytes

```
/(?<!\d).*?\b(\d++)(??{$1^1+$&=~y, ,,||"(*PRUNE)".say$&})^/

```

Try it online!

# Answer
> 3 votes
# Charcoal, 38 bytes

```
ＩＥΦＬθ∧‹§θι⁺²ι⬤✂θ⁻⊕ι§θιι¹⁻λ⊕μ✂θ⁻⊕ι§θι⊕ι

```

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

```
    θ                                   Input array
   Ｌ                                    Length
  Φ                                     Filter over implicit range
       §θι                              Value at current index
      ‹                                 Is less than
          ⁺²ι                           Current index plus 2
     ∧                                  And
             ⬤                          For all elements of
              ✂θ                        Slice of input array
                ⁻⊕ι§θι                  From potential sequence start
                      ι¹                To current index
                         λ              Value
                        ⁻               Does not equal
                          ⊕μ            1-indexed index
 Ｅ                                      Map over matching indices
                            ✂θ⁻⊕ι§θι⊕ι  Extract sequence including length
Ｉ                                       Cast to string for implicit print

```

# Answer
> 2 votes
# , <sup>~~28~~</sup> 22 bytes

```
a:-.~((#={:)\{.@#<\)\.

```

Try it online!

Take the empty boxes `a:` away from `-.~` the following result:

For each postfix of the input `\.` do the following:

Filter `#` the boxed prefixes of the current input `<\` using the boolean mask which asks, also for each prefix of the current input, "Is the length equal to the last item?" `(#={:)\`.

From those boxed prefixes that *do* pass the filter, take the first one `{.@`. If *no* prefixes pass the filter, this will return the empty box `a:` (ie, the zero value of a list of boxes).

Note for J-ers: The function always returns a list of boxes, each of which contains a list of numbers. This (desirable) consistency is what creates some of the seeming inconsistencies required to correctly specify the expected values of the test cases:

* `(,:1)` -- a list containing 1
* `,:<,:1` -- a boxed list containing the list containing 1 (remember: a single box is an atom)

# Answer
> 2 votes
# C (clang), ~~101~~ ~~98~~ ~~97~~ 95 bytes

```
j;f(*l,z){for(l+=z;z;)if((j=-*--l)&&j>~z--&&j-~l[-1]|!z)for(puts("");printf("%d ",l[++j])*j;);}

```

Try it online!

-1 thanks to @ceilingcat

```
j;
f(*l,z){ // function taking a pointer and size
for(l+=z;z;) // move pointer to the end for backward iteration
if( // cascaded conditions :
  (j=-*--l) // skip if value is 0 while assigning to j its negation
  &&j>~z-- // skip if j>z ( before array begins)
  &&j-~l[-1] // skip if previous value is 1 less than value
  |!z // if z =0 previous value doesn't care
)
for(puts("") // newline to separate lists obtained
   ;printf("%d ",l[++j]) // print each value from j before l position
    *j;);} // to l (j=0)

```

# Answer
> 2 votes
# Japt `-mR`, 12 bytes

```
WsV
¯ÒUbÈÉ¶Y

```

Try it

```
-mR         //Map each element in the input to the following program, and join with newlines
            //U is the element being mapped over
            //V is the index
            //And W is the original array
WsV         //Set U to the original array, removing the first V(index) elements
¯           //Take the first n elements, where n is the following:
   Ub       //  The first index in U which satisfies the following condition
     ÈÉ¶Y   //    Where the element at that index minus one equals the index
  Ò         //   Add 1 to that result

```

# Answer
> 2 votes
# Ruby, ~~72~~ 70 bytes

-2 bytes by somehow typing `a.length` instead of `a.size` when constructing the range, but still using the correct function later down the line when checking the sequences.

```
->a{(r=0..a.size).map{|i|r.map{|j|a[i,j]}.find{|s|s[-1]==s.size}}-[p]}

```

Try it online!

# Answer
> 2 votes
# Perl 6, 40 bytes

```
{~<<m:ov/(<<\d+>>)+?%\s<!{$0-$0.tail}>/}

```

Try it online!

Regex-based approach working with strings of space-separated numbers.

**35 bytes** when working directly with ASCII strings:

```
{~<<m:ov/(.)+?<!{$0-$0.tail.ord}>/}

```

Try it online!

### Explanation

```
{                                      }  # Anonymous block
    m:ov/                             /   # Find all overlapping matches
          <<       # Left word boundary
            \d+    # One or more digits
               >>  # Right word boundary
         (       )+?     # One or more numbers, lazy
                    %\s  # Separated by space
                       <!{          }>  # Negative boolean condition check
                          $0-$0.tail    # Count of numbers minus last number
 ~<<  # Stringify matches

```

# Answer
> 2 votes
# Curry, 33 bytes

Tested in both KiCS2 and PAKCS.

```
f(_++u++x:_)|x==1+length u=u++[x]

```

Curry's powerful patterns let it beat the Haskell answer once again!

To test it you can use Smap. Just select `KiCS2 2.2.0` or `PAKCS 2.2.0` with the `/all-values` option and paste the following complete code:

```
f(_++u++x:_)|x==1+length u=u++[x]
main=f [7, 6, 5, 4, 3, 2, 1]

```

# Answer
> 1 votes
# Python 3, 98 bytes

```
lambda s,e=enumerate:[s[i-n:i]for i,n in e([9]+s)if all(m+~j for j,m in e(s[i-n:i-1]))>0<n<=i]

```

Try it online!

Takes the input as a list and maps it to a list of lists where each item is a sublist of length `n` ending with item `n` for each item. Then it is filtered so that no list contains other valid length terminators.

-4 bytes thanks to Jonathan Frech

# Answer
> 1 votes
# PHP, 90 bytes

```
for(;++$i<$c=count($argv);)for($j=$i;$c>$j;$j-$i-$n?:$c=print_r($$i))$$i[]=$n=$argv[$j++];

```

Try it online!

Input sequence is sent using command arguments (each number is one argument) and output is string representation of arrays using PHP's print\_r.

```
for(;                  // outer loop on $argv input items
  ++$i<                // $i is current index, starts from second item as PHP fills first item with script's name
  $c=count($argv);     // $c is total number of input items
)
  for(                 // inner loop on input items
    $j=$i;             // $j is inner loop's index, always starts from outer loop's index
    $c>$j;             // continue while inner index is less than $c
    $j-$i-$n?:         // THIS IS RUN LAST: if current number ($n) is equal to $j-$i ($j is incremented by one already, so $j-$i gives a position starting from 1 in the $$i)
       $c=print_r($$i) // THIS IS RUN LAST: print the $$i array and set $c to 1 to break the inner loop
  )
    $$i[]=             // THIS IS RUN FIRST: push into an array named by value of $i (if $i=2, variable name is 2)
    $n=$argv[$j++];    // THIS IS RUN FIRST: current number in index of inner loop and increment the index ($j) by one, $n also keeps current number

```

# Answer
> 1 votes
# Red, ~~149~~ 121 bytes

```
func[b][j: i: 0 until[if(i: i + 1)> n: length? b[j: j + 1 i: 1]if
b/(j + i) = i[print[copy/part at b j + 1 i]i: n]j = n]]

```

Try it online!

# Answer
> 1 votes
# Zsh,  ~~35~~ 37 bytes

*+2 bytes to suppress zero-length lists*

```
for x;((s=++i-x+1,x*s>0))&&<<<$@[s,i]

```

Try it online!

For each element in the input, calculate the index of where the sequence would have to start. If the start index and the element are both `>0`, then print the elements from there to the current index, inclusive.

# Answer
> 1 votes
# Ruby 2.7-preview1, 50 bytes

Uses Ruby 2.7's new `Enumerable#filter_map` method. (Sorry for no TiO link; TiO is still on Ruby 2.5.5.)

```
->a{i=0
a.filter_map{|c|i+=1
c>0&&c<=i&&a[i-c,c]}

```

# Answer
> 1 votes
# Icon, 121 bytes

```
procedure f(b)
r:=[];i:=j:=0
while j<*b do{if*b<(i+:=1)then j+:=1&i:=0 else b[j+i]=i&put(r,b[j+1+:i])&i:=*b}
return r
end

```

Try it online!

# Answer
> 1 votes
# Ruby, 64 bytes

```
->a,*s{(r=0;a.find{|x|(x==r+=1)&&s<<a[0,x]};w,*a=a)while a[0];s}

```

Try it online!

# Answer
> 1 votes
# Prolog (SWI), 135 bytes

```
A*B:-reverse(A,B).
[]-_. [A|Q]-[A|R]:-Q-R.
+[Q|R]:-length([Q|R],Q),\+((R*Z,X-Z,S*X,+S)).
Q/R:-N-Q,N*Z,X-Z,R*X,+X.
X//Y:-bagof(R,X/R,Y).

```

Try it online!

`A*B` is `reverse(A,B)`

`A-B` is true if A is a prefix of B

`+A` is true if A is a valid encoding, i.e. length-terminated list

`A/B` is true if, given list A, B is contained within A and B is a valid encoding

`A//B` is true if, given list A, Y is the list of all valid encodings in A (if there are no valid encodings in A, `A//B` fails)

Calling predicate `///2` with the left argument a list and the right argument a variable unifies the variable with the required result. For example, `[7,6,5,4,3,2,1]S.` will unify S with the `[[7, 6, 5, 4], [5, 4, 3], [3, 2], [1]]`. The TIO link contains a helper predicate that runs all inputs with against this predicate.

### Verbose

```
prefix([],_).
prefix(_,[]):-1<0.
prefix([A|Q], [A|R]):-
	prefix(Q,R).
suffix(A, B):-
	reverse(B, Q),
	prefix(P, Q),
	reverse(A, P).
encoded([H|T]):-
	length([H|T], H),
	\+((suffix(P,T), encoded(P))).
f(Q, R):-
	prefix(N, Q),
	suffix(R, N),
	reverse(R, T),
	encoded(T).
g(List, All):-
	bagof(Encoding, f(List, Encoding), All).

```

Try it online!

The tricks used from this verbose solution is to first create another predicate for `reverse` because it is repeated many times. Then operators are used in place of predicate names. The predicate for suffix turns out to only be used once, so it can be removed, replacing its call in `f` with its conditions. Doing this removes the need to use `reverse(R, T)` as the suffix predicate already has the same condition.

# Answer
> 1 votes
# T-SQL, 175 bytes

```
with s(r,i)as(select row_number()over(order by(rand())),*from string_split(<Comma delimited integer string>,','))select string_agg(l.i,',')from s,s l where l.r>s.r-s.i and l.r<=s.r and s.r-s.i>=0group by s.i

```

Try it online!

---

**Verbose version**

```
with s(r,i) as
(
    select row_number() over (order by (rand())) -- Add a row number for sorting
          ,*
    from string_split('7,6,5,4,3,2,1',',')       -- to the split out integer list
)
select string_agg(l.i,',')                       -- then aggregate back together
from s,s l                                       -- joining to itself
where l.r > s.r - s.i                            --   where the previous numbers sit in rows between [current int value] rows before
    and l.r <= s.r                               --     and the current row
    and s.r - s.i >= 0                           --     and there are enough list items for the current integer value
group by s.i                                     -- grouped to each output string

```

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
ŒʒDη.Δ¤sgQ}Q

```

Try it online or verify all test cases.

**Explanation:**

```
Œ           # Get all sublists of the (implicit) input-list
 ʒ          # Filter it by:
  D         #  Duplicate the current sublist
   η        #  Pop the copy and push its prefixes
    .Δ      #  Find the first prefix that's truthy for:
            #  (or -1 if none are)
      ¤     #   Push the last value (without popping the list itself)
       s    #   Swap so the list is at the top
        g   #   Pop and push its length
         Q  #   Check if the two values are the same
     }Q     #  After the find_first: Check if both are the same
            # (after which the filtered list is output implicitly)

```

The `¤sgQ` could alternatively be `DgÅ¿` or `Ðθ∍Q` for the same byte-count.

```
      D     #   Duplicate the list
       g    #   Pop the copy and push its length
        Å¿  #   Check if the list ends with this length as trailing value

      Ð     #   Triplicate the list
       θ    #   Pop one copy and push its last value
        ∍   #   Extend/shorten another copy to this length
         Q  #   Check if the two lists are still the same

```

# Answer
> 0 votes
# APL(NARS), chars 148, bytes 296

```
r←f w;i;j;v;q
k←≢w⋄r←⍬⋄i←0⋄w←(⍳k),¨w
→4×⍳k<i+←1⋄→2×⍳(j>q←≢v←i↑w)∨0=j←2⊃i⊃w⋄v←v↓⍨q-j⋄→3×⍳r≡⍬⋄→2×⍳∨/{(⍵[1]≡v[1])∧⍵⊆v}¨r
r←r,⊂v⋄→2
→0×⍳r≡⍬⋄r←{⍵[2]}¨¨r

```

because of the problem one has to know index of the element, the input set is elaborate as one set with indices (`w←(⍳k),¨w`) that in the end were removed (in `r←{⍵[2]}¨¨r`) test:

```
  ⎕fmt f 90 80 70
┌0─┐
│ 0│
└~─┘
  ⎕fmt f 100 0  2  2  2 0 0 2 4
┌5─────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌4───────┐│
││ 0 2│ │ 2 2│ │ 2 2│ │ 0 2│ │ 0 0 2 4││
│└~───┘ └~───┘ └~───┘ └~───┘ └~───────┘2
└∊─────────────────────────────────────┘
  ⎕fmt f 7 6 5 4 3 2 1
┌4──────────────────────────────┐
│┌4───────┐ ┌3─────┐ ┌2───┐ ┌1─┐│
││ 7 6 5 4│ │ 5 4 3│ │ 3 2│ │ 1││
│└~───────┘ └~─────┘ └~───┘ └~─┘2
└∊──────────────────────────────┘
  ⎕fmt f 1 2 3 4 5
┌1───┐
│┌1─┐│
││ 1││
│└~─┘2
└∊───┘
  ⎕fmt f ⍬
┌0─┐
│ 0│
└~─┘

```

---
Tags: code-golf, subsequence
---


title: Prime numbers in large number

text:
# Question
Title: Prime numbers in large number
Given a large number (in base 10), such as 1234567891011121314151617, find prime "subnumbers" in it.
A prime "subnumber" is a consecutive sequence of digits (taken from the input), which represents a prime number (in base 10).

* **Input**: A number (either a string, a file, or whatever you like).
* **Output**: All prime subnumbers separated somehow (either in a list, a file, comma-separated strings...) If the result is empty, you can take any convention you like (hardcoded string, empty string, gibberish, but program should not crash.
* **Example**
1234 -\> 2, 3, 23
6542 -\> 5, 2
14 -\> \[.. empty output\]

This is code-golf. The shortest program wins!
\[edit\] : additional rule, program must be explained! Not everybody is fluent in Jelly :)

# Answer
> 6 votes
# 05AB1E (legacy), 3 bytes

```
Œʒp

```

Try it online!

Substrings of the input that are prime.

# Answer
> 6 votes
# Perl 6, 28 bytes

```
{grep &is-prime,+«m:ex/.+/}

```

Try it online!

The `:ex` ("exhaustive") flag to the match operator `m` makes it return every possible match of `.+` (ie, every substring of one or more characters), even overlapping ones. The hyperoperator  turns that list of `Match` objects into numbers, which are then filtered for primeness by `grep &is-prime`.

# Answer
> 5 votes
# Python 2, ~~66~~ 65 bytes

```
P=k=1
n=input()
while~n+k:
 if`k`in`n`>0<P%k:print k
 P*=k*k;k+=1

```

Try it online!

# Answer
> 5 votes
# Brachylog, 4 bytes

-1 byte thanks to Kroppeb.

```
sᶠṗˢ

```

Try it online!

ind all `s`ubstrings, `ˢ`elect the rimes

# Answer
> 3 votes
# Japt, ~~13~~ 10 bytes

*Thanks @Shaggy -3 bytes*

```
ò fj f@søX

```

---

```
ò fj f@søX              Full program
                        implicity input
ò                       inclusive range [this - 1]
  fj                    filter primes and
     f@søX              values contained in input

```

Try it online!

# Answer
> 3 votes
# Jelly,  ~~5~~  4 bytes

-1 thanks to Kevin Cruijssen ( is an alias for `ÆP`)

```
ẆḌẒƇ

```

A monadic Link accepting a list of digits\* which yields a list of prime integers.

<sup>* going by "either a string, a file, or whatever you like" - to take an integer, prefix the code with a `D`</sup>

**Try it online!**

### How?

```
ẆḌẒƇ - Link: list of integers (digits)   e.g. [1,2,3,4]
Ẇ    - non-empty contiguous substrings        [[1],[2],[3],[4],[1,2],[2,3],[3,4],[1,2,3],[2,3,4],[1,2,3,4]]
 Ḍ   - convert to decimal (vectorises)        [1,2,3,4,12,23,34,123,234,1234]
   Ƈ - filter keep if:
  Ẓ  -   is prime?                            [2,3,23]

```

# Answer
> 2 votes
# Java 8, ~~148~~ 147 bytes

```
n->{for(int l=n.length(),i=l,j;i-->0;)for(j=l;j>i;){long k=2,x=new Long(n.substring(i,j--));for(;k<x;x=x%k++<1?0:x);if(x>1)System.out.println(x);}}

```

Try it online.

**Explanation:**

```
n->{                     // Method with String parameter and no return-type
  for(int l=n.length(),  //  Length of the input-String
          i=l,j;         //  Temp-integers
      i-->0;)            //  Loop `i` in the range [length, 0)
    for(j=l;j>i;){       //   Inner loop `j` in the range [length, 0)
      for(long k=2,      //    Set `k` to 2
               x=new Long(n.substring(i,j--)
                         //    Take the substring [`i`, `j`) from the input,
            );           //    convert it to a long, and set it as `x`
          k<x;           //    Inner loop as long as `k` is still smaller than `x`
        x=x%k++<1?       //     If `x` is divisible by `k`:
           0             //      Set `x` to 0
          :              //     Else:
           x);           //      Leave `x` unchanged
      if(x>1)            //    If `x` is now larger than 1 (a.k.a. If `x` is a prime):
        System.out.println(x);}}
                         //     Print `x` with a trailing newline to STDOUT

```

# Answer
> 2 votes
# MATL, 9 bytes

```
&XfXUtZp)

```

Try it online!

### Explanation

```
&Xf   % Implicit input: string. Push cell array of non-empty substrings
XU    % Convert to number. Vectorizes
t     % Duplicate
Zp    % Isprime. Vectorizes.
)     % Index. Keeps substrings indicated by the previous result. Implicit display

```

# Answer
> 2 votes
# Bash + GNU Core Utils: ~~80~~ 77 Bytes

```
for i in $(seq `tee a|wc -c`)
{
grep -oE .{$i}<a|factor|grep -oP ': \K\d+$'
}

```

This cannot be the shortest, but I am having trouble coming up with anything better. Help wanted!

By sticking to only POSIX, I got 82:

```
for i in $(seq `tee a|wc -c`)
{
grep -oE .{$i}<a|factor|awk -F\  'NF<3{print$2}'
}

```

# Answer
> 2 votes
# , 60 bytes

```
function(v)Filter(function(i)grepl(i,v)&sum(!i%%1:i)==2,1:v)

```

Try it online!

Not really efficient, inspired by @ovs python 2 answer

# Answer
> 2 votes
# Curry (KiCS2), ~~61~~ 58 bytes

-3 bytes thanks to Wheat Wizard!

Takes input as a string, returns integers. `f` is function which can return any of the results.

```
p n|n>1&&all((>0).mod n)[2..n-1]=n
f(_++a:b++_)=p$read$a:b

```

You can try this on Smap (select `KiCS2 2.2.0 /all-values`) by adding:

```
main = f "1234"

```

`p` is a primality test function which returns it's input if it is a prime, and doesn't return anything otherwise.

`f(_++a:b++_)` matches non-empty substrings of the input in `a:b` and `f` returns the value of `p` applied to `a:b` converted to integer.

Local output:

```
> f "1234"
[...]
Evaluating expression: f "1234"
2
23
3

```

# Answer
> 2 votes
# Vyxal , 4 bytes

```
ǎE~æ

```

Try it Online!

```
ǎE~æ # 'Ṡ' flag makes Vyxal take all input as strings
ǎ    # All substrings
 E   # Convert to numbers
  ~æ # Remove non-primes

```

# Answer
> 1 votes
# Python 2, ~~115~~ 114 bytes

```
f=lambda s:s and[n for n in[int(s[j:])for j in range(len(s))]if n>1and all(n%i for i in range(2,n))]+f(s[:-1])or[]

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 40 bytes

```
Select[PrimeQ@*FromDigits]@*Subsequences

```

Try it online!

Input and output are lists of digits. In the case of no prime subnumbers the empty list `{}` is returned.

Uses `@*` for `Composition` of functions. `Subsequences` gives a list of all subsequences of the input, and `Select[PrimeQ@*FromDigits]` is an operator form of `Select` which returns a list of all elements for which `PrimeQ@*FromDigits` returns `True`.

# Answer
> 0 votes
# Husk, 5 bytes

```
foṗiQ

```

Try it online!

# Answer
> 0 votes
# Clean, 108 bytes

```
import StdEnv,Data.List
$s=nub[n\\u<-inits s,n<-map(toInt o toString)(tails u)|n>1&&all(\m=n/m*m<n)[2..n-1]]

```

Try it online!

# Answer
> 0 votes
# Pyth, 8 bytes

```
fP_TsM.:

```

Test suite

Takes the input as a string, outputs a list of integers. Can also take input as an `int` by adding ``` at the end for an extra byte.

Explanation:
```
fP_TsM.:  | Full code
fP_TsM.:Q |  with implicit variables added
          | Print (implicit)
      .:Q |  list of all substrings of the input
    sM    |   converted to integers
fP_T      |    filtered for prime numbers

```

And ``` just converts `int` to `str`.

# Answer
> 0 votes
## Matlab, 89 bytes

```
function[m]=f(x),m=1;for i=1:length(x),m=[m;str2num(combnk(x,i))];end,m=m(isprime(m));end

```

Try it Online!

---
Tags: code-golf, number, primes
---


title: Flippign Lettesr Aroudn

text:
# Question
Title: Flippign Lettesr Aroudn
In chat, we are often fast-typers and don't really look at the order of letters before posting a message. Since we are lazy, we need a program that automatically swaps the last two letters in our words, but since we don't want to respond too late, the code must be short.

Your task, if you wish to accept it, is to write a program that flips the last two letters of each word in a given string (so the word `Thansk` turns into `Thanks`). A *word* is a sequence of two or more letters in the English alphabet delimited by **a single** space.

* The string / list of *characters* you receive as input is guaranteed to only contain alphabetic characters and spaces (ASCII \[97 - 122\], \[65 - 90\] and 32).
* You can take input and provide output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default.
* The output may have one trailing space and / or one trailing newline.
* The input will always contain words only (and the corresponding whitespace) and will consist of at least one word.

This is code-golf, so the shortest submission (scored in bytes), in each language wins!

### Test cases

Note that the strings are surrounded with quotes for readability.

```
Input -> Output

"Thansk"                                 -> "Thanks"
"Youer welcoem"                          -> "Youre welcome"
"This is an apple"                       -> "Thsi si na appel"
"Flippign Lettesr Aroudn"                -> "Flipping Letters Around"
"tHe oDd chALlEneg wiht swappde lettesR" -> "teH odD chALlEnge with swapped letteRs"

```

Or, for test suite convenience, here are the inputs and their corresponding outputs separately:

```
Thansk
Youer welcoem
This is an apple
Flippign Lettesr Aroudn
tHe oDd chALlEneg wiht swappde lettesR

```

```
Thanks
Youre welcome
Thsi si na appel
Flipping Letters Around
teH odD chALlEnge with swapped letteRs

```

Thanks to DJMcMayhem for the title. This was originally a CMC.

# Answer
> 16 votes
# , 4 ~~5~~ bytes

```
òeXp

```

Try it online!

`||` denotes the cursor

The buffer starts with `|w|ord and more words` and the cursor being on the first character.

Recursively `ò`

go to the `e`nd of a word

`wor|d| and more words`

remove `X` the character to the left of the cursor

`wo|d| and more words`

`p`aste it over the next character

`wod|r| and more words`

Implicit ending `ò`, repeat the same process for other words until the end of the buffer is reached

# Answer
> 10 votes
# Jelly, 7 bytes

```
Ḳœ?@€2K

```

A monadic link taking and returning lists of characters

**Try it online!**

### How?

```
Ḳœ?@€2K - Link: list of characters
Ḳ       - split at spaces
     2  - literal two
    €   - for €ach:
   @    -   with sw@pped arguments:
 œ?     -     nth permutation (the 2nd permutation has the rightmost elements swapped)
      K - join with spaces

```

# Answer
> 9 votes
# Brain-Flak, 122 bytes

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

```

Try it online!

The worst language for the job :)

~~Readable~~ Slightly more readable version:

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

    {
        {}
        <>

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

        (<>)
    }
    {}

    ({}<>)<>

}<>

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

{

    ({}<>)
    <>
}<>

```

# Answer
> 7 votes
# Python 3, 50 bytes

```
print(*(w[:-2]+w[:-3:-1]for w in input().split()))

```

Try it online!

This answer abuses Python 3's behavior of print: Multiple arguments are printed with a single space between them. Of course, we can't just give it multiple arguments because we don't know how many words will be in the input. So we use the splat operator. Basically

```
print(*[a,b,c])

```

is exactly the same thing as

```
print(a,b,c)

```

Abusing that makes a full program turn out shorter than a function/lambda where we'd have to use `' '.join` or something similar.

# Answer
> 7 votes
# Haskell, 40 bytes

```
(f=<<).words
f[a,b]=b:a:" "
f(x:r)=x:f r

```

Try it online! Usage example: `(f=<<).words $ "abc xyz"` yields `"acb xzy "`.

# Answer
> 7 votes
# Retina, 13 bytes

```
(.)(.)\b
$2$1

```

Try it online! Link includes test cases.

# Answer
> 5 votes
# C,  ~~62~~   ~~58~~  54 bytes

*Thanks to @Dennis for saving  ~~four~~  eight bytes!*

```
f(char*s){s[1]>32||(*s^=s[-1]^=*s^=s[-1]);*++s&&f(s);}

```

Try it online!

# Answer
> 5 votes
# Matlab (R2016b), ~~51~~ 50 bytes

Saved ~~49~~ 50 (!) bytes thanks to @Giuseppe.

```
function s(a),regexprep(a,'(\w)(\w)( |$)','$2$1 ')

```

And my previous answer:

# Matlab (R2016b), 100 bytes

(Just for the fun of it :P)

```
function s(a),a=regexp(a,' ','split');for i=1:length(a),fprintf('%s ',a{i}([1:end-2 end end-1])),end

```

Explanation:

```
function s(a) % Defining as a function...
a=regexp(a,' ','split'); % Splits the input string at the spaces
for i=1:length(a) % Loops through each word
    fprintf('%s ',a{i}([1:end-2 end end-1])) % And prints everything with the last two characters swapped.
end

```

# Answer
> 4 votes
# Prolog (SWI), 60 bytes

```
[A,B]+[B,A].
[A,B,32|U]+[B,A,32|Y]:-U+Y,!.
[A|U]+[A|Y]:-U+Y.

```

Try it online!

## Explanation

First we define the base case:

```
p([A,B],[B,A]).

```

This means that the last two letters will always be swapped.

Then we define what happens if we are right next to a space:

```
p([A,B,32|U],[B,A,32|Y]):-p(U,Y),!.

```

Two strings match if right before a space the letters before the space are swapped and the remainder if the strings match. We then use `!` to cut.

Our last case is if we are not next to a space the first two letters need to match.

```
p([A|U],[A|Y]):-p(U,Y).

```

# Answer
> 4 votes
# , ~~111~~ ~~51~~ 41 bytes

Courtesy of @Giuseppe, a regex approach which blows my old method out of the water.

```
cat(gsub("(.)(.)\\b",'\\2\\1',scan(,"")))

```

# Answer
> 4 votes
# Wolfram Language, 117 bytes

```
StringReplace[RegularExpression["\\b[[:alpha:]]{2,}\\b"]:>StringDrop[StringInsert["$0",StringTake["$0",{-1}],-3],-1]]

```

Try it online!

Applied to the test strings.

```
StringReplace[
  RegularExpression["\\b[[:alpha:]]{2,}\\b"] :>
   StringDrop[StringInsert["$0", StringTake["$0", {-1}], -3], -1]] /@
 {"Thansk", "Youer welcoem", "This is an apple",
  "Flippign Lettesr Aroudn", "tHe oDd chALlEneg wiht swappde lettesR"} // Column

```

> ```
> Thanks
> Youre welcome
> Thsi si na appel
> Flipping Letters Around
> teH odD chALlEnge with swapped letteRs
>
> ```

# Answer
> 4 votes
# APL (Dyalog Classic), 28 bytes

```
1↓∊((¯2↓⊢),2↑⌽)¨' '(,⊂⍨⊣=,)⍞

```

`⎕ML` and `⎕IO` are both `1`,

Try it online!

# Explanation

* **`... (,⊂⍨⊣=,) ...`** Split (while keeping borders, and appending a border to the beginning) ...
* **`... ⍞`** ... the input ...
* **`... ' ' ...`** ... at spaces.
* **`... ( ... )¨ ...`** Then, to each element of that:
    + **`... , ...`** Concatenate ...
    + **`... (¯2↓⊢) ...`** ... every item except the last two ...
    + **`... 2↑⌽ ...`** ... with the reverse of the last two elements.
* **`1↓∊ ...`** Finally, return all but the first element of the flattened result.

# Answer
> 3 votes
# Haskell, 45 bytes

*-2 bytes thanks to H.PWiz.*

```
(r.g.r=<<).words
g(x:y:z)=' ':y:x:z
r=reverse

```

Try it online!

# Answer
> 3 votes
# Funky, 34 bytes

```
s=>s::gsub("(.)(.)( |$)","$2$1$3")

```

Try it online!

# Answer
> 3 votes
# , ~~20 19~~ 11 bytes

Credit to @Bolce Bussiere

```
1&A.&.>&.;:

```

Try it online!

```
       &.;:      on words
    &.>          on each
  A.             apply the permutation
1&               number 1, swap the last two elements

```

# Answer
> 3 votes
## Alice, 24 bytes

```
/0RR'.%$1\' o
\ix*o ne@/

```

Try it online!

### Explanation

```
/...\' o
\.../

```

This forms a loop where the loop body is a linear Ordinal snippet and we execute `' o` in Cardinal mode between every two loop iterations. The latter just prints a space.

Unfolding the zigzag structure of the Ordinal code, the linear loop body actually looks like this:

```
iR*' %e10xRo.n$@

```

Breaking this down:

```
i     Read all input. On subsequent iterations, this will push an empty string.
R     Reverse.
*     Join. On the first iteration, this joins the input to an implicit empty string,
      which does nothing. On subsequent iterations, it will join the empty string to
      the word on top of the string, thereby getting rid of the empty string.
' %   Split around spaces. On the first iteration, this will split the input
      into individual words. On subsequent iterations, this does nothing.
e10   Push "10".
x     Use this to permute the (reversed) word on top of the stack. In
      particular, the word is rearranged with the same permutation that is
      required to sort the string "10", which means the first two letters
      get swapped (which correspond to the last two letters of the actual
      word).
R     Reverse the swapped word.
o     Print it.
.n$@  If there are no words left on the stack, terminate the program.

```

# Answer
> 2 votes
# brainfuck, ~~109~~ 100 bytes

Edit: don’t have to handle one letter words

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

```

Try it online!

Prints a trailing space

### How It Works

```
,[>++++[-<-------->],] Puts input on the tape and subtracts 32 from each character
                       This separates each word

>+[- Start the loop
   <[>++++[<++++++++>-]<[->>+<<]<] Add 32 to each letter of the word
                                   Skip this on the first iteration for the last word

   <<[->>+<<]>[[-<+>]>] Swaps the last two letters of the word
   <<[>+>+>]- If there is another word to the left continue loop
              Also set up to add a space to the end of the word
 <] End loop
 >>>>>>>[.>] Print the modified string

```

### Previous version, 109 bytes

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

```

Try it online!

# Answer
> 2 votes
# QuadR, 8 bytes

```
..\b
⌽⍵M

```

Try it online!

# Answer
> 2 votes
# Google Sheets, 33 Bytes

Anonymous worksheet function that takes input from cell `A1` and outputs to the calling cell

```
=RegExReplace(A1,"(.)(.)\b","$2$1

```

-2 Bytes Thanks to @KevinCruijssen for the use of `(.)` over `(\w)`

# Answer
> 2 votes
# Julia 1.0, 30 bytes

```
!s=replace(s,r"..\b"=>reverse)

```

Try it online!

detect end of words with a regex `r"..\b"` and apply `reverse` on the matches

# Answer
> 2 votes
# Curry, 33 bytes

Tested in both KiCS2 and PAKCS.

```
f(u++[x,y])=u++[y,x]
(>>=f).words

```

Curry's powerful patterns let it beat the Haskell answer!

To test it you can use Smap. Just select `KiCS2 2.2.0` or `PAKCS 2.2.0` and paste the following complete code:

```
f(u++[x,y])=u++[y,x]
g=(>>=f).words
main=f "Hello world an happy day"

```

# Answer
> 1 votes
# Haskell, ~~53~~ 45 bytes

```
u[a,b]=[b,a]
u(a:b)=a:u b
unwords.map u.words

```

Try it online!

## Explanation

`u` is a function that swaps the last two letters of a word. To apply it to all the words we use `words` to split the list, map it across all of the words and then use `unwords` to put it back together.

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
#vy`sðJ

```

Try it online!

-1 thanks to Magic Octopus Urn.

Prints one trailing space.

# Answer
> 1 votes
# Perl 5, 19 + 1 (`-p`) = 20 bytes

```
s/(\w)(\w)\b/$2$1/g

```

Try it online!

# Answer
> 1 votes
# PHP, 119 107 bytes

Edit: thanks to totallyhuman

```
<?php foreach(explode(" ",trim(fgets(STDIN)))as$w)echo substr($w,0,strlen($w)-2).strrev(substr($w,-2))," ";

```

Try it online!

# Answer
> 1 votes
# sed, ~~20~~ 17+1 (-r) = 18 bytes

```
s/(.)(.)\b/\2\1/g

```

Try it online!

# Answer
> 1 votes
# Haskell, 41 bytes

```
foldr(%)" "
a%(b:' ':r)=b:a:' ':r
a%s=a:s

```

Try it online!

Outputs with a trailing space.

The repeated `' ':r` looks wasteful. But `a%(b:t@(' ':r))=b:a:t` is the same length and `a%(b:t)|' ':_<-t=b:a:t` is one byte longer.

---

# Haskell, 41 bytes

```
f(a:b:t)|t<"A"=b:a:f t|1>0=a:f(b:t)
f e=e

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), ~~38~~ ~~36~~ 32 bytes

```
~~s=>s.replace(/(.)(.)( |$)/g,"$2$1 ")~~
```

```
s=>s.replace(/(.)(.)\b/g,"$2$1")

```

Try it online!

RegExp approach courtesy @Giuseppe (although I thought of this independently), assuming words separated by only one space

-2 for only considering 1 space and add trailing space

-4 Thanks @Shaggy

# Answer
> 1 votes
# PHP, 65 bytes

requires PHP 7.1 (or later)

```
for(;$s=$argv[++$i];$s[-1]=$s[-2],$s[-2]=$c,print"$s ")$c=$s[-1];

```

takes sentence as separate command line arguments. Run with `-nr`.

---

working on a single string, **77+1 bytes**:

```
foreach(explode(" ",$argn)as$s){$c=$s[-1];$s[-1]=$s[-2];$s[-2]=$c;echo"$s ";}

```

Run as pipe with `-nR`.

---

... or try them online.

# Answer
> 1 votes
# K (oK), ~~23~~ 22 bytes

```
" "/{x@prm[!#x]1}'" "\

```

Try it online!

**Example:**

```
" "/{x@prm[!#x]1}'" "\"Hello World"
"Helol Wordl"

```

**Explanation:**

Port of FrownyFrog's solution to save **1 byte**.

I'll come back to this.

```
" "/{prm[x]1}'" "\ / the solution
              " "\ / split input on " "
    {       }'     / apply lambda to each
     prm[x]        / permute input x
           1       / and take the 2nd result
" "/               / join with " "

```

**Previous solution:**

* `" "/-2{(x_y),|x#y}'" "\` **23 bytes**

# Answer
> 1 votes
# Java 8, 35 bytes

```
s->s.replaceAll("(.)(.)\\b","$2$1")

```

Port of *@TaylorScott*'s Google Sheets answer, after I golfed two bytes. EDIT: I see it's now a port of *Neil*'s Retina answer after my two golfed bytes.

**Explanation:**

Try it online.

```
s->                           // Method with String as both parameter and return-type
   s.replaceAll("(.)(.)       //  Replace any two characters,
                       \\b",  //  with a word-boundary after it (space or end of String)
                "$2$1")       //  With the two characters swapped

```

# Answer
> 1 votes
# Vyxal `S`, 5 bytes

```
⌈ƛ÷$Ṡ

```

Try it Online!

-2 thanks to Aaron Miller.

# Answer
> 1 votes
# Ly, 30 bytes

```
i00I[rpr' =[ppf' 0]p0I]pfrp[o]

```

Try it online!

This one reads all the input into the stack, then copies characters one at a time to the other end of the stack (with a null separator between the original and the "fixed" codepoints). Anytime a space it found, it reverse the position of the previous two codepoints.

When the loop hits the null separator it end, then the just prints the stack.

```
i00I[rpr' =[ppf' 0]p0I]pfrp[o]
i0                              # Read all the input, then push a null
  0I                            # Copy the bottom of the stack to the top
    [                 ]p        # Loop until the null reaches the bottom of the stack
     rpr                        # Reverse, pop, reverse (delete bottom of the stack)
                    0I          # Copy the bottom of the stack to the top
        ' =                     # Is the codepoint " "?
           [p    0]p            # If-then, runs if codepoint is " "
             pf'                # Delete " ", flip two entries, add " " back
                        f       # End of input, flip the last two codepoints
                         rp     # Reverse stack, delete null
                           [o]  # Print the stack as characters

```

# Answer
> 1 votes
# Lexurgy, 24 bytes

This kind of challenge is one of the canonical reasons for captures in Lexurgy to exist (for things like metathesis and reduplication).

Capture 2 of any character, and swap their order when they are at the end of a "word".

```
a:
[]$1 []$2=>$2 $1/_ $

```

# Answer
> 0 votes
# Jelly, 10 bytes

```
ḲṪ,¥\€Ḋ€UK

```

Try it online!

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), ~~136~~ 119 bytes

```
	I =INPUT
B	I SPAN(&LCASE &UCASE) . Y ARBNO(' ') =:F(O)
	Y RPOS(2) REM . Z =REVERSE(Z)
	O =O Y ' '	:(B)
O	OUTPUT =O
END

```

Try it online!

Prints with a trailing space. ~~You know you've done something wrong when a language is a backronym for *StriNg Oriented and symBOlic Language* and your code is longer than Brain-Flak :(~~ now it's slightly better.

Line `B` takes `I` and replaces `(alphabetic characters saved as Y)(some number of spaces)` with the empty string.

The following line extracts the last 2 characters of `Y` as `Z` and replaces them as `Z` reversed, then the next line concatenates `O`, `Y`, and a single space character.

Finally, it prints when `I` no longer matches the required pattern in line `B`.

# Answer
> 0 votes
# Clean, ~~75~~ 59 bytes

*-16 from Laikoni*

```
@[a,b]=[b,a]
@[a,b,' ':c]=[b,a,' ': @c]
@[a:b]=[a: @b]
@e=e

```

Try it online!

# Answer
> 0 votes
# Standard ML (MLton), ~~92~~ 77 bytes

```
implode o foldr(fn(a,b:: #" "::r)=>b::a:: #" "::r|(a,r)=>a::r)[#" "]o explode

```

Try it online! Based on xnor's Haskell solution.

---

### Previous 92 byte version

```
fun f(a::b:: #" "::r)=b::a:: #" "::f r|f(x::r)=x::f r|f r=r
fun$s=implode(f(explode(s^" ")))

```

Try it online! Example usage: `$ "Flippign Lettesr Aroudn"` yields `"Flipping Letters Around "`.

### Ungolfed

```
fun f (a :: b :: #" " :: r) = b :: a :: #" " :: f r
  | f              (x :: r) = x :: f r
  | f                    r  = r

fun g s = implode (f (explode (s ^ " ")))

```

Try it online!

# Answer
> 0 votes
# Japt `-S`, ~~7~~ 6 bytes

A port of Jonathan's Jelly solution.

```
¸Ëá ÅÎ

```

Try it

```
¸Ëá ÅÎ     :Implicit input of string
¸          :Split on spaces
 Ë         :Map
  á        :  Permutations
    Å      :  Slice off the first element
     Î     :  Get the first element
           :Implicit output joined with spaces

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 72 bytes

```
x""<>(Characters[StringSplit@x][[;;,#]]&/@{;;-3,-1,-2})~Riffle~" "

```

Try it online!

Another approach using manipulation of character list and take parts instead of string regex.

The two Unicode characters are `\[Function]` and `\[Transpose]` in private use area of Mathematica, take 3 bytes each.

## 74 bytes

Try it online!

# Answer
> 0 votes
# Excel VBA, 78 Bytes

Anonymous VBE immediate window that takes input from range `A1` and outputs to the VBE immediate window.

```
For Each s in Split([A1]):l=Len(s):?Left(s,l-2)Right(s,1)Mid(s,l-1,1)" ";:Next

```

# Answer
> 0 votes
# Ruby, 53 bytes

```
$*.each{|x|print x[0,x.length-2]+x[-2,2].reverse," "}

```

The program takes input through command line arguments (formatted as a regular sentence, without quotes).

$\* is a shorthand for ARGV, therefore i can iterate over each of the words, already in an array.

Only thing that bugs me is that awful x.length-2 snippet. I would prefer to use x.last(-2), but i believe that is only in RoR.

Called like:

```
ruby file.rb Helol Wordl

```

So that each word becomes a parameter. (Not wrapped in quotes)

# Answer
> 0 votes
# Clojure, ~~122~~ 117 bytes

-5 bytes by shortcutting the indices of the characters to swap

```
(fn[p](map #(let[l(count %)v(vec %)y(dec l)z(- l 2)](apply str(assoc v y(v z)z(v y))))(clojure.string/split p #" ")))

```

It's a shame that most of Clojure's String function are tucked away inside of `Clojure.string`, and that there are no good ways of manipulating the characters of Strings directly. `clojure.string/split` is atrociously long, and the conversion to-and-from vectors added quite a lot. I might be able to shave off a couple bytes by shortcutting the trailing indices, but this is the only decent algorithm I could think of.

```
(defn flip-last [phrase]
  (let [words (clojure.string/split phrase #" ")]

    ; For each word...
    (map #(let [len (count %)
                ; Need to turn the string into a vector so we can manipulate it using indices
                vec-word (vec %)]

            ; ... then turn the vector of characters back into a String.
            (apply str
               ; Associate the element at the second last index with the element at the last index,
               ;  and vice-versa...
              (assoc vec-word (dec len) (vec-word (- len 2))
                              (- len 2) (vec-word (dec len)))))

         words)))

```

# Answer
> 0 votes
# QuadR, 8 bytes

```
..\b
⌽⍵M

```

Try it online!

`..\b` any two characters followed by a word boundary

gets replaced with

`⌽⍵M` the reverse of the **M**atch

---

Equivalent to the following 18-byte Dyalog APL function:

```
'..\b'⎕R{⌽⍵.Match}

```

# Answer
> 0 votes
## PHP4 (48 chars)

Given *$argv\[1\]* as a command line argument :

```
echo preg_replace('#(.)(.)\b#','$2$1',$argv[1]);

```

## PHP7.4 (48 chars)

The function **$f** is inverting the last two chars of every word :

```
$f=fn($s)=>preg_replace('#(.)(.)\b#','$2$1',$s);

```

Try it Online \- Usage :

```
echo $f('Flippign Lettesr Aroudn');

```

Both versions are using 's PCRE Text Processing Functions.

**Info**: Support for PHP4 has been discontinued since 2008 but same code still works in PHP8.1.

## Mathematica (58 chars)

```
f=StringReplace[#,RegularExpression["(.)(.)\\b"]:>"$2$1"]&

```

Try it online

# Answer
> 0 votes
# Factor, 50 bytes

```
[ " "split [ 2 cut* reverse append ] map " "join ]

```

Try it online!

Factor's regular expressions don't support backreferences for philosophical reasons, so here's (possibly) the next best thing. It splits the input on spaces, applies a quotation to each word, and joins them with a space into a single string. Here's how the mapping quotation works:

```
          ! "Flipping"
2 cut*    ! "Flippi" "ng"
reverse   ! "Flippi" "gn"
append    ! "Flippign"

```

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


title: Sniff out biased random permutations

text:
# Question
Title: Sniff out biased random permutations
The brilliant engineers at \<enter company you love to hate\> have struck again. This time they've "revolutionised" the generation of random permutations. "Every great invention is simple" they say and their magical new algorithm is as follows:

* Start with a list `1,2,3,...,n` of numbers to permute.
* For each element x in the list draw a random index in the list and swap x and the element at the random index

Then they "prove" that this is unbiased because each element occurs at each position with equal frequency.

Obviously, their reasoning is flawed because their method has `n^n` equally likely outcomes which typically is not a multiple of `n!`

Your task is as follows: Write a program / function that accepts a list / stream / generator / iterator (whatever makes most sense in your language of choice) of permutations and decides whether they are a biased sample as created by the algorithm above or not. If not you may assume that the sample is unbiased.

`n` will be `3` or more. You can set a minimum sample size as you see fit,

Your program may err on small samples but must converge to the correct answer as the sample size increases.

You may output True/False or any two values (but not groups of values: so for example empty list vs. nonempty list is not allowed unless the nonempty list is always the same)

Apart from that standard rules apply.

This is code-golf, smallest function or program in bytes wins. Different languages compete independently.

# Python 3 Test case generator

```
import random

def f(n,biased=True,repeats=10,one_based=False):
  OUT = []
  for c in range(repeats):
    out = [*range(one_based,n+one_based)]
    OUT.append(out)
    for i in range(n):
      o = random.randint(i-i*biased,n-1)
      out[o],out[i] = out[i],out[o]
  return OUT

```

Try it online!

### Additional hints

Now that @AndersKaseorg has let the cat out of the bag I see no harm in giving a few more hints.

Even though it may look plausible at first sight it is not true that elements are uniformly distributed over positions.

We do know:

1. Directly after the nth element was swapped with a random position the element at position n is truly uniformly random. In particular, in the final state the last position is uniformly random.
2. Before that the nth element is guaranteed to be equal or smaller than n
3. Whatever is swapped downwards from position n to m can only be returned to n at the nth move. In particular, it can't be if the original move was the nth in the first place.
4. If we rank positions by their expectation after the kth move then positions m and n can overtake each other only at the mth or nth move.
5. Select values:

* The base (i.e. first or zeroth) element's position is uniformly random. This holds after the first swap and remains true from there on.
* The next element is over-represented in the first position: Out of `n^n` possible draws it occurs in `(n-1) x n^(n-2) + (n-1)^(n-1)` instances.
* The last element is under-represented in the first position: Out of `n^n` possible draws it occurs in `2 x (n-1)^(n-1)` instances.

More demo / test code

5 can be used to solve this challenge in a similar but perhaps slightly less golfable way to Anders's answer.

# Answer
> 12 votes
# Python 3, ~~45~~ 43 bytes

(−2 bytes from xnor)

```
lambda v:sum(r<r[-1:]for r in v)/len(v)>.51

```

Try it online!

### How it works

Computes the fraction of samples where the first entry is less than the last entry. For unbiased input, this converges to \\$\frac12\\$.

For biased input, the last entry is uniform, but the first entry is less than a uniform one with probability

$$\frac{(3n - 2)(n - 1)^{n - 1}}{2n^n},$$

which is \\$\frac{14}{27} ≈ 0.518518\\$ at \\$n = 3\\$, and increases toward \\$\frac{3}{2e} ≈ 0.551819\\$ as \\$n → ∞\\$.

This calculation ignores a slight anti-correlation between the first and last entries for \\$n ≥ 4\\$, but we can bound it and show that it’s much too small to affect correctness. Here are the exact probabilities computed by dynamic programming.

# Answer
> 7 votes
# , ~~94~~ ~~78~~ ~~74~~ 56 bytes

*Edit: -12 bytes thanks to Giuseppe, and -6 bytes and corrected (I hope) maths thanks to Anders Kaseorg*

```
function(m,n=max(m))var(t<-table(n^(1:n)%*%m))/mean(t)>2

```

Try it online!

Input is a matrix `m` with each row representing a permutation.

If permutations are unbiased, then all permutations should occur with the same observed frequency `t` (with `k` samples, `mean(t)==k/factorial(n)`), and with an expected variance equal to the mean (binomial variance = `k*p*q` = `k*(1/factorial(n))*(1-1/factorial(n))` = `mean(t)*(1-1/factorial(n))` = `mean(t)` after correction for sample size `factorial(n)`).

We guess that sampling is biased if the variance is greater than twice the mean. Simulations indicate that this is sufficient to detect biased samples with `n=3`, and the difference becomes bigger (so, easier to detect) at larger `n`. As `n` increases, though, the number of permutations needs to be quite large for the guess to be reliable.

---

Addendum: Note that a port of Anders Kaseorg's approach, which is much better tailored to detect exactly *this* type of biased permutations (rather than simply any biased set of permutations) is 19 bytes shorter:
`function(m)mean(m[1,]<m[max(m),])<.51` (try it).

# Answer
> 4 votes
# Charcoal, 20 bytes

```
›₂⌈Ｅθ№θι⊕₂∕ＬθΠ…·¹Ｌ⊟θ

```

Try it online! Link is to verbose version of code. Outputs `-` if it thinks the list of permutations is biased. (Test case consists of 768 biased permutations of four elements.) Explanation:

```
    θ                   Input list
   Ｅ                    Map over elements
     №                  Count of
       ι                Current element
      θ                 In input list
  ⌈                     Maximum
 ₂                      Square root
›                       Is greater than
            θ           Input list
           Ｌ            Length
          ∕             Divided by
                   θ    Input list
                  ⊟     Last element
                 Ｌ      Length
             Π…·¹       Factorial
         ₂              Square root
        ⊕               Incremented
›                       Implicitly print

```

A port of @AndersKaesorg's answer would be just 16 bytes:

```
‹·⁵¹∕ΣＥθ‹§ι⁰⊟ιＬθ

```

Try it online! Link is to verbose version of code. Outputs `-` if it thinks the list of permutations is biased. (Test case consists of 256 biased permutations of four elements.)

---
Tags: code-golf, combinatorics, random, open-ended-function, statistics
---


# Question
Title: Convert from variable-width Two's Complement to Integer
Take an input, and convert it from Two's Complement notation (binary where the first bit is negated, but the rest are taken as normal) into an integer (in a somewhat standard output form). Input can be as a string, a list of digits, a number, or pretty much any other format which is recognizably Two's Complement. Leading zeroes must function properly. Both returning and outputting the value are fine.

Examples:

```
0 -> 0
1 -> -1
111 -> -1
011 -> 3
100 -> -4
1001 -> -7
0001 -> 1

```

Example conversion: Say our input is 1101. We can see that the first bit is in position 4, so has a positional value of 2^3. Therefore, since it's a 1, we add -8 to our total. Then, the rest of the bits are converted just the same as regular binary (with 101 being the same as 5), so the result is -3.

Example implementation (Mathematica, 40 characters): `Rest@#~FromDigits~2 - 2^Length@#/2*#[[1]] &` This implementation takes input as a list of digits.

Code-golf, so shortest solution wins.

# Answer
# JavaScript (ES6), 31 bytes

Expects a binary string.

```
s=>(q=1<<s.length-1,'0b'+s^q)-q

```

Try it online!

Uses the classic sign extension formula:

```
sign_extended = (value XOR mask) - mask

```

where only the sign bit is set in `mask` (e.g. `0x80` for a byte).

---

# JavaScript (ES6), 26 bytes

Expects an array of bits.

```
f=a=>1/a?-a:a.pop()+2*f(a)

```

Try it online!
> 10 votes

# Answer
# Jelly, 4 bytes

```
N1¦Ḅ

```

A monadic link that accepts a list of `1`s and `0`s and yields an integer.

**Try it online!** Or see the test-suite.

### How?

```
N1¦Ḅ - Link: list of 1s and 0s, A
  ¦  - sparse application to A...
 1   - ...indices: 1
N    - ...action: negate
   Ḅ - convert from binary (conversion from base functions allow non-base digits)

```
> 8 votes

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

```
s=>'0b'+s-s[0]*2**s.length

```

Try it online!
> 7 votes

# Answer
# Python 3.8 (pre-release), 33 bytes

```
lambda n:2*int(n,2)-int(n[0]+n,2)

```

Try it online!

This is essentially `2 x n - n'` where n is the input and n' is the input with its highest bit repeated. It can be rewritten  `2 x n - 2 x h - n = n - 2 x h` where h is the highest bit of `n`

## Python 3.8 (pre-release), 34, 33 bytes (@GB)

```
lambda n:eval(f"0b{n[1:]}0-0b"+n)

```

Try it online!

This boils down to `2 x n' - n` where n is the input and n' is the input with the highest bit cleared. This can be rewritten as `2 x n - 2 x h - n = n - 2 x h` where `h` is the highest bit of `n` (in position).
> 7 votes

# Answer
# Perl 5 `-pl`, 31 bytes

```
s/.//;$_=-$&*2**y///c+oct"0b$_"

```

Try it online!
> 6 votes

# Answer
# Python 3.8 (pre-release), 38 bytes

```
lambda n:(a:=int(n,2))-(a*2&2**len(n))

```

Try it online!
> 6 votes

# Answer
# Wolfram Language (Mathematica), 20 bytes

```
Fold[#+##&,-#,!##2]&

```

Try it online!

Input `[digits...]`.

Negates the first bit, and takes the rest as normal.
> 6 votes

# Answer
# x86-16 machine code, 25 bytes

Binary:

```
00000000: 33c0 9903 f1f9 4e13 d2f6 0401 7402 0bc2  3.....N.....t...
00000010: e2f4 7404 33c2 2bc2 c3                   ..t.3.+..

```

Listing:

```
33 C0       XOR  AX, AX             ; AX = 0 (working sum)
99          CWD                     ; DX = 0 (mask bit)
03 F1       ADD  SI, CX             ; SI = end of input string
F9          STC                     ; set CF so DX = 1 on first loop
        TC_LOOP:
4E          DEC  SI                 ; get next significant bit
13 D2       ADC  DX, DX             ; shift left with CF to least sig bit
F6 04 01    TEST BYTE PTR[SI], 1    ; this bit a '1'?
74 02       JZ   NEXT_BIT           ; if not, go to next
0B C2       OR   AX, DX             ; flip bit on working sum, CF = 0
        NEXT_BIT:
E2 F4       LOOP TC_LOOP            ; loop until end of input string
74 04       JZ   TC_DONE            ; was most sig bit a 1?
33 C2       XOR  AX, DX             ; if so, sign extend
2B C2       SUB  AX, DX
        TC_DONE:
C3          RET                     ; return to caller

```

Callable function. Input string at `DS:[SI]`, length in `CX`. Output to `AX`.
> 6 votes

# Answer
# , ~~42~~ ~~40~~ ~~39~~ ~~37~~ 36 bytes

*Edit: -2 bytes thanks to @Giuseppe and -2 bytes thanks to @Dominic van Essen.*

```
\(x)2^rev(a<-seq(x)-1)%*%(x*(-1)^!a)
```

Attempt This Online!

Takes input as a list of digits.
> 5 votes

# Answer
# C (GCC), 88 bytes

```
n;main(i,v)char**v;{char*s=*++v;for(;*s;)n=n*2|(*s++-=48);printf("%d\n",n-(**v<<s-*v));}
```

Attempt This Online!

Indented code:

```
n;
main(i,v)char**v;{
    char*s=*++v;
    for(;*s;)
        n=n*2|(*s++-=48);
    printf("%d\n",n-(**v<<s-*v));
}

```

The input is passed through `argv[1]`.
> 5 votes

# Answer
# Vyxal, 5 bytes

```
ḣ$NpB

```

Try it Online!

When you steal ideas from Jelly

```
ḣ$NpB # Expects a list of digits
ḣ     # Push the first item and then the rest
 $    # Swap
  N   # Negate the first item
   p  # Prepend the result to the rest of the list
    B # Binary to decimal

```

# Vyxal, 8 bytes

```
h[†B›N|B

```

Try it Online!

My original pre-Jelly answer

```
h[†B›N|B # Takes input as a list of binary digits
h[       # If the first bit is 1...
  †      # Vectorized not
   B     # Convert to decimal
    ›    # Add one
     N   # Negate
      |  # Otherwise...
       B # Convert to decimal

```
> 5 votes

# Answer
# C (gcc), ~~63~~ ~~57~~ 46 bytes

```
b;f(char*n){for(b=48-*n;*++n;)b+=b+*n-48;n=b;}

```

Try it online!

*Saved 11 bytes thanks to att!*

Inputs a string of two's complement \\$1\\$s and \\$0\\$s.
Returns its `int` value.
> 5 votes

# Answer
# 05AB1E, 5 bytes

```
ć(š2β

```

Input as a list of bits.

Same approach as *@JonathanAllan*'s Jelly answer, but found independently.

Try it online or verify all test cases.

**Explanation:**

```
ć      # Extract head of the (implicit) input-list; push remainder-list and first
       # item separated to the stack
 (     # Negate this head
  š    # Prepend it back to the list
   2β  # Convert it from a base-2 list to an integer
       # (after which the result is output implicitly)

```
> 5 votes

# Answer
# , 34 bytes

```
\(x)sum(a<-x*2^rev(seq(x)))/2-a[1]
```

Attempt This Online!

Test setup borrowed from pajonk's R answer.
> 5 votes

# Answer
# x86 machine code, 7 bytes

Function that works in 32 or 64-bit mode, with inputs:

* length `n` of the bitstring, in ECX (really just CL)
* bit-pattern in the low `n` bits of EAX. (bits in "a number" is an allowed input format)

Output: Signed integer in the full width of EAX.
In binary 2's complement format, as standard for x86.

Apparently a "number" is a valid output, with no need to convert it ourselves to something having anything to do with decimal, judging by other existing answers, except for a C answer that actually calls `printf` after sign-extending to fill an `int`. (And languages that implicitly print numeric output as a decimal string, but most of the non-golf-language answers are functions that return a number.)

NASM listing: address, machine-code bytes, source

```
                  sign_extend_nbits:
00 F7D9              neg  ecx          ; 32-n = -n after masking to &31
02 D3E0              shl  eax, cl      ; x86 shifts implicitly mask the count &31
04 D3F8              sar  eax, cl
06 C3                ret

```

Try it online!

**Algorithm**: Left shift so the MSB of the narrow input is at the top of the full register (count = 32-n), then arithmetic right-shift back to where it was, leaving the upper bits filled with copies of the MSB. x86 is a 2's complement machine; its arithmetic right shift does 2's complement sign extension.

This problem reduces to 2's complement sign-extension, with no need to read an ASCII string of base 2 digits, as stated by the question's input formats. (But this output format intentionally violates the stated "decimal" output requirement of the question the same way many other answers do. We could `div` in a loop, or maybe `fild` / `fbstp` to make BCD in about twice as many bytes.)

x86 shifts mask their count with `&31` (for 8, 16, and 32-bit operand-size), so the `-n` = `CHAR_BIT*sizeof(int)-n` trick only works for 32 or 64-bit shifts, not 8 or 16. 8086 didn't mask shift counts at all, and I think when they introduced masking for performance reasons in 186 and 286, they wanted to still allow shifting out all the bits of a 16-bit register. But when 32-bit regs were new, masking was already a thing so they could choose whatever semantics they wanted.

---

This "protest" answer is intended to show how trivial the problem is with the stated allowed input formats, if we follow the precedent of other answers ignoring the "decimal" output requirement.

Computers, and most computer languages, use binary integers. In most of those languages, operators like bitwise `n & 1` being the same as `% 2` (for positive numbers), and `x<<1` being the same as `x*2`, prove that numbers are binary. Converting an integer to an array or ASCII string of decimal digits takes extra work, as in https://stackoverflow.com/questions/13166064/how-do-i-print-an-integer-in-assembly-level-programming-without-printf-from-the/46301894#46301894 (Or perhaps use x86 `fild` / `fbstp` to store the float as packed BCD. Yes this instruction exists, and yes it's microcoded and *very* slow)

If you don't want to require that, don't say "decimal", just say "integer".

But don't maybe don't allow input formats that are already 2's complement integers? A C answer of `f(x){return x;}` is arguably valid if we say that the 2's complement input number must already be in an `int`, which is a fixed-width type and thus requires 2's complement sign-extension for valid integers. I decided to support variable widths by taking a value + length instead of just writing a 1-byte `C3 ret` as a full protest answer, to stick to the spirit of what seemed to be the challenge, 2's complement sign extension without any actual conversion necessary.
> 5 votes

# Answer
# JavaScript (Node.js), ~~51~~ 49 bytes

```
s=>2**s.length/2*-s[0]+parseInt(s.slice(1)||0,2)

```

*-2 bytes because dividing by 2 is golfier than subtracting 1 from length*
*-1 byte thanks to Matthew Jensen's suggestion to use `slice` over `substr`*

Try it online!
> 4 votes

# Answer
# APL(Dyalog Unicode), 5 bytes SBCS

Takes input as a vector of digits.

```
2⊥-@1

```

Try it on APLgolf!

Port of att's answer. Negate the first (most significant) bit and convert from base 2.
> 4 votes

# Answer
# MathGolf, 8 bytes

```
å∞l├∞▌å-

```

Input as a string.

Port of *@loopyWalt*'s top Python answer

Try it online.

**Explanation:**

```
å      # Convert the (implicit) input-string from binary to an integer
 ∞     # Double it
l      # Push the input-string again
 ├     # Pop and push its first character
  ∞    # Double it to two of those characters
   ▌   # Prepend it back
    å  # Convert it from a binary-string to an integer
-      # Subtract the two integers from each other
       # (after which the entire stack is output implicitly as result)

```
> 4 votes

# Answer
# Haskell, ~~38~~ ~~32~~ ~~29~~ 27 bytes

*Thanks @Unrelated String and @Bubbler for helping me golf this in TNB chatroom.*

*Thanks @Bubbler for another -2 bytes by directly setting* `-h` *as the initial value of* `foldl`

```
f(h:t)=foldl((+).(2*))(-h)t

```

Try it online!

### Explanation

```
f(h:t)=foldl((+).(2*))(-h)t
f(h:t)=                        list input, with the list's head being h and tail being t
                               example: [1,0,0,1]
       foldl(  ....  )(-h)     starting with initial value -h...
             (+).(2*)     t    iteratively apply the function (+).(2*) == \x y->2*x+y
                               across the list t from left to right
                               this converts from a binary list to decimal, with the
                               head of the list negated
                               example: [1,0,0,1] ->  -1 (initial -h) * 2 + 1 = -1
                                        [0,0,1]   -> -1 * 2 + 0 = -2
                                        [0,1]     -> -2 * 2 + 0 = -4
                                        [1]       -> -4 * 2 + 1 = -7 (output)

```
> 4 votes

# Answer
# Haskell, 21 bytes

```
(0-).foldl1((-).(2*))

```

Try it online!

A modification of Aiden Chow's answer to avoid head-tail dissection.

Given that `(+).(2*)` is a shorthand for `\x y -> 2*x+y`, we can replace `+` with `-` to get `\x y -> 2*x-y`. When used with `foldl1`, the modification has the effect of negating every single number of input list `l`, except the first. Then it suffices to negate back the entire result to get the intended answer.
> 4 votes

# Answer
# Pari/GP, 29 bytes

I don't think this should work but it does.

```
f(v)=v[1]*=-1;fromdigits(v,2)

```

Try it online!
> 4 votes

# Answer
# Pip, 8 bytes

```
-:@ggFD2

```

Takes input as a list of bits, given as separate command-line arguments. Attempt This Online!

### Explanation

Same approach as Jonathan Allen's Jelly answer:

```
-:@ggFD2
   g      List of cmdline args
  @       First element
-:        Negate in place
    g     Updated list
     FD   Convert from a list of digits
       2  In base 2

```
> 3 votes

# Answer
# Charcoal, 10 bytes

```
Ｉ↨ＥＡ⎇κι±ι²

```

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

```
   Ａ        Input array
  Ｅ         Map over elements
     κ      Current index
    ⎇       If nonzero then
      ι     Current bit else
        ι   Current bit
       ±    Negated
 ↨       ²  Convert from base `2`
Ｉ           Cast to string
            Implicitly print

```
> 3 votes

# Answer
# Retina 0.8.2, 46 bytes

```
^1
-
1
01
+`(-|1)0
0$1$1
+`-1|0

^(-?).*
$1$.&

```

Try it online! Link includes test cases. Explanation:

```
^1
-

```

Change a leading `1` to a `-`.

```
1
01
+`(-|1)0
0$1$1

```

Perform binary to unary conversion, counting `-` as a digit, which causes it to be raised to the appropriate power of 2.

```
+`-1|0

```

Subtract the value of the lower order bits from that power of 2.

```
^(-?).*
$1$.&

```

Convert to decimal, keeping the leading sign if the number is negative.
> 3 votes

# Answer
# Ruby, 28 bytes

```
->n{eval"0b#{n}0-0b"+n[0]+n}

```

Try it online!
> 3 votes

# Answer
# APL+WIN, 27 bytes

Prompts for two's compliment as vector of integers

```
(1+¯2×n)×n+2⊥1↓2|(n←↑b)+b←⎕

```

Try it online! Thanks to Dyalog APL Classic
> 2 votes

# Answer
# Desmos, 52 bytes

```
L=l.length-2
f(l)=total(2^{[L...0]}l[2...])-2^Ll[1]2

```

\\$f(l)\\$ takes in a list of bits and outputs the corresponding decimal form.

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# TI-Basic, ~~35~~ 29 bytes

```
sum(Ansseq(2^(dim(Ans)-I)(1-2(I=1)),I,1,dim(Ans

```

Takes input as a list of digits in `Ans`. Output is as an integer in `Ans` and is displayed.
> 2 votes

# Answer
# Javascript (ES2020), 33 chars

```
s=>BigInt.asIntN(s.length,"0b"+s)

```

Test:

```
f=s=>BigInt.asIntN(s.length,"0b"+s)

console.log(`0 -> 0
1 -> -1
111 -> -1
011 -> 3
100 -> -4
1001 -> -7
0001 -> 1`.split`
`.map(x=>x.match(/^(\S+) -> (\S+)$/))
.every(([,s,key])=>f(s)==key))
```
> 2 votes

# Answer
# Piet \+ ascii-piet, 46 bytes

```
tlrdveccsittttttbbbuebV???? vuikuemmaiitdem vV

```

Input the binary as a string space separated bits, with `2` being the sentinel value (`2` is a valid sentinel value because the input only contains `0`'s and `1`'s). For example, `1001` is inputted as `1 0 0 1 2`.

Try It Online!

Image format (46 codels)

Enlarged for clarity (codel size = 50)
> 1 votes

---
Tags: code-golf, math, binary, base-conversion
---