title: Is the checkbox not not unchecked?

text:
# Question
Title: Is the checkbox not not unchecked?
Doing code review, I stumbled upon the following code, that tests the status of a checkbox:

```
if (!isNotUnchecked()) { ... }

```

I had to brainstorm for 30 minutes to find out what actual checkbox status the code was expecting. Please write me a program that can simplify these silly expressions!

---

The program should accept as input a string representing the expression to simplify (for example: `!isNotUnchecked()`). The program should output a logically equivalent simplified expression, either `isChecked()` or `!isChecked()`.

The method name in the input expression always starts with `is`, contains 0..n `Not`, and ends with `Checked()` or `Unchecked()`. The method can be prefixed by any number of `!`.

## Examples

```
isChecked() => isChecked()
isUnchecked() => !isChecked()
isNotChecked() => !isChecked()
!isNotChecked() => isChecked()
!!!isNotNotUnchecked() => isChecked()

```

# Answer
# Python, 51 bytes

```
lambda s:sum(map(s.count,'!NU'))%2*'!'+'isC'+s[-8:]

```

Try it online!
> 32 votes

# Answer
## Retina, 23 bytes

```
Unc
!C
Not
!
O`is|!
!!

```

Try it online!

### Explanation

```
Unc
!C

```

Turn `Unchecked` into `!Checked`.

```
Not
!

```

Turn all `Not`s into `!`. We now get something like `!!!is!!!!Checked()`.

```
O`is|!

```

Sort all matches of either `is` or `!`. Since `! < is`, this moves all the `!` to the beginning of the string, so the above example would become `!!!!!!!isChecked()`.

```
!!

```

Remove pairs of `!` to cancel repeated negation.
> 24 votes

# Answer
# ///, 26 bytes

```
/Unc/NotC//isNot/!is//!!//

```

Try it online!

Port of my Retina answer.
> 14 votes

# Answer
# Python, 43 bytes

```
lambda s:sum(map(ord,s))%2*'!'+'isC'+s[-8:]

```

An unnamed function taking the string, `s` and returning a string.

**Try it online!**

No need to check for existence of characters when `!`, `Not`, and `Un` all have exactly one odd ordinal (and `c` and `C` are both odd), so just sum up the ordinals and use the value modulo 2 to decide if we want a `!` or not.

Other than that the form is the same as xnor's answer, as I didn't find anything better. The following is also 43:

```
lambda s:'!isC'[~sum(map(ord,s))%2:]+s[-8:]

```
> 13 votes

# Answer
## JavaScript (ES6), ~~51~~ 50 bytes

```
f=
s=>(s.split(/!|n/i).length%2?'':'!')+'isChecked()'
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

Works by looking for `!`, `N`, and `n` characters, which invert the checked state. `split` returns an odd array length by default, so we add the `!` when the `split` length is even. Edit: Saved 1 byte thanks to @ETHproductions. Alternative version, also for 50 bytes:

```
s=>`${s.split(/!|n/i).length%2?``:`!`}isChecked()`

```
> 10 votes

# Answer
# Retina, 24 bytes

```
Unc
NotC
+`isNot
!is
!!

```

Try it online!
> 9 votes

# Answer
# Java 7, ~~100~~ 77 bytes

```
String c(String s){return(s.split("[!NU]").length%2<1?"!":"")+"isChecked()";}

```

**Expanation:**

```
String c(String s){  // Method with String parameter and String return-type
  return(s.split("[!NU]").length
                     //  Count the amount of '!', 'N' and 'U' in the input String (+ 1)
    %2<1?            //  and if they are an even number:
     "!"             //   Start with an examination mark
    :                //  Else:
     "")             //   Start with nothing
    +"isChecked()";  //  And append "isChecked()" to that
}                    // End of method

```

**Test code:**

Try it here.

```
class M{
  static String c(String s){return(s.split("[!NU]").length%2<1?"!":"")+"isChecked()";}

  public static void main(String[] a){
    System.out.println(c("isChecked()"));
    System.out.println(c("isUnchecked()"));
    System.out.println(c("isNotChecked()"));
    System.out.println(c("!isNotChecked()"));
    System.out.println(c("!!!isNotNotUnchecked()"));
  }
}

```

**Output:**

```
isChecked()
!isChecked()
!isChecked()
isChecked()
isChecked()

```
> 7 votes

# Answer
# Aceto, 49 bytes

```
&M"pp"
L!)(de
&c;`Che"
`!d!sick
!',@p"!'
'N'U`!Lu

```

yadda yadda Hilbert curve.

First of all, we push the three important characters on the stack:

```
!'
'N'U

```

Then we set a catch mark and start by reading a single character. We `d`uplicate it and negate it, and if the result of this is truthy (so if the string was empty; so the input ended), we jump to the end:

```
;`
d!
,@

```

With the remaining copy of the input character, we check whether it is contained in the rest of the stack (i.e. if its one of !, N, U). If it's not, we raise an error, throwing us back to our catch mark where we read another character:

```
&c
`!

```

Otherwise, we load what's on quick storage (essentially a register that's initially an empty string; falsy), negate it and send it back to quick storage, then raise the error too (going back to reading characters):

```
&M
L!

```

When the input stopped, we are sent to the end. There, we reverse the direction, push an exclamation mark, and load quick storage and negate it. If that is truthy (i.e. we've had an odd number of negation things), we print the exclamation mark we've pushed:

```
p !'
`!Lu

```

Finally, we push the string in two parts and print them (for space saving reasons):

```
"pp"
)(de
  Che"
  sick
   "

```

Afterwards, the program still runs back to the original beginning, but since none of the commands output anything or have loopy behaviour, that doesn't matter. Actually, the first non-nopping command we reach raises an exception, skipping a majority of the code because we jump to the catch mark, meaning all Aceto sees in that part is:

```
&

!' @
'N'U

```

Since `U` is now not preceeded by a single-quote character and is therefore not seen as a character literal, it gets interpreted as a command: `U` reverses all the elements on the stack (now it's `!`, `N`, `U`, from the top), and `'N` and `'!` push more characters, meaning we end with the stack `[U, N, !, N, !]`.

*Side note: This is the first Aceto program written (in part) with the help of Aceto's new editor.*
> 7 votes

# Answer
## C, ~~78~~ ~~70~~ 68 Bytes

Thank you Christoph!

```
c;f(char*s){for(c=1;*s;)c^=!!strchr("!NU",*s++);s="!isChecked()"+c;}

```

Try it online

Output:

```
isChecked() => isChecked()
isUnchecked() => !isChecked()
isNotChecked() => !isChecked()
!isNotChecked() => isChecked()
!!!isNotNotUnchecked() => isChecked()

```
> 6 votes

# Answer
# Perl 5, 31 bytes

*-2 bytes thanks to @Dom Hastings.*

30 bytes of code + `-p` flag.

```
/c/i;$_="!"x(y/UN!//%2).isC.$'

```

Try it online!

`y/UN!//` counts the number of occurrences of `Un`, `Not`, and `!`. The result is that many `!` modulo 2, followed by `isChecked()`.

---

Another attempt, based on regex, for 38 bytes (Dom Hastings saved 1 byte on that one):

```
s/isNot|isUn(c)/!is\u$1/?redo:s/!!//g

```

Try it online!
> 6 votes

# Answer
# Scala, ~~39~~ 30 bytes

```
s=>"!"*(s.sum%2)+"isChecked()"

```

Try it online!

Unfortunately I couldn't get it to deduce the type of s.

Edit: Moved the type declaration to the header (I think this is allowed, if not I'll put it back).
> 6 votes

# Answer
# Ruby, 40 bytes

```
->x{?!*(x.count('!UN')%2)+'isChecked()'}

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 22 bytes

```
…Unc„!C:'€–™'!:'!†„!!K

```

Try it online!
> 3 votes

# Answer
## PHP (5.5 - 5.6), ~~52~~ ~~50~~ 49 Bytes

```
<?='!'[count(spliti('!|N',$argn))%2]?>isChecked()

```

Try it here.

```
-2 Bytes by @Titus. Ty :)
-1 Byte  by @ETHproductions. Ty :)

```

## PHP (\>=5.5), ~~66~~ ~~65~~ 61

```
for($b=b;$a=$argn[$i++];)$b^=$a;echo$b&"!"|" ","isChecked()";

```

Without regex it gets a bit more compex :) Try it here.

```
-4 Bytes by @Titus. Ty :)

```
> 3 votes

# Answer
# Jelly,  ~~16~~  15 bytes

```
OSḂ⁾!iṫ⁾sCø³ṫ-7

```

A full program that takes the string as a command line argument and prints the result

**Try it online!**

`OSḂ⁾!iṫ-7³ṫṭ⁾sC` or `OSḂ⁾!iṫ-7³ṫ⁾sC;` would both also work for 15.

### How?

Uses the same idea as my Python answer, but saves bytes using a different construction of `!isC` or `isC` and some implicit printing in Jelly...

```
OSḂ⁾!iṫ⁾sCø³ṫ-7 - Main link: s
O               - cast to ordinals
 S              - sum
  Ḃ             - mod 2
   ⁾!i          - literal ['!','i']
      ṫ         - tail -> ['i'] if OSḂ was 0; ['!','i'] if OSḂ was 1
                - this is printed due to the following starting a new leading
                - constant chain. Printing smashes so either "i" or "!i" is printed.
       ⁾sC      - literal ['s','C']
                - this is printed (as "sC") due to the following niladic chain.
          ø     - start a new niladic chain
           ³    - program's first input (3rd command line argument), s
            ṫ-7 - tail from index -7 = ['h','e','c','k','e','d','(',')']
                - implicit print (of "hecked()")

```

previous @ 16 bytes 9 (using concatenation and pairing with the same underlying idea):

```
OSḂ⁾!iṫ;⁾sC,ṫ€-7

```
> 3 votes

# Answer
# 05AB1E, 16 bytes

```
ÇOÉ'!×…isCyR8£RJ

```

Try it online!

Uses the trick of summing the ordinals from Jonathan Allan's python answer.

**Explanation**

```
 ÇO                # sum of ascii values of input
   É               # is odd
    '!×            # repeat "!" that many times
       …isC        # push the string "isC"
           IR8£R   # push the last 8 chars of input
                J  # join everything to string

```
> 3 votes

# Answer
# Japt, ~~24~~ 23 bytes

```
o"!N" l u)ç'! +`‰C”×B()

```

# Explanation

```
 o"!N" l u)ç'! +`‰C”×B()
Uo"!N" l u)ç'! +`‰C”×B()`
Uo"!N"                     # Only keep "!", "n" and "N" from the input
           ç'!             # Repeat the string "!" by
       l u)                # the parity of the length of the newly formed string
               +`‰C”×B()` # and concatenate with the string "isChecked()"

```

Try it online!
> 3 votes

# Answer
## Mathematica, ~~82~~ ~~61~~ 60 Bytes

Small tweak, added one more infix operator:

```
"!"~Table~Mod[#~StringCount~{"o","n","!"},2]<>"isChecked()"&

```

Previously:

```
"!"~Table~Mod[StringCount[#,{"o","n","!"}],2]<>"isChecked()"&

```

Count up all the o's, n's and !'s then mod 2 and put that many ! in front.

Old version:

```
"!"~Table~Mod[StringCount[StringReplace[#,{{"o","n"}->"!"}],"!"],2]<>"isChecked()"&

```
> 2 votes

# Answer
# sed, ~~37~~ 38 bytes

```
:;s/is(Not|Un)/!is/;s/!!//;t;s/ch/Ch/

```

37 + 1 for `-r` switch:

```
sed -r ':;s/is(Not|Un)/!is/;s/!!//;t;s/ch/Ch/'

```
> 2 votes

# Answer
# Perl 6,  ~~35~~  31 bytes

```
{'!'x m:g/<[!NU]>/%2~'isChecked()'}

```

Try it

```
{'!'x tr/!NU//%2~'isChecked()'}

```

Try it
(requires mutable input string which will be mutilated)

## Expanded:

```
{
  #(
    '!'
  x               # string repeat

    # m:g/<[!NU]>/
    tr/!NU//      # find the number of negatives
      % 2         # modulus 2
  #)

  ~                # string concat

    'isChecked()'
}

```
> 2 votes

# Answer
# Sed, 36 Bytes

Same idea as all the other direct substitution answers.

```
:
s/Unc/NotC/
s/isNot/!is/
s/!!//
t

```
> 2 votes

# Answer
# Windows Batch, 120 bytes

Previously 268 257 253 245 239 221 182 176 169 123 bytes

```
@set a=%1
@set s=#%a:~,-2%
@set s=%s:!=N#%
@for %%a in (%s:N= %)do @set/ac+=5
@if %c:~-1%==0 cd|set/p=!
@echo isC%a:~-8%

```

The programs replaces all the `!` into `N#`. Because now all negation signs, !(Now it is `N#`), `Not`, and `Un` contains `N`, the program can counts the number of appearance of `N` and determines if an leading `!` is required.

Each time the program counts an `N`, the counter is added by 5. The reason for adding 5 is because each alternating values when adding 5 ends in either 0 or 5. This can be used to determine whether the value is odd or even and the leading `!` us added if required.

In addition, xnor's last-eight-character trick is utilized.
> 2 votes

# Answer
# Excel, 90 bytes

```
=IF(ISODD(SEARCH("C",SUBSTITUTE(SUBSTITUTE(A1,"Un","!"),"Not","!"))),"","!")&"isChecked()"

```
> 2 votes

# Answer
# PHP, 55 Bytes

```
<?=preg_match_all("#!|N#i",$argn)&1?"!":""?>isChecked()

```

Try it online!

# PHP, 58 Bytes

```
<?=preg_match_all("#[!NU]#",$argn)%2?"!":"","isChecked()";

```

instead `"#[!NU]#"` you can use `"#[!N]#i"`

Try it online!

# PHP, 68 Bytes

Version without Regex

```
for(;$c=$argn[$i++];)$d^=!trim($c,"UN!");echo"!"[!$d],"isChecked()";

```

Try it online!
> 1 votes

# Answer
# Jelly, ~~29~~ ~~28~~ ~~25~~ 21 bytes

```
f“NU!”LḂ”!x;“µịÆẹṠƊẹ»

```

Try it online!

```
f“NU!”LḂ”!x;“µịÆẹṠƊẹ»  Main link, argument is z
f“NU!”                 Filter to only keep "NU!"
      LḂ”!x            Repeat exclamation mark by the parity of the length
           ;“µịÆẹṠƊẹ»  Concatenate to "isChecked()"

```

-4 bytes thanks to Jonathan Allan!
-4 bytes thanks to Jonathan Allan! (by using compressed strings)
> 1 votes

# Answer
# Japt, 19 bytes

```
`‰C”×B()`i'!pU¬xc u

```

Try it online!

### Unpacked & How it works

```
`‰C”×B()`i'!pUq xc u

`‰C”×B()`   Compressed string for "isChecked()"
i     Insert the following string at the beginning...
'!p     "!" repeated the following number of times...
Uq        Split the input into chars
xc        Sum the charcodes
u         Modulo 2

```

Using the charcode-sum trick from Jonathan Allan's Python solution.
> 1 votes

# Answer
# Pascal (FPC), 119 bytes

```
var s:string;j:word;c:char;begin read(s);for c in s do j:=j+ord(c);if 1=j mod 2then write('!');write('isChecked()')end.

```

Try it online!

Using method that almost every answer does, summing codepoints of characters in the input, then checking parity of the sum.
> 1 votes

# Answer
# ReRegex, 32 bytes

```
/!!//Not/!/Unc/!C/is!/!is/#input

```

## Explained

Works like the Retina answer

```
/!!//                            #Remove all !! pairs
     Not/!/                      #Replace all Nots with !s
           Unc/!C/               #Replace any Unc's with !C (Turning Unchecked into !Checked)
                  is!/!is/       #Float all !'s past the is to the left
                          #input #Take the stdin as input

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Find the most important character

text:
# Question
Title: Find the most important character
# Find the most important character

The challenge is to write a program that outputs the most occurrent character in the input string, excluding these bracketing characters `()[]{}`. Each submission should consist only of non-trivial\* characters. Each solution is scored using the formula in the scoring section. Bracketing characters are allowed in the program, but may not be selected by the program as the most occurrent character. In cases where letters occur with the same frequency, any or all of the characters may be returned.

\*Non-trivial is defined in this case to be a character that contributes to the functionality of the program. If the character can be removed without influencing how the program runs, it is a trivial character.

## Scoring

Score is determined as follows:

$$(\frac{n\_{char}}{n\_{total}}) * 100(\\%) $$

With nchar being the number of occurrences of the most frequent character in the input, and ntotal being the total number of non-trivial characters in the input. With this scoring criteria, all scores should be within the range \\$\[0,100\]\\$

Highest scoring solution per language wins.

## Input

Solutions should take in any valid string as input. A convenient method of determining the most occurrent character in the program itself would be to use the program's source code as input to the program itself. The program does not have to check for non-trivial characters, as they should not be included in the program source.

## Output

A single character with the highest percentage occurrence. Each solution should be capable of outputting standard ASCII, as well as the language's codepage (if applicable).

## Errata

Creative solutions are encouraged. Boring solutions with long padded strings substituted in for numbers are discouraged. Standard loopholes are disallowed.

## Examples

Program:

`aabbbc`

Output:

`b`

---

Program:

`aabb`

Output:

`a` or `b` or `ab`

---

Sandbox Link

# Answer
> 6 votes
# 05AB1E, 99.999999999999999957%

```
1111111111111111111 ... (9352835025086960662 1's total) ... 11111g₅B.V

```

`g` gets the length of the large integer literal. Obviously this is too long for TIO, so try a version using 9352835025086960662 instead of the equivalent 1111...1111g.

# Answer
> 3 votes
# JavaScript (Node.js), 55.85% (or much more)

```
s=>eval(Buffer((g=n=>n?[+[n&127n],...g(n>>7n)]:[])(0b1001111010011001001100101001101110111000110111101100111110110111101111011110111011010111010011000001111111101101011110001010011011101110001110110111101111111111001011010111101101110111000111011011110111101010000111110011110111000110101100110011101011111011101101110110111001011011111110111110110101001010100010111101011011010111101111011101111011110111011010101000110010111000111100001110110011100001100101111001001011101110011n))+'')

```

Try it online!

This is a 'fair' version, in that only the payload binary data is included (7 bits per character). But the score could be made arbitrary large by padding each encoded character with as many zeros as desired. They would still be 'non-trivial' as per the challenge rule, as removing any of them would break the decoding.

The binary string is decoded as:

```
s.replace(m=o=/[^(){}[\]]/g,c=>(o[c]=-~o[c])<m?0:m=o[O=c])&&O

```

# Answer
> 3 votes
# PHP, 75%

```
foreach(count_chars($argn)as$c)$o[]=$c*'1111111111111111111111111111111111111111001111111111111111111111111111111111111111111111111010111111111111111111111111111110101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'[$i++];arsort($o);echo chr(key($o));

```

Try it online!

Ungolfed:

```
// table of valid input chars - ASCII 0-255
// index is the ASCII number, and 1 or 0 if it is valid
$valid_chars = '1111111111111111111111111111111111111111001111111111111111111111111111111111111111111111111010111111111111111111111111111110101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111';

// get input string and aggregate count of each letter
$counted_chars = count_chars( $argn );

// iterate through each
foreach( $counted_chars as $ascii => $count ) {
    // multiply count by either 1 if valid or 0 if not
    $out[] = $count * $valid_chars[ $ascii ];
}

// sort resulting list descending
arsort( $out );

// display the ASCII value of the "most popular" valid char
echo chr( key( $out ) );

```

Counts the frequency of each character and uses a lookup table to to determine if a given character is excluded (example: `()[]{}`) from being counted. Sorts by frequency and returns the "most important" remaining char.

Note: PHP's `count_chars()` only counts ASCII chars `0-255` which corresponds to the array of valid chars, so is not arbitrarily or unnecessarily long. Using a lookup table of flags to test the validity of a result is, while not the most efficient in this case, a valid and commonly-used programming practice.

# Answer
> 1 votes
# 05AB1E, tends to 50%

```
'""{}[]()"'""м.M"J".V"".V"".V".V

```

Try it online!

You can keep appending `".V"` before the final J, any part of this string can't be removed and hence none of the characters themselves are non-trivial. Hence this tends to 50% of the program being " as you add more `".V"`

Note: you couldn't have a single char command to tend to 66% inside the brackets like `"J"` as it can likely be shortened to `""`

# Answer
> 0 votes
# C (gcc), 13.2% `;`

```
float m;a[256];l;t;c;n(char*s){bzero(a,1024);l=0;for(;*s;){a[*s]++;s++;l++;};m=0;t=0;for(;t++<255;)if(a[t]>m)c=t,m=a[t];m*=100;printf("%c %f\n",c,m/l);}

```

This version doesn't pad the end with semicolons. It only contains a few unneeded ones to push up my score to the next percent.

Feel free to add semicolons up until you get 100%.

Try it online!

---
Tags: string, code-challenge
---


title: Count regex matches

text:
# Question
Title: Count regex matches
# Your task

Given a *simple* regular expression, you have to count how many strings of length `n` have a match of length `n` with the given *simple* regex. This will just be a subset of regexs. Like, no lookaheads or named groups or recursion or whatever weird things regexs have.

# Simple regular expression

For the purposes of this challenge, a regex is said to be *simple* if, for one, it only contains characters in the ASCII range `32-126`. Furthermore, it should only use the following functionalities:

* match literal characters, much like the regex `abc` would only match the string "abc";
* match options, like `abc|def` would match "abc" and "def";
* match exactly 0 or 1 occurrence of something, e.g. `https?` matches "http" and "https";
* match 1 or more occurrences of something, e.g. `ah+` would match "ah", "ahh", "ahhh", "ahhhh", etc;
* match any amount of occurrences of something, e.g. `1*` matches "", "1", "11", "111", "1111", etc;
* match between `n` and `m` occurrences of something, e.g. `lo{1,4}l` matches only "lol", "lool", "loool" and "looool". If `n` is ommited, it matches up to `m` occurrences. If `m` is ommited, it matches at least `n` occurrences. Assume at least one of `n` or `m` is present;
* use `()` to group, e.g. `ab(c|d)ef` would match "abcef" and "abdef" (c.f. 2nd item in this list) or `(10)+` would match "10", "1010", "101010", "10101010", etc;
* use `.` to match any character (in the ASCII range `[32, 126]`), so `ab.` would match "abc", "ab9", "ab)", etc;
* use `\` to escape the special meaning of a character, e.g. `ab?` would match "a" and "ab", while `ab\?` only matches "ab?";
* use `[]` as a group of possible characters. Inside the brackets, all characters lose their special behaviours, except for `-` and `\`. This means that, for one, `ab[cde]` is shorthand for `ab(c|d|e)` and secondly, `ab[?+*]` matches "ab?", "ab+" and "ab\*"; also related to `[]`:
* use `-` to specify a character range within brackets. The ranges you have to support are `a-z`, `A-Z` and `0-9`, as well as their subsets, like `h-z` or `3-8`. E.g., the regex `ab[c-g]` matches "abc", "abd", "abe", "abf" and "abg"; Note that `-` has no special meaning outside of `[]` so `a-z` would only match "a-z".

# Input

The input for your program/function/routine/etc should be a string representing the regex and an integer `n`. For the regex, you can further assume:

* all characters that show up are in the ASCII range `[32, 126]`
* if `{n,m}` is used, then \\$n \leq m \\$
* if `-` is used inside `[]` then the specified range is well-formed

# Output

The number of strings of length `n` that match the given regex. You only have to account for characters in the ASCII range `[32, 126]`.

# Test cases

```
".*", 0 -> 1
".*", 1 -> 95
".*", 2 -> 9025
".*", 3 -> 857375
".*", 4 -> 81450625
"abc", 2 -> 0
"abc", 4 -> 0
"ab|ac|ad", 2 -> 3
"a(b|c)", 2 -> 2
"hell(o|oo)", 5 -> 1
"https?", 5 -> 1
"ho{1,4}ly", 6 -> 1
"ho{3,}ly", 137 -> 1
"[abcde]{,2}", 2 -> 25
"(10)+", 7 -> 0
"(10)+", 8 -> 1
"ab\?", 3 -> 1
"[t7]h[i1][s5] is c[0o]d[Ee3] g[0oO][l1L]f", 17 -> 432
"\+351 9[1236] [0-9]{3,3} [0-9]{2,2} [0-9][0-9]", 17 -> 40000000
"-", 1 -> 1
"\\", 1 -> 1
"[+?*]", 1 -> 3
"Abc([d-z]*|(.H)+)", 11 -> 5132188812826241
"ab|ab", 2 -> 1
".(.(.(.(.|a))))|hello", 5 -> 7737809375

```

---

This is code so shortest solution in bytes, wins. If you like this challenge, consider upvoting it... And happy golfing!

# Answer
# Java 10, ~~356~~ ~~342~~ ~~284~~ ~~275~~ ~~233~~ ~~225~~ 220 bytes

```
import java.util.*;List S;r->k->{S=new Stack();p("",k);k=0;for(var p:S)k+=(p+"").matches(r.replaceAll("\\{(,\\d+\\})","{0$1"))?1:0;return k;}void p(String p,int k){if(k<1)S.add(p);else for(char i=32;i<127;)p(p+i++,k-1);}

```

Works, but way too slow for \\$n\geq4\\$.

Try it online.

**Explanation:**

```
import java.util.*; // Required import for Stack and List
List S;             // List on class-level, uninitialized

k->r->{             // Method with integer and String parameter and integer return-type
  S=new Stack();    //  Create a new List
  p("",k);          //  Put all permutations of length `k` consisting of printable ASCII
                    //  characters in this list
  k=0;              //  Re-use `k` as counter-integer, starting at 0
  for(var p:S)      //  Loop over all permutations in the List:
    k+=             //   Increase the counter by:
       (p+"")       //    Convert the permutation from Object to String
       .matches(r   //    If it matches the input-regex,
         .replaceAll("\\{(,\\d+\\})","{0$1"))?
                    //    after we've replaced all {,m} with {0,m}
          1         //     Increase the counter by 1
       :            //    Else:
          0;        //     Leave the count the same by increasing with 0
  return k;}        //  And return the counter as result

void p(             // Separated method with two parameters and no return-type, where:
    String p,       //   `p` is the prefix-String, starting empty
    int k){         //   `k` is the length the permutations we want to generate
  if(k<1)           //  If `k` is 0:
    S.add(p);       //   Add the current prefix-String to the List
  else              // Else:
    for(char i=32;i<127;)
                    //  Loop over the printable ASCII characters:
      p(            //   And do a recursive call, with:
        p+i++,      //    The prefix-String appended with the current character
        k-1);}      //    And `k` decreased by 1

```

Some notes:

* Java's regex only supports `{n,m}` and `{n,}`, since `{,m}` could be written as `{0,m}`.
* And Java's `String#matches` builtin implicitly adds a leading `^` and trailing `$` to check the entire String.
> 6 votes

# Answer
# Python 3, ~~139~~ ~~137~~ 129 bytes

Saved 2 naughty bytes thanks to @Kevin, then 6 thanks to @ovs and then 2 more by rewriting `f`, thanks to @wilkben!

```
lambda r,n:sum(1for s in map(''.join,i.product(map(chr,range(32,127)),repeat=n))if re.match(f"^{r}$",s))
import re,itertools as i

```

You can try the smaller test cases online. My solution generates all strings of length `n` with the generator `g` and then tries to match the regex to the whole string. If the test case is the regex `r`, I use the regex `^r$` to force the match to be on the whole string.
> 3 votes

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

Another brute-force solution taking input as `(n)(regex)`.

```
n=>g=(p,s='',c=127)=>n*!s[n-1]?--c>>5&&g(p,s+Buffer([c]))+g(p,s,c):!!s.match(`^${p}$`)

```

Try it online!

### Commented

```
n =>                      // n = target string length
  g = (                   // g is a recursive function taking:
    p,                    //   p = regex pattern
    s = '',               //   s = current string
    c = 127               //   c = current ASCII code
  ) =>                    //
    n * !s[n - 1] ?       // if n is not equal to 0 and s is less than n char. long:
      --c >> 5 &&         //   decrement c; if it's greater than or equal to 32:
      g(                  //     do a 1st recursive call where:
        p,                //
        s + Buffer([c])   //       the character with ASCII code c is added to s
                          //       c is not passed so that it's reset to 127
      ) +                 //
      g(                  //     do a 2nd recursive call where:
        p, s, c           //       this value of c is discarded
      )                   //
    :                     // else:
      !!s.match(`^${p}$`) //   return true (1) if s matches p, or false (0) otherwise

```
> 3 votes

# Answer
# perl -E, 79 bytes

```
($,,$")=@ARGV;@@="";@@=map{$,=$_;map$,.chr,32..126}@@for 1..$,;say~~grep/$"/,@@

```
> 1 votes

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


title: Are They Similar Polygons?

text:
# Question
Title: Are They Similar Polygons?
# Task

Given the x,y coordinates (coordinates are guaranteed to be integers) of the vertices of two simple polygons in clockwise or anti-clockwise order. Output a Truthy value if both the polygons are similar otherwise a Falsy value

A simple polygon is a polygon that does not intersect itself and has no holes. That is, it is a flat shape consisting of straight, non-intersecting line segments or "sides" that are joined pairwise to form a single closed path. If the sides intersect then the polygon is not simple. Two edges meeting at a corner are required to form a an angle that is not not straight (180°)

Two polygons are similar if either polygon can be rescaled, repositioned, and reflected, so as to coincide precisely with the other polygon.

# Testcases

**Input**

```
[(0, 0), (1, 0), (1, 1), (0, 1)]
[(-1, 0), (2, 1), (1, 4), (-2, 3)]

```

Graph

**Output**

```
Truthy

```

---

**Input**

```
[(2, 3), (0, 0), (4, 0)]
[(-3, 0), (-2, 2), (0, 1), (1, -1), (-1, -2), (-2, -2)]

```

Graph

**Output**

```
Falsy

```

---

**Input**

```
[(1, 4), (1, 3), (0, 2), (1, 1), (-3, 2)]
[(2, 0), (2, -1), (3, -1), (4, -2), (-2, -2)]

```

Graph

**Output**

```
Falsy

```

---

**Input**

```
[(-1, 0), (2, 1), (1, 4), (-2, 3)]
[(1, 4), (2, 1), (-1, 0), (-2, 3)]

```

Graph

**Output**

```
Truthy

```

---

**Input**

```
[(-2, 0), (-1, 1), (0, 1), (1, 3), (1, 0)]
[(5, 4), (4, 2), (3, 2), (2, 1), (5, 1)]

```

Graph

**Output**

```
Truthy

```

---

**Input**

```
[(2, 13), (4, 8), (2, 3), (0, 8)]
[(0, 0), (5, 0), (8, 4), (3, 4)]

```

Graph

**Output**

```
Falsy

```

---

**Input**

```
[(-1, 0), (-5, 3), (-5, 9), (-1, 6)]
[(0, 0), (5, 0), (8, 4), (3, 4)]

```

Graph

**Output**

```
Falsy

```

---

**Input**

```
[(0, 0), (1, 2), (1, 0)]
[(2, 0), (2, 2), (3, 0)]

```

Graph

**Output**

```
Truthy

```

---

# Answer
# Mathematica, 97 bytes (SBCS)

```
Or@@(Equal@@(a@u/#)&/@(a/@NestList[RotateLeft,v,Length@v]))
a@l_:=Norm[#〚1〛-#〚2〛]&/@l~Subsets~{2}

```

You can try it online!

The function `a` computes all the pairwise distances between any two vertices of the polygon.

The main function applies this to the first list and to every rotation of the second list, to try and find the corresponding vertices. The rotation of the second list is correct if all the corresponding distances have been scaled accordingly.

Thanks to @J42161217 for saving me some 3 bytes
> 5 votes

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


# Question
Title: Convert a string to its Rövarspråket equivalent
## Rövarspråket

Rövarspråket is a word game played by Swedish children, from the books about Kalle Blomkvist by Astrid Lindgren.

The basic rules are as follows (from Wikipedia):

* Every consonant (spelling matters, not pronunciation) is doubled, and an o is inserted in-between.
* Vowels are left intact.

A few examples:

* "hello" -\> "hohelollolo"
* "Min svävare är full med ål" -\> "MoMinon sosvovävovarore äror fofulollol momedod ålol"

Swedish consonants are the same as the English ones, so the program should work with both Swedish and English entries.

The letter "y" is taken as a consonant in this case - as most of the time it is.

---

## Your Task:

Write a program to convert a string of Swedish letters, inputted through a function or through stdin, into its Rövarspråket equivalent. Shortest answer in bytes wins!

# Answer
# Retina, 14 + 5 = 19 bytes

Retina is a language that is essentially just .NET regex with as little overhead as possible. The code for this program consists of two files:

```
i`[b-z-[eiou]]

```

```
$0o$0

```

This reads the input on STDIN and prints the output to STDOUT.

If you call the files `pattern.rgx` and `replacement.rpl`, you can run the program simply like

```
echo "hello" | ./Retina pattern.rgx replacement.rpl

```

## Explanation

This is pretty straightforward, but let me add some explanation anyway (mostly about how Retina works). If Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.

Retina can be configured (which includes `RegexOptions` and other options) by prepending the regex with ``` and a configuration string. In this case I'm only giving it `i` which is the normal regex modifier for case insensitivity.

As for the regex itself, it uses .NET's character class subtraction to match any consonant in the ASCII range. The replacement then just writes the match back twice with an `o` in between.
> 14 votes

# Answer
**Using Unix KSH ~~27~~ ~~28~~ ~~32~~ 27 bytes** (or 21 if we only count inside sed command)

Thanks to the suggestions of others :) Appreciated.

.. I got down to this:

```
sed 's/[^AEIOUÅÄÖ ]/&o&/ig'

```

(allowed for spaces and Swedish characters)

```
echo "hello" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
hohelollolo
echo "HELLO" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
HoHELoLLoLO
echo "QuIcKlY Now" | sed 's/[BCDFGHJ-NP-TV-Z]/&o&/ig'
QoQuIcocKoKlolYoY NoNowow

```
> 12 votes

# Answer
# CJam, ~~32~~ 30 bytes

```
q{_eu'[,66>"EIOU"-#)g{'o1$}*}/

```

This is a full program reading from STDIN and printing to STDOUT. It works for arbitrary Unicode input and treats the following 42 characters as consonants:

```
BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz

```

Test it here.

## Explanation

```
q                              "Slurp STDIN.";
 {                          }/ "For each character...";
  _eu                          "Duplicate and convert to upper case.";
     '[,66>                    "Get a string from B to Z using range and slice.";
           "EIOU"-             "Remove the remaining four vowels.";
                  #            "Find the position of the character in this string or
                                -1 if the character can't be found.";
                   )g          "Increment, take signum, which gives 1 for consonants,
                                and 0 otherwise.";
                     {    }*   "Repeat this block that many times, i.e. do nothing for
                                non-consonants.";
                      'o       "Push an 'o'.";
                        1$     "Copy the current character.";

```
> 8 votes

# Answer
# JavaScript, ~~59~~ ~~57~~ ~~55~~ ~~44~~ bytes

```
s=>s.replace(/(?![eiou])[b-z]/gi,"$&o$&")

```

Thanks to Masterzagh for reminding me that a function would be acceptable as well, and for his regex tip regarding backreferences without capturing!

Longer version with input/output:

```
alert(prompt().replace(/(?![eiou])[b-z]/gi,"$&o$&"));

```

Displays a prompt box to enter the string, then shows a dialog containing the Rövarspråket output. The code uses a regex to double the consonants and insert `o`s.
> 5 votes

# Answer
# Julia, ~~46~~ 44 bytes

```
t->replace(t,r"(?![eiou])[b-z]"i,s->s*"o"*s)

```

This creates an anonymous function that takes a single string input and prints the Rövarspråket equivalent. To call it, give it a name, e.g. `f=t->...`.

Not much has really been golfed here, other than spaces after the commas in `replace()`.

Here we're using 3 arguments in the `replace()` function: the input string, the regular expression for identifying substrings, and a replacement. Julia denotes regular expression patterns by `r"..."`. Adding `i` to the end makes it case insensitive. This particular regex matches consonants. If a function is used for the replacement, the output is that function applied to each matched substring. The function we're using here takes a string `s` and returns `sos`, since `*` performs string concatenation in Julia. Thus the end result is the input string with each consonant doubled with an "o" between.

Examples:

```
julia> f("Min svävare är full med ål")
"MoMinon sosvovävovarore äror fofulollol momedod ålol"

julia> f("hello")
"hohelollolo"

julia> f("Rövarspråket")
"RoRövovarorsospoproråkoketot"

```

Note that this will be 9 bytes longer if we have to print the result rather than return it. Awaiting confirmation from the OP.

---

**Edit:** Saved 2 bytes thanks to Martin Büttner!
> 4 votes

# Answer
# Mathematica, ~~84~~ ~~73~~ 72 bytes

```
StringReplace[#,a:RegularExpression@"(?i)[BCDFGHJ-NP-TV-Z]":>a<>"o"<>a]&

```

Explanation:

* `RegularExpression@"(?i)[BCDFGHJ-NP-TV-Z]"` is a regex matching all consonants case-insensitively.
* `a:*..*:>a<>"o"<>a` creates a delayed rule to bind those consonants to `a`, and replace it with and o surrounded by itself.
* Finally, `StringReplace[#,*..*]&` creates a pure function applying that rule to every matching letter in its argument.
> 4 votes

# Answer
# Haskell, 81 bytes

```
x n|elem n"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"=[n,'o',n]|1<2=[n]
f=(>>=x)

```

Usage: `f "Hello there!"` -\> `"HoHelollolo tothoherore!"`.

I cannot cleverly construct the list of consonants without expensive `import`s. Even turning the letter to check to lowercase needs more bytes than simply listing both upper and lowercase consonants.
> 3 votes

# Answer
# Java 8, 45

Use as a lambda function. Uses regular expression.

```
a->a.replaceAll("(?i)[b-z&&[^eiou]]","$0o$0")

```

Try here
> 3 votes

# Answer
# Python, 61

I couldn't get a character class union or subtraction to work, and so I don't think Python has that feature. I had to use a negative lookahead instead.

```
import re;f=lambda s:re.sub('(?i)(?![eiou])([b-z])',r'\1o\1',s)

```

Run it here: http://repl.it/fQ5

Link to the inverse: https://codegolf.stackexchange.com/a/48182/34718
> 2 votes

# Answer
# C 106

**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**

```
x;main(c){for(;read(0,&c,1);printf("%s%s%s"+x*2,&c,x+"o",&c))x=c<66|c>122|c>90&c<98||index("EIOUeiou",c);}

```

Try it online!
> 2 votes

# Answer
# Perl, 33 Bytes

This answer is mostly regex-only, with a small amount of extra code to perform I/O.

```
$_=<>;s/[^aeiou\W]/$&o$&/gi;print

```

It's been a while since I've used Perl regexes, so this can probably be improved.

```
$_=<>;                              This takes input from STDIN `<>` and stores
                                    it into the default variable $_
      s/          /     /gi;        This is a case-(i)nsentive, (g)lobal,
                                    (s)ubstitution regex.  Since no other
                                    variable is specified, it is applied to
                                    the default variable $_.
        [^aeiou\W]                  This matches any single character that
                                    is a consonant, by using a double-
                                    negative ^\W to match only alphanumeric
                                    characters excluding vowels.  Accented
                                    vowels are not considered alphanumeric
                                    by Perl.
                   $&o$&            This forms the replacement.  $& contains the
                                    match (the consonant), so this replaces each
                                    consonant with two copies of itself with
                                    an 'o' in between.
                            print   This prints the result.  With no arguments,
                                    it prints $_ by default.

```
> 2 votes

# Answer
## **Windows Batch, 235 bytes**

```
@echo off
setlocal enabledelayedexpansion
set d=qwrtypsdfghjklzxcvbnm
set #=%1
:x
if defined # (
for /l %%i in (0,1,20)do (
set m=!d:~%%i,1!
if /i !m!==%#:~0,1% set g=!g!!m!o)
set g=!g!%#:~0,1%
set #=%#:~1%
goto x)
echo %g%

```

Usage:

```
script.bat hello

```

Output:

```
hohelollolo

```

You might be wondering why I didnt set d to "aoui", checking for not-equals requires breaking out of a loop. Not everything that should work, does work, in batch. The script handles 1 word of characters \[as they appear on your keyboard\]. All spaces and newlines that are still present are required for the script to run.

*Windows XP or higher, required. Not tested in Windows 8 and above.*
> 2 votes

# Answer
## **PowerShell - 35 bytes**

Just to show that PowerShell can compete in these sometimes too, and with the regex shamelessly stolen from Martin Büttner's Retina answer:

```
%{$_-replace'[b-z-[eiou]]','$0o$0'}

```

accepts string input from stdin
> 2 votes

# Answer
# 05AB1E, 16 15 13 bytes

-2 bytes thanks to Kevin Cruijssen

```
žNDu«SD'o«€Ć‡

```

Try it online!
> 2 votes

# Answer
# Pyth - 28 bytes

This is works in the obvious way by generating the consonants list on the fly using set-wise difference.

```
FNzpk+N?+\oN}rNZ-{G{"aeiou"k

```

Explanation coming soon.

Try it here.
> 1 votes

# Answer
# Clip 10, 30

```
gx"((?i)[b-z&&[^eiou]])""$1o$1

```

Basic regex substitution.
> 1 votes

# Answer
# Pyth, 25 24 23

```
sm+d*+\od}rd0-G"aeoui"z

```

Run it here.
> 1 votes

# Answer
# K, 38 chars

```
f:{,/(1+2*~(_x)in"aeiouåäö ")#'x,'"o"}

-1 f"Min svävare är full med ål";
MoMinon sosvovävovarore äror fofulollol momedod ålol

```
> 1 votes

# Answer
# K, 31 bytes

```
,/{(x,"o",x;x)9>" aeiouåäö"?x}'

```

A straightforward solution seems fairly competitive given that K lacks regexes. Select between the "XoX" form and "X" form based on whether each character was found in a lookup table of ignored vowels and join the resulting lists.

You can try it in your browser using oK:

```
http://johnearnest.github.io/ok/index.html?run=%20%2C%2F%7B(x%2C%22o%22%2Cx%3Bx)9%3E%22%20aeiouåäö%22%3Fx%7D'%22Min%20svävare%20är%20full%20med%20ål%22

```

(Unfortunately I can't provide a clickable link because stack overflow doesn't appear to allow accented characters in URLs)
> 1 votes

# Answer
# Golfscript, 35 bytes

```
{."aeiouåäö\n "?-1={."o"\}{}if}%

```

Expects the input to be on the stack. With input (50 bytes):

```
"#{STDIN.gets}"{."aeiouåäö\n "?-1={."o"\}{}if}%

```

Works with the swedish vovels å, ä and ö.
> 0 votes

# Answer
# Sed (on command line), 28 bytes

```
sed 's/\([^aeiou]\)/\1o\1/g'

```

Either pipe the text in or type it direct. Just the sed code on its own is 22 bytes.
> 0 votes

# Answer
# JavaScript 43

Thanks to @Masterzagh for saving on function syntax.

```
x=>x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&")

```

## JavaScript 62

```
function E(x){return x.replace(/[bcdfghj-np-tv-z]/gi,"$&o$&")}

```
> 0 votes

# Answer
# R, 45 chars

```
gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)

```

Simple regex. Reads from stdin. `i=T` stands for `ignore.case=TRUE` (thanks to partial matching of argument names), which makes `gsub` case insensitive.

Usage:

```
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
Min svävare är full med ål
[1] "MoMinon sosvovävovarore äror fofulollol momedod ålol"
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
hello
[1] "hohelollolo"
> gsub("([^aeiouäöå ])","\\1o\\1",readline(),i=T)
hElLo
[1] "hohElolLoLo"

```
> 0 votes

# Answer
# \<\>\< (Fish), 64 bytes

```
>" oieauåäöOIEAUÅÄÖ"0i:1+?!;01.
 :&=?\     l?!v&
^[0o&<&o"o"o:&<

```

It's not the shortest answer but I enjoy the challenge of programming in \<\>\<

Try it out here
> 0 votes

# Answer
# golflua, 36 bytes

```
B=I.r():g("[^aeiou%W ]","%1o%1")w(B)

```

Simple pattern-matching: take stdin, then find the non-vowels (`%W` takes care of non-alphanumeric chars) & insert an `o` between the two replacements. Sadly, doing all this within the write (i.e., `w(I.r():g(....))`) also output the count of insertions, though it saved 3 chars. A Lua equivalent would be

```
line = io.read()
rovar = line:gsub("[^aeiou%W ]","%1o%1")
print(rovar)

```
> 0 votes

# Answer
# REXX, 107 bytes

```
parse arg s
v='aeiouåäö '
o=
do until s=''
  parse var s l 2 s
  if verify(l,v)>0 then l=l'o'l
  o=o||l
  end
say o

```

"MoMinon sosvovävovarore äror fofulollol momedod ålol"
> 0 votes

# Answer
# Japt v2.0a0, 7 bytes

```
r\c_+io

```

Try it
> 0 votes

# Answer
# Haskell, 75 bytes

```
x n|elem n[x|x<-['B'..'z'],notElem x"EIOUaeiou"]=[n,'o',n]|1<2=[n]
f=(>>=x)

```

This is a slight improvement on nimi's answer (unfortunately I can't comment yet) which uses a "clever" way to generate a list of consonants (`[x|x<-['B'..'z'],notElem x"EIOUaeiou"]`) that saves 6 bytes over just listing them out.

In this case `['B'..'z']` expands to `"BCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"`.

While some non-letter characters are included in the list of consonants, these don't include any punctuation or spaces so it should work for any regular sentence.

Usage: `f "Hello there!"` -\> `"HoHelollolo tothoherore!"`.
> 0 votes

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


# Question
Title: Combinations of stepwise increasing integers
Working on something in probability theory, I stumbled across another combinatorical exercise. These are always fun to solve, searching for intelligent approaches. Of course, one can use brute force for the following task, but this challenge is restricted complexity, so this is not allowed.

## Task

Given an integer Input \\$n \> 1\\$, print all integer vectors of length \\$n\\$, respecting following conditions:

* \\$v\_1 = 1\\$
* \\$v\_{i+1} - v\_i \in \\{0,1\\}\\$
* \\$v\_n \neq n\\$

example:

Input:

`n=4`

Output:

```
[1 1 1 1]

[1 1 1 2]

[1 1 2 2]

[1 1 2 3]

[1 2 2 2]

[1 2 2 3]

[1 2 3 3]

```

Additionally, time complexity of your solution must be \\$O(2^n)\\$. Note that generating all vectors and then filtering would be \\$O(n^n)\\$, which is not acceptable. A direct construction, not generating any false vector or duplicate vector at all, seems to be a bit more of a challenge.

Having said that, shortest code in bytes, respecting the above condition, wins.

# Answer
> 2 votes
# Ruby, ~~65~~ 55 bytes

```
->n{(0..2**~-n-2).map{|x|w=1;(1..n).map{|d|w+=x[n-d]}}}

```

Try it online!

### How:

Partial sum of bits (starting with 1) of all numbers up to 2n-1-2

For example: if the number is `111010011` it becomes:

```
  1 1 1 0 1 0 0 1 1
  | | |   |     | |
  v v v   v     v v
 +1+1+1  +1    +1+1
  -----------------
1 2 3 4 4 5 5 5 6 7
|
Initialized to 1

```

# Answer
> 1 votes
# 05AB1E, ~~10~~ 9 bytes

```
<oxÍŸεbηO

```

Try it online!

```
<           # decrement: n-1
 o          # 2**(n-1)
  x         # push 2 * 2**(n-1) = 2**n without popping
   Í        # 2**n - 2
    Ÿ       # range [2**(n-1), ..., 2**n - 2]
     ε      # for each number in that range:
      b     #  convert it to binary
       η    #  prefixes
        O   #  sum each prefix

```

# Answer
> 1 votes
# Jelly, ~~17~~ ~~16~~ 11 bytes

```
’2*
Ç’Ḷ+ÇBÄ

```

You can try it online!

```
’2*      Compute 2^(n-1) (let me call it x).
Ç’       Take x and decrement it,
  Ḷ      creating the range [0, ..., x-1].
   +     Then add
    Ç    x to every element in said range,
     B   take its binary representation
      Ä  and then take the cumulative sums.

```

This is a golfed version of the following:

The condition \\$v\_{i+1} - v\_i \in \\{0, 1\\}\\$ means we can instead generate all the sequences \\$d\_i\\$ of \\$n - 1\\$ elements with \\$d\_i \in \\{0, 1\\}\\$ and then generate a vector \\$v\\$ as such:

$$\begin{cases} v\_1 = 1 \\ v\_{i+1} = v\_i + d\_i \end{cases}\tag{1}$$

The only sequence we can't consider is when \\$d\_i = 1\ \forall i\\$ because in that case, \\$v\_n = n\\$, which can't happen as per the OP. On top of that, we can see the sequences \\$\\{d\_i\\}\_{i=1}^{n-1}\\$ as the binary numbers from \\$0\\$ to \\$2^{n-1} - 1\\$. So we do just that: find the binary representation of all integers from \\$0\\$ to \\$2^{n-1}-1\\$ and take those sequences as the jumps, to define \\$v\\$ as per \\$(1)\\$.

```
’                  Take the input integer and subtract 1,
 2*                take 2 to the power of that
   ’               and finally decrement again (this builds 2^(n-1) - 1).
    Ḷ              Take the lower range [0, ... (2^(n-1)-1) - 1]
     B             and write every number in the range in binary.
            €      Now, for each binary representation
           ¿       While said binary representation
       L<³Ɗ        has length smaller than the input number,
      Ż            prepend a 0 to it.
             Ä     Take the cumulative sum of every binary representation
              +1   and add 1 to every element.

```

# Answer
> 0 votes
# Charcoal, 20 bytes

```
ＩＥ⊖Ｘ²⊖θ⮌ＥＩθ⊕Σ⍘÷ιＸ²λ²

```

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

```
    ²                  Literal 2
   Ｘ                   To power
      θ                 Input
     ⊖                  Decremented
  ⊖                     Decremented
 Ｅ                      Map over implicit range
          θ             Input
         Ｉ              Cast to integer
        Ｅ               Map over implicit range
               ι        Outer index
              ÷         Integer divide by
                 ²      Literal 2
                Ｘ       To power
                  λ     Inner index
             ⍘     ²    Convert to base 2
            Σ           Digital sum
           ⊕            Incremented
       ⮌                Reversed
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 29 bytesSBCS

Full program.

```
¯1↓{⊃,/(⊂,¨0 1+⊢/)¨⍵}⍣(⎕-1),1

```

Try it online!

`,1` the list `[1]`

`{``}⍣(⎕-1)` apply the following anonymous lambda one-less-than input times:

`(``)⍵` on the argument:

`⊢/` take the last element (lit. right-argument reduction)

`0 1+` add `[0,1]` to that

`⊂,¨` concatenate each to the entire argument

`,/` flatten (lit. concatenation reduction)

disclose (since the reduction enclosed to reduce rank from 1 to 0)

`¯1↓` drop the last

# Answer
> 0 votes
# GolfScript, 70 bytes

```
[]\(:m 2\?:p{(.[2 base]@\+\.}do;{.,m\-[0]\*\+}%{1:s;{s+:s}%[1]\+ }%(;`

```

Try it online!

This is just my first stab, I have a few ideas on how to improve, but this is my hot garbage to start with. My goal is to get it under 50, then I'll write a full explanation.

The short is that it writes every binary combination, sums the elements recursively, then adds 1 to the front.

# Answer
> 0 votes
# JavaScript (V8),  ~~72 69~~  68 bytes

```
f=(n,a=1,p=1,m=n)=>--m?[p,p+1].map(p=>p<n&&f(n,a+[,p],p,m)):print(a)

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~111~~ 108 bytes

```
def f(n):
 for i in range(2**(n-1)-1):
  v,j=[],1
  for c in bin(i)[2:].zfill(n):j+=int(c);v+=[j]
  print(v)

```

Try it online!

No gigantic superset just straight up generation of vectors using G B's partial sum of bits idea.

# Answer
> 0 votes
# Pyth, 12 bytes

```
msM._dPh#^U2

```

Try it online!

Make all length `n` sequences of `0,1`, filler for the ones that start with 1, remove the all ones sequence, form prefixes, soon the prefixes.

# Answer
> 0 votes
# Python 2, 62 bytes

```
f=lambda n:1/n*[[1]]or[x+[x[-1]+d]for d in 0,1for x in f(n-1)]

```

Try it online!

# Answer
> 0 votes
# , 69 bytes

```
f=function(n,m=1,`?`=cbind)"if"(n-1,rbind(f(n-1,1?m),f(n-1,1?m+1)),m)

```

Try it online!

Simple recursive solution; returns a matrix where each row is one of the valid lists.

# Answer
> 0 votes
# 6502, 31 bytes

```
0016           .function
0016 A0 FE     LDY #FEh   ; starting bit pattern
0018           .again
0018 84 41     STY 41h    ; store current bit pattern in scratchpad
001A A9 31     LDA #049   ; ASCII "1"
001C A6 40     LDX 40h    ; load index with vector size
001E           .more_bits
001E 46 41     LSR 41h    ; shift lsb into carry
0020 69 00     ADC #0     ; add with carry
0022 85 0F     STA 0Fh    ; display ASCII char
0029 CA        DEX        ; decrease index
002A D0 F2     BNE 1Eh    ; more bits if index not zero
0024 C9 31     CMP #049   ; sequence ends in "1" so all bits zero
0026 D0 01     BNE 2Ch    ; continue
0028 60        RTS        ; exit function
0029           .continue
002C A9 2C     LDA #044   ; display...
002E 85 0F     STA 0Fh    ; ... comma
0030 88        DEY        ; next ...
0031 88        DEY        ; ... bit pattern
0032 4C 18 00  JMP 0018h  ; go again

```

Try It On Visual6502.org

(Press the Play button to run the program. Press Trace Less to speed up simulation). Input is at memory location 40 hex - click and enter hex numbers to modify before running. Since the 6502 is an eight bit microprocessor, for golfing purposes input is restricted from 1 to 8.

---
Tags: code-golf, combinatorics, restricted-complexity
---


title: 10-pin bowling split spare

text:
# Question
Title: 10-pin bowling split spare
# Bowling

Bowling is a game where, essentially, each player gets 10 turns to:

Take 2 attempts at knocking down 10 pins arranged in a triangle.

* between turns the pins are reset
* from the 1st to the 2nd attempt the pins are left as-is

The arrangement of the pins resembles the following scheme, with the pins numbered `0-9`:

```
6 7 8 9
 3 4 5
  1 2
   0

```

(Some rules and scoring mechanics omitted.)

# Split spare

In bowling, a spare is when the player manages to knock down the pins that were left standing after a first attempt. A spare is said to be a split spare1 if the pins that were left standing are not adjacent.

E.g. if the pins are laid out as such:

```
. . 8 9
 . . .
  . 2
   .

```

Then a player who manages to knock down all these 3 pins would score a split spare, given that the pin `2` is not adjacent to the `8, 9` group.

(1 for the purposes of this challenge, a split spare is defined taking into account *only* the adjacency of the pins left standing, even though Wikipedia's link states that for a split spare to take place, the pin 0 must have been knocked down already)

# Your task

Given the numbers of the pins left standing, output a Truthy value if such an arrangement would give a split spare and Falsy otherwise.

# Input

The list of all pins left standing (at least 2), in any reasonable format. Pin numbering may be 0- or 1-indexed provided it follows the numbering direction shown above. Sensible input formats include:

* a list of integers, like `[2, 8, 9]`
* a string of integers, like `"289"`
* separate arguments to a function
* an integer whose bits correspond to the pints left standing and whose least significant bit corresponds to pin `0`, e.g. `0b1100000100` for pins 2, 8 and 9.

You may assume input is sorted, if that helps you in any way.

# Output

A single consistent value for Falsy test cases and anything else for Truthy test cases.

# Test cases

## Truthy

```
[0, 9]
[2, 8, 9]
[1, 5, 8]
[3, 5]
[3, 8]
[3, 9]
[6, 8]
[6, 9]
[3, 5, 8, 9]
[5, 6]
[0, 1, 5, 6, 7, 9]
[1, 2, 8, 9]

```

## Falsy

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

```

# Bonus imaginary internet points

Bonus imaginary internet points if your algorithm works for any triangle number of pins, instead of just 10.

So far, only Grimmy's 05AB1E answer qualifies for the bonus internet points!

---

Standard loopholes are forbidden by default.

This is so shortest solution wins! If you enjoy the challenge, consider upvoting it... And happy golfing!

# Answer
> 9 votes
# 05AB1E, ~~27~~ ~~25~~ ~~24~~ 23 bytes

```
ÅTαε.āθDÆª}©æε®yKδαOß}à

```

Try it online!

Outputs 2 for falsy and a larger integer for truthy. Works for any triangle number of pins, thus qualifying for the bonus internet points.

A set of pins is split if and only if there is a partition of the set of pins in two subsets A and B such that no pin in A is adjacent to a pin in B.

Adjacency is determined using 3-element hexagonal coordinates.

First, we convert the input pins to their hex coordinate triplets:

```
   ε      }     # for each pin in the input:
ÅT              #  list of triangle numbers <= pin
  α             #  absolute difference of each one with pin
    .ā          #  enumerate: [a, b, c] => [[a, 1], [b, 2], [c, 3]]
      θ         #  get the last pair
       D        #  duplicate
        Æ       #  reduce the copy by subtraction
         ª      #  append that to the pair

```

Then, we iterate over partitions of this set of triplets in two subsets:

```
©               # save the set in the register
 æ              # powerset (list of subsets)
  ε       }     # for each subset y:
   ®            #  push the set from the register
    y           #  push y
     K          #  set difference (=> y's complement)

```

Then, we compute the 2D list of distances between each pin in the first subset and each pin in the second subset. Thanks to the elegance of 3-element hexagonal coordinates, this is surprisingly easy:

```
      δα        #  double vectorized absolute difference
        O       #  sum each triplet

```

Finally, we answer the question:

```
         ß      #  minimum distance for the current partition
          }     #  end the loop
           à    # maximum of the list of minimums

```

# Answer
> 7 votes
# Ruby, ~~72...~~ 74 bytes

```
->l{*r=l[0];l.map{r.map{|w|r|=l&"zê-ǓᔂYMŰɃc"[w].ord.digits}};l&r!=l}

```

Try it online!

### What is that?

Starting from the first pin in the list, check if all pins can be reached within a finite number of steps.

The binary string "zê-ǓᔂYMŰɃc" is the UTF-8 encoding of the adjacency list \[122,234,45,467,5378,89,77,368,579,99\]. Some digits are repeated to make the numbers fit into the ASCII range and spare some bytes, some edges are omitted if the node can be reached through different paths.

Thanks Value Ink for smoothing out rough edges (-3 bytes).

# Answer
> 7 votes
# JavaScript (ES6),  ~~87~~  83 bytes

*Saved 4 bytes thanks to @Grimmy*

Takes input as a 10-bit integer (LSB = pin \\$0\\$, MSB = pin \\$9\\$). Returns a non-zero integer for a split spare, or \\$0\\$ otherwise.

```
n=>(g=m=>[6,29,51,210,430,788,136,344,688].map((v,i)=>m|=m>>i&1&&n&v)|m)(g(n&-n))^n

```

Try it online!

### How?

Starting with the lowest bit set in the input, we progressively expand a bitmask with the pin neighbors. We eventually compare the result with the input.

Because we expand from pin \\$0\\$ to pin \\$9\\$ (let's call them \\$P\_0\\$ to \\$P\_9\\$), a single pass would occasionally miss a connection. Fortunately, processing two passes is always enough for all possible paths, which is what this code is doing.

For instance, let's consider the following configuration:

```
6 - - -
 3 4 -
  - 2
   -

```

**First pass**

We start with \\$P\_2\\$, which expands to \\$P\_4\\$. Then, \\$P\_4\\$ expands to \\$P\_3\\$. The connection between \\$P\_3\\$ and \\$P\_6\\$ is missed because \\$P\_3\\$ is not included in the bitmask at the time it's processed.

**Second pass**

Again, we start with \\$P\_2\\$, which expands to \\$P\_4\\$ (no change). Then, \\$P\_3\\$ expands to \\$P\_4\\$ (no change) and \\$P\_6\\$, which completes the bitmask.

### Improvement

As pointed out by @Grimmy, we never need to expand from \\$P\_9\\$: when we reach it, its neighbors (\\$P\_5\\$ and \\$P\_8\\$) have necessarily been found already. Therefore, we can safely discard its neighbor bitmask and iterate only from \\$P\_0\\$ to \\$P\_8\\$.

### Commented

```
n => (                // n = input bitmask
  g = m =>            // g is a recursive function taking a mask m
    [                 //   lookup table:
             6,       //     neighbors of pin 0
           29,51,     //     neighbors of pins 1, 2
        210,430,788,  //     neighbors of pins 3, 4, 5
      136,344,688     //     neighbors of pins 6, 7, 8
    ]                 //
    .map((v, i) =>    //   for each value v at position i in the above array:
      m |=            //     update m:
        m >> i & 1 && //       if the i-th bit is set in m:
        n & v         //         m = m OR (n AND v)
    ) | m             //   end of map(); return the new value of m
)(                    // invoke g twice to support the longer paths,
  g(n & -n)           // starting with the lowest bit set in n
) ^ n                 // compare the result with n

```

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~106~~ 121 bytes

Defines a function `P.__contains__` that takes a set of pins and returns `False` for a split spare or `True` otherwise.

e.g. `P.__contains__({"0", "9"})` returns `False` while `P.__contains__({"0", "1"})` returns `True`

```
d="6310214374254859876"
P={*map(frozenset,zip(d,d[1:]))}
while P<(P:={a|b for a in P for b in P if a&b}):0
P.__contains__

```

Try it online!

# Answer
> 2 votes
# C++ (gcc), ~~381~~ \\$\cdots\\$ ~~267~~ 248 bytes

```
#import<set>
using S=std::set<long>;int f(S s){std::set<S>c;for(long b=0x5792628a5a065664;b>9;b/=10)c.insert({b%10,b/10%10});for(S i:c)for(S j:c){S q(i);q.insert(begin(j),end(j));if(q.size()<i.size()+j.size())c.insert(q);}return c.find(s)==end(c);}

```

Try it online!

### Ungolfed

```
#include<set>
#include<algorithm>
using namespace std;
using S=set<int>;
bool f(S s) {
    // Change array a for any number or shape of pins,
    //  instead of just a triangle of 10.
    // It lists all the pins next to all their adjacent pins.
    int a[]{6,3,1,0,2,1,4,3,7,4,2,5,4,8,5,9,8,7,6};
    set<S> c;
    for(int i=0;i<sizeof(a)/sizeof(int)-1;++i)
        c.insert({a[i], a[i+1]});
    set<S> t;
    // Keep on adding connected sets of pins until there are no more new ones.
    while (t!=c) {
        for (auto i:c)
            for (auto j:c)
                if (any_of(begin(i),end(i),
                   [&](auto e){return j.find(e)!=end(j);}))
                {
                    S q(i);
                    q.insert(begin(j),end(j));
                    t.insert(q);
                }
        swap(t,c);
    }
    return c.find(s)==end(c);
}

```

Builds a set of all connected pin sets as per Kyle Gullion's idea and then simply tests for membership.

# Answer
> 1 votes
# Charcoal, 47 bytes

```
ＵＯ⁸#Ｆθ«≔⌊⊘⊖₂⊕×⁸ιηＪ⁺³⁻⊗ι×η⁺²η⊗ηＵＯ²ψ»¤#≔›⁶⁴ＬＫＡη⎚η

```

Try it online! Link is to verbose version of code. Takes input as an array of integers and outputs a Charcoal boolean, `-` for a split spare, empty output otherwise. Explanation:

```
ＵＯ⁸#

```

Draw an 8-by-8 rectangle of `#`s.

```
Ｆθ«

```

Loop over the input pins.

```
≔⌊⊘⊖₂⊕×⁸ιη

```

Calculate the row of the pin.

```
Ｊ⁺³⁻⊗ι×η⁺²η⊗η

```

Jump to the position of the pin.

```
ＵＯ²ψ

```

Erase a 2-by-2 rectangle representing the pin.

```
»¤#

```

Fill with `#`s starting at the last pin.

```
≔›⁶⁴ＬＫＡη

```

See whether the fill restored all 64 `#`s.

```
⎚η

```

Clear the canvas and output the result.

Although I calculate the position of the pin directly (I tried a look-up table but it was the same byte count) this method won't handle arbitrary numbers of pins since it needs to be able to draw a large enough initial rectangle. However it can be adjusted to handle a specific maximum number of pins: the initial `8` needs to be increased by 2 for each additional row of pins, the `3` needs to be one less than the new number of rows of pins, and the `64` needs to be the square of the number that replaces `8`.

# Answer
> 1 votes
# Excel (Ver. 1911), 142 Bytes

```
A1     'Input
B1:B10 3ÒƮ̔ŘʰĠ 'one character per row
       ^^^ (Non-printing characters)
C1     =ROW(B1:B10)-1
D1     =BITAND(INT(A1/2^C1#),1)*UNICODE(B1:B10)
E1     =SUM(MMULT(N(BITAND(2^C1#,TRANSPOSE(D1#))*D1#>0),N(C1#>=0)))+2<2*SUM(N(D1#>0)) 'Output

```

Here un-golfed using named ranges and extra columns

```
Input         'Input
Bit_List      3ÒƮ̔ŘʰĠ 'as a column of chars
Pin_Num       =SEQUENCE(ROWS(Bit_List))-1
Unicode       =UNICODE(Bit_List)
Pins_Left     =BITAND(INT(Input/2^Pin_Num),1)*Unicode
Pins_Adjacent =MMULT(SIGN(BITAND(2^Pin_Num,TRANSPOSE(Pins_Left))*Pins_Left),SIGN(Pin_Num+1))
Split         =SUM(Pins_Adjacent)<2*(SUM(SIGN(Pins_Left))-1)

```

Try it offline! (link to the workbook in a google drive)

You'll need to download and open in the latest version of excel for the formulas to work.

Single Test+Comments screenshot

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


title: Answer templating

text:
# Question
Title: Answer templating
# Context

Just look around! Whenever someone posts an answer, the same template is followed over and over again! A first line with the byte count and language name. Then the code. Then the TIO link. This is the basic skeleton almost everyone follows.

# Task

Your task, should you choose to accept it, is to write a program/function/procedure/etc that takes as input the variable bits and produces the basic CGCC answer.

# Input

The language name, some code and a TIO link, in any sensible formats. For the language name and the TIO link, a string is suggested. For the code, sensible formats include a string with possibly some newlines, or a list of strings, one string per line.

Additionally, you may also take the byte count as input. If you don't, you have to compute it yourself (if you compute it yourself, you can assume the byte count equals the length of the code string).

You have to support that the input strings may contain any printable, non-whitespace ASCII characters plus the space. The only exclusion being the newlines in the source code. You don't have to worry about the weird characters used by golfing languages in their code pages.

The inputs may be ordered in any way you like.

# Output

You should output this raw content:

```
# {name}, {byte count} bytes

    {code}

You can [try it online][tio]!

[tio]: {link}

```

Where `{name}`, `{byte count}`, `{code}` and `{link}` should be filled in by your code. Three of those are inputs, the byte count should be computed within your code if you chose not to receive it as input (you can assume the byte count is equal to the number of characters in the `code` argument). Beware that the code given may be multiline, in which case the `{code}` section must be indented by 4 spaces for each line of code.

# Test cases

You can check some test cases.

Related challenge

---

This is , so shortest answer in bytes wins. If you liked the challenge, consider upvoting it... And happy golfing!

# Answer
> 7 votes
# Ruby, ~~98~~ ~~95~~ 94 bytes

Really simple string interpolation. I don't think there's all that much to optimize here that will save a lot of bytes.

Takes the byte count as a parameter in order to save 3 bytes, as per Kevin Cruijssen's suggestion.

```
->n,b,c,l{"# #{n}, #{b} bytes

#{c.gsub /^/,' '*4}

You can [try it online][tio]!

[tio]: "+l}

```

Try it online!

# Answer
> 6 votes
# 05AB1E (legacy), ~~56~~ ~~53~~ ~~52~~ ~~51~~ 50 bytes

```
“# ÿ, ÿ¡Ï“I4ú»"[tio]"D“You€© [try€•€Ø]ÿ!“s¶·ý„: IJ

```

Inputs in the order `name`, `byte-count`, `[code-lines]`, `link`, where the `[code-lines]` is a list of lines.

Try it online.

**50 bytes alternative (credit to *@Grimmy*):**

```
“:# ÿ, ÿ¡Ï“I4ú»“You€© [try€•€Ø][tio]!“Â6£R¨¶·ýÀ$ú«

```

Try it online.

**Explanation:**

```
“# ÿ, ÿ¡Ï“  # Push dictionary string "# ÿ, ÿ bytes", where the `ÿ` are automatically
            # filled with the first two implicit inputs (name & byte-count)
I           # Push the third input-list of code-lines
 4ú         # Prepend 4 spaces before each line of code
   »        # And join it by newlines
"[tio]"     # Push string "[tio]"
       D    # Duplicate it
        “You€© [try€•€Ø]ÿ!“
            # Push dictionary string "You can [try it online]ÿ!", where the `ÿ` is
            # automatically filled with the "[tio]"
s           # Swap to get "[tio]" at the top of the stack again
¶           # Push a newline character
 ·          # Double it, which in the legacy version built in Python works with strings
  ý         # And join the stack by this double newline as delimiter
„:          # Push string ": "
   I        # Push the fourth input (link)
    J       # Join the entire stack together without delimiter
            # (after which the result is output implicitly)

“:# ÿ, ÿ¡Ï“ # Push dictionary string ":# ÿ, ÿ bytes", where the `ÿ` are automatically
            # filled with the first two implicit inputs (name & byte-count)
I4ú»        # Same as above
“You€© [try€•€Ø][tio]!“
            # Push dictionary string "You can [try it online][tio]!"
 Â          # Bifurcate it; short for Dulpicate & Reverse Copy
  6£        # Only leave the first 6 characters (the "![oit]")
    R       # Reverse it to "[tio]!"
     ¨      # Remove the last character: "[tio]"
¶·ý         # Same as above
À           # Rotate once towards the left, so the leading ":" becomes trailing
 $          # Push the fourth input (link) and a 1
  ú         # Prepend this link-string with that 1 space
   «        # And append it to the earlier created string
            # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“# ÿ, ÿ¡Ï“` is `"# ÿ, ÿ bytes"` and `“You€© [try€•€Ø]ÿ!“` is `"You can [try it online]ÿ!"`.

# Answer
> 5 votes
# Red, ~~102~~ 94 bytes

-6 bytes thanks to Kevin Cruijssen!

```
func[l n c u][reduce["#"rejoin[l","]n{bytes

   }c{

You can [try it online][tio]!

[tio]:}u]]

```

Try it online!

# Answer
> 4 votes
# PHP, ~~134~~ ~~132~~ ~~125~~ 119 bytes

```
# <?=($a=$argv)[1].", $a[2] bytes

".preg_replace("/^/m","    ",$a[3])."

You can [try it online][tio]!

[tio]: $a[4]";

```

Try it online!

Finally an easy job for PHP!

EDIT: easily saved 2 bytes with concatenation in first `<?=`

EDIT 2: saved another 7 bytes, just remembered that multi-lines strings work in PHP with `"`

EDIT 3: and another 6 with using `/^/m` instead of `/\n/`

# Answer
> 4 votes
# Haskell, ~~125~~ ~~121~~ ~~119~~ 113 bytes

-4 bytes thanks to kronicmage
-2 bytes thanks to xnor

```
(l!b)c t="# "++l++", "++show b++" bytes\n"++(("\n    "++)=<<c)++"\n\nYou can [try it online][tio]!\n\n[tio]: "++t

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 102 bytes

```
(n,b,c,l)=>`# ${n}, ${b} bytes

${c.replace(/^/gm, '    ')}

You can [try it online][tio]!

[tio]: `+l

```

Try it online!

"/^/gm" is a Global Multi-line replace of start line (^)

# Answer
> 3 votes
# Python 3, ~~97~~ \\$\cdots\\$ ~~118~~ 116 bytes

Added 28 bytes to fix a bug kindly pointed out by RGS.

Saved 2 bytes thanks to ovs!!!

```
lambda n,b,c,l,x='\n':f"""# {n}, {b} bytes

    {c.replace(x,x+' '*4)}

You can [try it online][tio]!

[tio]: {l}"""

```

Try it online!

Takes code length as a parameter to save 3 bytes.

# Answer
> 3 votes
# Kotlin, ~~83 109 101~~ 95 bytes

```
{n,b,c,l->"""# $n, $b bytes

${c.prependIndent()}

You can [try it online][tio]!

[tio]: $l"""}

```

Try it online!

-6 bytes thanks to @snail\_

-2 bytes thanks to @ovs

-6 bytes since `prependIndent` has a default of 4 spaces

# Answer
> 3 votes
# Japt, 60 bytes

```
i`# {V}, {W} ßs

{XmiSp4 R}

YŒ ¯n [try Š Ò‚][o]!

[o]:

```

Try it

# Answer
> 2 votes
## `j`, 77 bytes

```
# "a", "ck" bytes
"c'
,"
    ":@\+"

You can [try it online][tio]!

[tio]: "b

```

## Explanation

% Header section
# "               % The beginning header
   a              % The first input (the language name)
    ", "          % The comma & space
        ck        % The length of the program (taken at the 3rd input)
          " bytes % Appended with " bytes"
"                 % And a trailing newline

% Code section
c           % The third input
'
,           % Splitted by a newline
"
    "      % Add string representing a newline and 4 spaces
      :    % Stack: '\n'split(c), "    ", "    "
       @   % Stack: "     ",'\n'split(c), "    "
        \  % Join with 4 spaces
         + % Prepend 4 spaces

% Link section
          "

You can [try it online][tio]!

[tio]: "   % The template
         b % The second input
```
</code></pre>

# Answer
> 2 votes
# Java 10, 141 bytes

```
(n,b,c,l)->{var t="";for(var p:c)t+="    "+p+"\n";return t.format("# %s, %d bytes\n\n%s\nYou can [try it online][tio]!\n\n[tio]: "+l,n,b,t);}

```

Takes the byte-count as integer-input, and the code as an array of String-lines.

Try it online.

**Explanation:**

```
(n,b,c,l)->{    // Method with four parameters and String return-type
  var t="";     //  Temp-String, starting empty
  for(var p:c)  //  Loop over the code-lines:
    t+="    "   //   Append four spaces,
       +p       //   the code-line itself,
       +"\n";   //   and a newline to this temp-String
  return t.format("# %s, %d bytes\n\n%s\nYou can [try it online][tio]!\n\n[tio]: "
                //  Return this String above, where:
    +l,         //   The link is appended at the end
    n,          //   The first `%s` is replaced with the name `n`
    b,          //   The `%d` is replaced with the byte-count `b`
    t);}        //   And the second `%s` is replaced with the temp-String

```

# Answer
> 2 votes
# Wren, 117 bytes

Just a normal string interpolation here.

```
Fn.new{|a,b,c,d|"# %(a), %(b) bytes

%("    "+c.split("
").join("
    "))

You can [try it online][tio]!

[tio]: "+d}

```

Try it online!

# Answer
> 2 votes
## Japt, 85 bytes

```
"# {U}, {V} bytes

{"    "+Wq"
" q"
    "}

You can [try it online][tio]!

[tio]: "+X

```

Try it online!

# Answer
> 2 votes
# Keg, `-pn`, ~~92~~ ~~83~~ ~~79~~ 75 bytes

```
®N®l®b`# ©N, ©b  ¬E;s\n`,÷(\    $+,)
,“0:0X“` [try it a.;][tio]!\n[tio]: ©l`+,

```

Input is: Name, link, byte count and code

## Explained

```
®N®l®b

```

We first take the inputs `name`, `link` and `byte count` and store them in variable `N`, `l` and `b` respectively.

```
`# ©N, ©b  ¬E;s\n`,

```

Next, we construct a string that represents the header. The `©N` and `©b` are used for. string interpolation, and `¬E;` is the compressed word for `byte`. Printing the string using `,` formats the string with variables.

```
÷(\ $+,)

```

Now, we item split the implicit code list and print each item with a tab appended to it.

```
<newline>,

```

Then, we print a newline to separate everything.

```
“0:0X“` [try it a.;][tio]!\n[tio]: ©l`+,

```

Finally, we construct two strings: the string `You can` (represented by `“0:0X“`) and  `[try it online][tio]!\n[tio]: ©l` (which has the variable `l` interpolated within it). The two strings are then joined and printed.

Try it online!

## Answer History

### 79 bytes

```
0&®N®l®b`# ©N, ©b  ¬E;s\n`,÷(`\t`$+,)
,“0:0X“` [try it a.;][tio]!\n[tio]: ©l`+,

```

Try it Online!

### 83 bytes

```
0&®N®l®b`# ©N, ©b  bytes\n`,÷(`\t`$+,)
,`You can [try it online][tio]!\n[tio]: ©l`,

```

Try it online! Saved 9 bytes due to not calculating the byte count.

### 92 bytes

```
0&®N®l÷(:⑴⑼⑹")"⑺⑻®b`# ©N, ©b  bytes\n`,(`\t`$+,)
,`You can [try it online][tio]!\n[tio]: ©l`,

```

Try it online!

Note that I haven't applied string compression yet, which would get this down to 89 bytes. I'll do it tomorrow. The code is to be given as a list where each item is an individual line.

# Answer
> 2 votes
# Jinja2, 102 bytes

```
# {{n}}, {{b}} bytes

{%for a in c%}
    {{a}}
{%endfor%}

You can [try it online][tio]!

[tio]: {{l}}

```

Does this count as a language? Used jinja cli from here: https://pypi.org/project/jinja2-cli/

I think it should as this is the usage to run it:

```
jinja2 tio.j2 test.json --format=json

```

It accepts a file as a program, and input in some format. That fits the definition of a language to me.

This was the input json tested with:

```
{"n": "lang_name", "b": 10, "c": ["line_1", "line_2"], "l": "https://example.com"}

```

# Answer
> 2 votes
# C (gcc), 162 bytes

```
t(n,b,c,l)char*n,*c,*l;{for(printf("# %s, %d bytes\n\n    ",n,b);*c;)putchar(*c++)-10?:printf("    ");printf("\n\nYou can [try it online][tio]!\n\n[tio]: %s",l);}

```

There may be spaces after a trailing newline but I'm not sure if I'll be able to find a solution (or if a solution is even needed).

You can try it online!

# Answer
> 1 votes
# Charcoal, ~~67~~ 56 bytes

```
Ｆ⪪“`⊟«Ｍ["Þ…εＵ↑⁵ï²¹@↧≡⊗»⭆∧⌕´r⪪ιυＮτ⁰⬤N➙⁺⁰UＹ⟧MyoJb⎇»﹪”¶«ι Ｓ

```

You can try it online!

Try it online! Link is to verbose version of code. Assumes you're not worried about Charcoal's default output padding, which can be turned off at a cost of 2 bytes. Explanation: Each input has a certain amount of text that appears before it, which always ends in a space, so the loop prints the text and space before each input. Because it uses separate print commands for the inputs, the newlines in the code block maintain the indent, but the text strings themselves include carriage returns which turn off the indent (particularly applicable to the TIO gubbins). The four text strings themselves are extracted from a large compressed string.

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


title: Find the largest recurring prime

text:
# Question
Title: Find the largest recurring prime
Inspired by Find the largest fragile prime

A recurring prime (or whatever you choose to call it) is a prime that, when removing leading digits, always remain prime regardless of how many digits are removed.

```
for example
6317 is a recurring prime because...
317 is a recurring prime because...
17 is a recurring prime because...
7 is a prime

```

727 is a prime but not a recurring prime because 27 is not a prime.

**Goal**
Like the original question, your score is the largest recurring prime found by your program/ algorithm.

**Rules**
I copied these from the original question

```
You may use any language and any third-party libraries.
You may use probabilistic primality tests.
Everything is in base 10.

```

Edit: Welp... turns out I have not factored in adding zeros in this question. Although I have not thought about adding 0 at first but it indeed satisfy my requirements, since removing a digit in front of (any number of) zeros skips many digits of prime tests and returns trivially true if the last few digits is a recurring prime. To make this question less of a "zero spam" but also reward strategic use of zeros, **at most 2 consecutive zeros can be present in your answer**. (Sorry to Level River St who asked me this)

# Answer
> 7 votes
# Python 3, 79 digits (probably optimal)

A simple depth first search that allows up to two consecutive zeros.

```
from sympy.ntheory.primetest import isprime

def dfs(n=0, k=1):
    yield n
    if 100*n > k:
        yield from dfs(n, k*10)
    for i in range(1,10):
        if isprime(k*i + n):
            yield from dfs(k*i + n, k*10)

l = 1
for prime in dfs():
    if prime > l:
        d = len(str(prime))
        print(f'{d} digits: {prime}')
        l = 10**d

```

Try it online! Validate the result!

Finds `200400201909005006060042636079002004200130030090050030780060900408062003` (72 digits) in 8 seconds on TIO. I let the program run on my computer a little longer and the highest recurrent prime it found is `7030560306007020600400306654060053003909007054300609009069003056030702030330347` (validation). The program actually completed after finding this number, so this is probably the longest prime meeting the challenges requirement.

Note that sympys `isprime` could theoretically return `true` for pseudoprimes `>2^64`, though no examples are known as of now.

---

# Python 3, 24 digits

only considers numbers without zeros

```
from sympy.ntheory.primetest import isprime

def dfs(n=0, k=1):
    yield n
    for i in range(1,10):
        if isprime(k*i + n):
            yield from dfs(k*i + n, k*10)

l = 1
for prime in dfs():
    if prime > l:
        print(f'{len(str(prime))} digits: {prime}')
        l *= 10

```

Try it online! Validate the result!

Finds `357686312646216567629137` in less then a second on TIO.

# Answer
> 2 votes
# Charcoal, 32 bytes

```
Ｆ37⊞υιＦυＦＥ⁹⁺⊕κι¿⬤…²Ｉκ﹪Ｉκλ«κＤ⎚

```

Try it online! Finds all zero-free recurring primes, but is inefficient, so the TIO link is limited to just under 60 seconds' worth of primes. Explanation:

```
Ｆ37⊞υι

```

Start with the two possible last digits of all recurring primes (except the trivial `2` and `5`).

```
Ｆυ

```

Perform a breadth first search of recurring primes as they are found.

```
ＦＥ⁹⁺⊕κι

```

Prefix each non-zero digit to the prime so far.

```
¿⬤…²Ｉκ﹪Ｉκλ«

```

Use trial division to find out whether this is a new prime.

```
κＤ⎚⊞υκ

```

If it is then output it and add it to the list of recurring primes.

---
Tags: code-challenge, primes
---