# Question
Title: Print/Output all positive numbers in which every multi-digit substring in its decimal representation is also prime.
# Task

Your task is to print or output all **positive** numbers in which every multi-digit substring in its decimal representation is also prime. If the number has at least 2 digits, this would imply that the number itself also needs to be prime.

# Example

* `6197` is in the sequence because every multi-digit substring in `6197` is prime, namely: `61`, `19`, `97`, `619`, `197`, `6197` (itself).
* Note that `6` is not a prime but `6197` is still in the sequence because `6` is not a multi-digit substring of `6197`.
* `8` is also in the sequence because every multi-digit substring in `8` is prime. There is no multi-digit substring in `8`, so this is a case of vacuous truth.

# Specs

* Standard loopholes apply, except that you are **allowed** to hardcode the output or store information related to the output in your program.
* The numbers in the output can be in **any order**.
* The numbers in the output are **allowed** to have duplicates.
* You may use **any separator**, if you choose to print instead of output.
* You are **allowed** to prefix and/or postfix output if you choose to print instead of output.
* The separator and the prefix and the postfix may **not** contain any digits (U+0030 to U+0039).

# Full list (58 items)

```
1
2
3
4
5
6
7
8
9
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
113
131
137
173
179
197
311
313
317
373
379
419
431
479
613
617
619
673
719
797
971
1373
3137
3797
6131
6173
6197
9719

```

# Reference

---

As always, please feel free to address in the comments anything I should clarify.

# Answer
# Brachylog, 18 bytes

```
9719⟦₁{sᶠℕ₁₀ˢṗᵐ&}ˢ

```

Try it online!

So...am I ready for the "bounty"? :D
> 9 votes

# Answer
# 05AB1E, ~~15~~ 13 bytes

Code:

```
4°GN§ŒD9›ÏpP–

```

Explanation:

```
  G            # For N in range 1,
4°             #   10000
   N           # Push N
    §          # Convert that to string
     Œ         # Get all substrings
      D9›Ï     # Keep all substrings that are greater than 9
          p    # Check each of them if they are prime
           P   # Product
            –  # If 1, print N

```

Uses the **CP-1252** encoding. Try it online! (might take a few seconds).
> 8 votes

# Answer
# Brachylog, ~~18~~ ~~17~~ ~~15~~ ~~16~~ 15 bytes

```
ℕ₁<l4&≜sᶠ{Ḋ|ṗ}ᵐ

```

Try it online!

-1 byte after a discussion with Fatalize inspired me to just see what happens if I swap the `l` and the `<` around.

This predicate generates the output through the input variable, so long as the output variable is left unconstrained. Since duplicates are allowed, each number is generated with multiplicity equal to 2 to the power of the number of its digits which are prime numbers.

```
ℕ₁                 The input variable is a natural number
  <                less than
   l4              some number with length 4 (maximized as 9999).
     &≜            Assign a number to the input, and assert that
       sᶠ          every substring of it
         { | }ᵐ    is either
            ṗ      a prime number
          Ḋ        or a single digit.

```

Older versions:

```
{≜ℕsᶠ{Ḋ!|ṗ}ᵐ&}ᶠ⁵⁹b
7^₅⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ
8ḟ⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ
∧8ḟ>?ℕ₁≜sᶠ{Ḋ|ṗ}ᵐ

```
> 5 votes

# Answer
# Brachylog, 18 bytes

Another Brachylog solution. I couldn't get it *shorter* than Erik The Outgolfer's Brachylog solution; it's the exact same length, but approaches the generation from the opposite direction.

```
{≜ℕ{sℕ₁₀}ᶠṗᵐ&}ᶠ⁵⁹b

```

Looks like Unrelated String has beaten this by many a character, whom I congratulate.

Explanation:

```
{≜ℕ                Brute force all nonnegative integers to find any that match the constraints
   {s               Create a predicate that finds all subsequences of digits of said integer
     ℕ₁₀            Constrains those subsequences to be >= 10
        }ᶠ          Finds all possible values of that predicate: all multi-digit subsequences
          ṗᵐ        Apply a primality constraint to all of those subsequences
            &       Make the predicate output the input integer rather than a prime subsequence
             }ᶠ⁵⁹   Find the first 59 results (all of the puzzle's solutions, and zero)
                 b  Remove the first element of the list, i.e. 0

```

Try it online!
> 4 votes

# Answer
# Jelly, 17 bytes

```
DẆṖÐfḌÆP€Ạ
³²RÇÐf

```

My first Jelly answer! Saved 3 bytes thanks to @Leaky Nun!

Try it online

Explanation:

```
DẆṖÐfḌÆP€Ạ      The helper link, which checks if a given number satisfy the conditions.
DẆ              Convert the argument to a list of its digits and get all its substrings.
  ṖÐf           Remove all lists of length 1.
     ḌÆP€Ạ      Convert back each element to an integer and check if all of them are prime.

³²RÇÐf          Main link.
³²              Create a 100 and square it, which gives 10000.
  R             Create a list from 1 to it.
   ÇÐf          Filter out all the elements where the helper link gives false.

```
> 3 votes

# Answer
# Java 8, 182 bytes

```
v->{for(int n=0;++n<1e4;)if(P(n)>0)System.out.println(n);}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}int P(int n){return n>99?p(n)*p(n%100)*p(n%1000)*P(n/10):n<10?n:p(n);}

```

Port of *gastropner*'s C (gcc) answer, so make sure to upvote his answer!

Try it online.

**Explanation:**

```
// Loop in range [1,10000), and print any primes corresponding to the challenge description
v->{for(int n=0;++n<1e4;)if(P(n)>0)System.out.println(n);}

// Checks if the given integer is a prime (return unchanged input if prime, 0 if not)
int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

// Recursive method that checks if every part of length 2+ is a prime, or is below 10
int P(int n){return n>99?p(n)*p(n%100)*p(n%1000)*P(n/10):n<10?n:p(n);}

```
> 3 votes

# Answer
## PowerShell v2+, ~~107~~ 104 bytes

```
1..10+(11..1e4|?{($x=11..($i=$_)|?{"$i"-match$_}).count-eq($x|?{'1'*$_-match'^(?!(..+)\1+$)..'}).count})

```

*Warning: Kinda Slow*

Loops from `11` to `1e4` (i.e., `10000`) and pulls out numbers using the `Where-Object` selector (`|?{...}`). The clause is two components -- the first loops from `11` up to the current number and uses `Where-Object` to pull out those numbers that form a substring of the current number (via the `-match` regex operator). We store those substrings in `$x`. The second portion loops through `$x` and uses `Where-Object` to pull out all primes using the prime regex. We then take the `.count` of both and the check is actually whether those are `-eq`ual. For example, `971` will have `$x = (71,97,971)` and each of those are prime, so `3-eq3` is `$TRUE` and thus `971` will be selected.

That result is array-concatenated with a range `1..10`. The resulting array is left on the pipeline and output is implicit, with a newline between elements by default.
> 2 votes

# Answer
# C (gcc), ~~144~~ ~~142~~ ~~140~~ ~~136~~ ~~134~~ 132 bytes

-2 thanks to Kevin Cruijssen. -2 thanks to ceilingcat

...And inspired by that, we can get another 2 bytes from that for loop.

Also shamelessly nicked the rather better prime checker from Kevin Cruijssen's answer for another -4.

```
p(n,i){for(i=2;i<n;)n*=n%i++||n<10;i=n;}P(n){n=p(n)*(n<99||p(n%100)*p(n%1000)*P(n/10));}f(n){for(n=1e4;--n;)P(n)&&printf("%d\n",n);}

```

Try it online!
> 2 votes

# Answer
# Japt, 15 bytes

```
L²õs f_ã fÅe_°j

```

Test it
> 2 votes

# Answer
# Malbolge Unshackled (20-trit rotation variant), 2,5254e7 bytes or 1,9809e7 bytes

Size of this answer exceeds maximum postable program size (eh), so the code is located in my GitHub repository (note: Don't copy the code using CTRL+A and CTRL+C, just rightclick and click "Save destination element as...").

## How to run this?

This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).

The best one I could find is the fixed 20-trit rotation width variant, that performs very well.

To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.

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

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

```

## Performance notes

The application ran about 40 minutes on my machine, producing HEX numbers of the sequence. I stopped it around an hour of calculations, and it finished on 0x11.

Note this answer differs from my other one, because this one actually calculates the numbers, and it can be made so it calculates them indefinitely.

The application allocates the spinup buffer, that is around 7 gigabytes big, so better prepare your free RAM.

# Alternative variant

Alternative variant uses around 2 gigabytes of memory less, but produces the output in form of ASCII characters (0 = ASCII(0x0), 10 = newline, etc...), and is available here. It doesn't compete though, due to challenge requirements
> 2 votes

# Answer
# Python 3, 118 bytes

```
r=range(9720)
for n in r[1:]:all(all(l%k+9//l for k in r[2:l])for l in(n%10**(i%5)//10**(i//5)for i in r))and print(n)

```

Try it online!

### Explanation

Warning: no actual strings involved in this solution.

```
r=range(9720)
for n in r[1:]:                                        # For each positive integer up to 9720
 all( ... for l in(n%10**(i%5)//10**(i//5)for i in r)) # Check for all its substrings
  all(l%k ... for k in r[2:l])                         # If it is either prime
   +9//l                                               # Or smaller than 10
and print(n)                                           # Then print

```
> 2 votes

# Answer
## C#, ~~261~~ ~~249~~ 247 bytes

*Saved 12 bytes thanks to Leaky Nun*

```
()=>{Action<int>w=System.Console.WriteLine;int i=0,n,j,k,p,m,b;for(;++i<10001;){n=(i+"").Length;if(n<2)w(i);else{b=1;for(j=1;++j<=n;)for(k=0;k+j<=n;){p=int.Parse((i+"").Substring(k++,j));if(p%2<1)b=0;for(m=3;m<p;m+=2)if(p%m<1)b=0;}if(b>0)w(i);}}};

```

This compiles to a `Func<List<int>>`.

The formatted version looks like:

```
() =>
{
    Action<int> w = System.Console.WriteLine;

    int i = 0, n, j, k, p, m, b;

    for (; ++i < 10001;)
    {
        n = (i + "").Length;

        if (n < 2)
            w(i);

        else
        {
            b = 1;
            for (j = 1; ++j <= n; )
                for (k = 0; k + j <= n; )
                {
                    p = int.Parse((i + "").Substring(k++, j));

                    if (p % 2 < 1)
                        b = 0;

                    for (m = 3; m < p; m += 2)
                        if (p % m < 1)
                            b = 0;
                }

            if (b > 0)
                w(i);
        }
    }
};

```
> 1 votes

# Answer
# Ruby, 81 + 8 = 89 bytes

+8 bytes for `-rprime`.

```
puts (?1..?9*4).select{|m|(r=2..m.size).all?{|i|r.all?{|j|m[i-2,j].to_i.prime?}}}

```

See it on repl.it: https://repl.it/CniR/2
> 1 votes

# Answer
# Perl 6,  ~~47 44~~  43 bytes

```
~~for 1..9719 {all(m:ex/..+/).Int.is-prime&&.say}
put grep {is-prime +all(m:ex/..+/):},1..9719~~
put grep {is-prime +all m:ex/..+/:},1..9719
```

## Explanation:

```
# print the values space separated, with trailing newline
put

# that match
grep -> $_ {

  # call the method ｢.is-prime｣ ( that is what ｢:｣ is for )
  # (autothreaded)
  is-prime

  # convert following to numeric (autothreaded)
  +
  # a junction of
  all(
    # all substrings 2 characters or greater
    $_ ~~ m :exhaustive / . .+ /
  )

  # needed to indicate that ｢is-prime｣ is a method call
  :

},

# in this Range
1..9719

```
> 1 votes

# Answer
# Swift 4, 144 bytes

```
let p={n in !(2..<n).contains{n%$0<1}}
print((1...971).filter{$0<10||p($0)&&($0<100||p($0/10)&&p($0%100))}+[1373,3137,3797,6131,6173,6197,9719])

```

Try it online!

## Explanation

```
let p={n in !(2..<n).contains{n%$0<1}} // Helper function p, tests if a number is prime
print((1...971).filter{                // Print every number n in the range 1 to 971
 $0<10                                 //  that is less than 10
 ||p($0)&&                             //  or a prime and
 ($0<100                               //   is less than 100 or
  ||p($0/10)&&p($0%100))}              //   n/10 and n%100 are primes
+[1373,3137,3797,6131,6173,6197,9719]) // Print the four digit numbers

```
> 1 votes

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

if i can assume infinite stack `i*i<=n&&` can be removed and `i*i>n` turns to `i>=n` which reduces the code by 9 bytes and maybe convert main function to recursive : https://tio.run/##LYpBDoIwEEX33AMyAxVbXUmccgX2xkWDRYeQaSPqyrvXkrj5ef/lze7j1vHJ8bWTcPMpTQRMWjm6XJFs0/DZ@EM/ASunBmCsKtfG9/rIiJ0rIoEoJpNbKXPdx@1jx5akGEiytqdNYp2nNFr/wR@xHkD2Rn81dpLGIGtYfLuEO0yAmH4 (119 bytes)

```
_=>eval(`for(a=[i=1];++i<1e4;)P(i)&&a.push(i)`)||a
p=(n,i=1)=>i*i<=n&&n%++i?p(n,i):n%i
P=n=>n>9?p(n)*p(n%100)*p(n%1e3)*P(n/10|0):n

```

Try it online!
> 1 votes

# Answer
# Malbolge, 1361 bytes

Simple and boring version. Displays numbers from the highest.

```
D'`r^"!=[YG3yUCvA-csNqp-nJ$HYFgDC#AbQ,|*)\rwvutm3kSonmlkdihg`&dc\aZ_X|V[ZYXQPt7SRQPOHGkKJIHG@d>=<A:98\}|:981U5.-2+0/.'K%$#G!E}e#z!~}v<]yxwpun4rkj0nmfN+ihaf_^$\a`_XW{>=YXWVONrLKPINGkE-IBAe(>=<;_?>=}|:3W1w543,P0).-&J*)(!E}|B"!~}|{zyr8potml2jongfkjibg`&d]\"`_XW{>=YXWVONr54JIHMFj-,HGF?>b%A@?87[;:981w543,P0).-&J*j(!EfeB"!~}_u;yrqpun4rqpihmlkjihg`&d]\"`_X|\[ZYXQuUNMLQJnH0LKJIBAe(>=<`#"8\<5Y9270T43,Pqp.-&J$)"!~D|#"y~}|u;s9qvotsrk1inglkdihg`&d]\"Z~XWVUZYXQu87SLKo2NGFjDIHGF?>bBA#"8\6;:981Uv.32+*)Mnm%$)('~D|{A!xwv{zyr8vXnsrkjoh.fNdchg`ed]#aC_^WVz=YXQPt7SRQPOHGkK-IHGF?>bBA#"8\6;:981Uv.32+*)Mnm%*#"F&%$#cy?}v<]\xwpun4rqSonmf,diha'eG]#a`_X|V[ZYXWPt76LKoIHGLEiCHGFED=aA:?>7[;:981w/4-,PO)o'&J*j(!E%edz@~}_u;yxqpo5mrqpoh.f,jibgf_%]\[!_XW{[ZYXQu87SLKo2NGFjJIHAF?c=BA@?>=<5Y38765.-Q10)o'&J*j(!E%e{z@~}|{ts9qpotsrk1oQglkd*)gIed]#DZ_^]VzZYRQuONMRKJnNGLEJCgG)(D=aA:?>=<;4X816/43,P0).-&+$H('gf|Bcb~w|u;yxwYutmrqj0nmleMib(fH%cba`_X|VUZYXWPt7SRQPOHGkEDIHG@dDC<;@?8\6|:32V0T43,+O)o'&J*)('&}C{"yxwv<tyr8vun4Ukpoh.fN+c)gIed]#DZ_^]VzTSRWPtTSLQJnH0LKJIBAe(>=BA@987[;:381Uv.32+*)Mnm%$)('~D${"y?}_uzyxqpo5srqSonmf,jihgfeG]#a`_X|V[ZYXWPt76LKo2NGFjJIH*)ED=a;@?>76;4X816/43,P*).',%I)('~Ded"y~}|u;srqvo5mlqpih.fN+cba`&d]\aZ~^]VUZSwWPUTSLpJ2NGLEiCHGFED=a;:?>7<5YX876v43,+O).-,+$H('&feBz!x}v{zsr8punsrk1inglkdihg`&d]\"Z~X]V[ZSwQVUTMRKo2NGFjDIHGF?>b%A@?87[;{921U5.3210)M-,%k#(!EfeB"y~}v{zyr8%

```

Try it online!
> 1 votes

# Answer
# TI-83/84 BASIC, 124 Bytes

```
For(A,1,E4
DelVar Nint(log(A→P
Ans→Q
While Ans
For(I,0,Q-Ans
10^(P+1
AnsfPart(iPart(A/10^I)/Ans→S
min(Ans={2,3,5
If S≥7 and fPart(.5S
min(remainder(S,3+2cumSum(not(binompdf(int(.5√(S)),0
N+not(Ans→N
End
P-1→P
End
If not(N
Disp A
End

```

Loops over the first 10k integers. Sets up a counter in N to check each substring prime, and int(log(A retrieves one less than the number of digits in the current number. We then set that number aside in a second variable so we can step P down through each length substring at least 2 digits. 10^... and AnsfPart(iPart(,,, generate the current substring to check for primality, then the following 3 lines do the primality check to 1 or 0 in Ans. If the substring is not prime, we increment N, and after all the substrings are checked if N is still 0 we print the current number.

Possibly some tweaking could be done to increase the efficiency of the primality check toward this test? I'm just glad I found an algorithm in fewer bytes than storing the output directly in TI-83 formatting!
> 0 votes

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

```
r=range
s=str
l=lambda _:len(s(_))
[*map(print,[t for t in r(1,10**4) if all(all(int(x)%b for b in r(2,int(x))) for x in [s(t)[i:j+1] for i in r(l(t)) for j in r(i,l(t)) if l(s(t)[i:j+1])>1])])]

```

Try it online!
> 0 votes

# Answer
# PHP, 135 bytes

```
for(;++$n<1e4;$p||print"$n
")for($p=$i=0;$i<$l=strlen($n);$i++)for($j=1;$j++<$l-$i;$p|=$k)for($k=($m=substr($n,$i,$j))-1;$k&&$m%$k--;);

```

Try it online!

```
for(;                         // level 1 loop on
  ++$n<1e4;                   // all numbers from 1 to 10,000, $n is current number
  $p||print"$n\n"             // at the end of loop for each number, print $n if all multi digit sub strings were prime ($p=0)
)
  for(                        // level 2 loop on each digit of $n
    $p=                       // $p is a flag for all sub string primes and is set to 0 for each new $n
      $i=0;                   // $i is position of current digit (and sub string start position)
    $i<$l=strlen($n);         // $l is the total digits count in $n
    $i++                      // increment $i by one
  )
    for(                      // level 3 loop to create sub strings
      $j=1;                   // $j is length of sub string, we only care about multi digit sub strings so it starts from 1
      $j++<$l-$i;             // continue the loop as long as $j has not reached last digit and increment it by one
      $p|=$k                  // THIS IS RUN AFTER LOOP LEVEL 4: update $p flag based on value of $k
                              //     $p will be left at 0 only if all of the sub strings are prime (if $k is always 0)
    )
      for(                    // level 4 loop to check each sub string to be prime
        $k=(                  // $k is set to current sub string minus 1
          $m=substr($n,$i,$j) // $m is current sub string
        )-1;                  //
        $k && $m%$k--;        // as long as $k is more than 0 and $m%$k is not zero, decrement $k by one and continue
                              //     a prime number will only get a 0 remainder, when $k gets to 1
                              //     so $k will be 0 for primes and more than 0 for non-primes
      );

```
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity, sequence, primes
---


title: ASCII TURNED SHAPE

text:
# Question
Title: ASCII TURNED SHAPE
How can we depict a turned shape simply and nicely using ascii characters in 3D space?

I suggest this method :

Instead of a circle we use a square rotated by 45° for the cutting section so that we only need '/' and '\\' characters to draw it.

```
 /\
/  \
\  /
 \/

```

And we use '\_' character for the profiles: upper, lower and median.

```
  _________
 /\        \
/  \________\
\  /        /
 \/________/

```

Isn't it Turning complete? Well, if you agree, write a full program or a function taking an unsigned integer value N , representing a number of steps , producing a 3d shape as described below.

The profile of this turned shape has the form of a stair step curve raising from 0 to N steps and lowering back to 0 where each step is 2 char('/') high and 5 char long ('\_').

Maybe some examples describes it more clearly.

For N = 0 you may output nothing but it's not mandatory to handle it.

```
  N = 1

   _____
  /\    \
 /  \____\
 \  /    /
  \/____/
.
```

```
      N = 2

        _____
       /\    \
   ___/_ \    \__
  /\    \ \    \ \
 /  \____\ \____\_\
 \  /    / /    / /
  \/____/ /    /_/
      \  /    /
       \/____/
.
```

```
       N = 3
             _____
            /\    \
        ___/_ \    \__
       /\    \ \    \ \
   ___/_ \    \ \    \ \__
  /\    \ \    \ \    \ \ \
 /  \____\ \____\ \____\_\_\
 \  /    / /    / /    / / /
  \/____/ /    / /    / /_/
      \  /    / /    / /
       \/____/ /    /_/
           \  /    /
            \/____/

```

Rules :
\- Margins are not specified.
\- Standard loopholes are forbidden.
\- Standard input/output methods.
\- Shortest answer in bytes wins.

# Answer
> 8 votes
# Charcoal, ~~70~~ 69 bytes

```
ＮθＦθ«Ｊ⊕×⁷⊕ι⁰≔⊗⊕ιι↙ι↑←×⁵_Ｐ↖²→↗ι×⁴_↖ι←×⁵_↓Ｐ↙²→↘ιＪ⁻×⁹θ⊗ι⊖ι__↗ι←Ｐ←__↖ι←__

```

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

```
ＮθＦθ«

```

Input `N` and loop that many times.

```
Ｊ⊕×⁷⊕ι⁰

```

Jump to the (middle) right corner of the front slice.

```
≔⊗⊕ιι

```

Get the size of the slice.

```
↙ι↑←×⁵_Ｐ↖²→↗ι×⁴_↖ι←×⁵_↓Ｐ↙²→↘ι

```

Draw the front slice.

```
Ｊ⁻×⁹θ⊗ι⊖ι

```

Jump to the bottom (that we can see) of the back slice.

```
__↗ι←Ｐ←__↖ι←__

```

Draw the back slice.

# Answer
> 8 votes
# JavaScript (ES8),  ~~322 282 278~~  272 bytes

Builds the output line by line.

```
f=(n,y=0,Y=(k=y>2*n)?4*n-y:y,S='___/_25__,/\\    \\25,\\/____/14_/,\\ 14,\\/____/,_____, \\____\\, /    /, \\    \\,_\\, /, \\'.split`,`)=>~Y?(y-2*n?''.padEnd(n*5-(Y>>1)*5-3-y%2-k)+S[y?Y?k*2+y%2:4:5]:'/ 03').replace(/\d/g,n=>S[+n+6].repeat(Y-(n>2||-k)>>1))+`
`+f(n,y+1):''

```

Try it online!

### How?

For each row \\$0 \le y \le 4n\\$, we define:

$$k=\cases{ 0,&\text{if $y \le 2n$}\\ 1,&\text{if $y \> 2n$} }$$ $$Y=\cases{ y,&\text{if $k=0$}\\ 4n-y,&\text{if $k=1$} }$$

Each row is first converted into a main pattern. A main pattern may contain digits: they are placeholders for repeated sub-patterns that are expended afterwards.

The middle row (when \\$y=2n\\$) is a special case which is processed separately. For all other rows, we compute the main pattern ID \\$p\\$ with:

$$p=\cases{ 5,&\text{if $y=0$}\\ 4,&\text{if $y \neq 0, Y=0$}\\ 2k+(y \bmod 2),&\text{otherwise}\\ }$$

There are no leading spaces for the middle row. For all other rows, the number \\$s\\$ of leading spaces is given by:

$$s=5n-5\left\lfloor\frac{Y}{2}\right\rfloor-3-(y\bmod 2)-k$$

There are inner sub-patterns (marked with a digit \\$\le2\\$) and outer sub-patterns (marked with a digit \\$\>2\\$), which are repeated \\$n\_1\\$ and \\$n\_2\\$ times respectively:

$$n\_1=\left\lfloor\frac{Y+k}{2}\right\rfloor\\ n\_2=\left\lfloor\frac{Y-1}{2}\right\rfloor$$

The above formulae apply to the middle row as well, but are irrelevant for the first and last rows, which do not have sub-patterns.

Below is what we get for \\$n=3\\$:

```
  y Y k |  p  |  s  |   before .replace()  | n1 | n2 |      after .replace()
--------+-----+-----+----------------------+----+----+-----------------------------
  0 0 0 |  5  | 12  | ............_____    |  0 | -1 | ............_____
  1 1 0 |  1  | 11  | .........../\    \25 |  0 |  0 | .........../\    \
  2 2 0 |  0  |  7  | .......___/_25__     |  1 |  0 | .......___/_ \    \__
  3 3 0 |  1  |  6  | ....../\    \25      |  1 |  1 | ....../\    \ \    \ \
  4 4 0 |  0  |  2  | ..___/_25__          |  2 |  1 | ..___/_ \    \ \    \ \__
  5 5 0 |  1  |  1  | ./\    \25           |  2 |  2 | ./\    \ \    \ \    \ \ \
  6 6 0 | n/a | n/a | / 03                 |  3 |  2 | /  \____\ \____\ \____\_\_\
  7 5 1 |  3  |  0  | \ 14                 |  3 |  2 | \  /    / /    / /    / / /
  8 4 1 |  2  |  1  | .\/____/14_/         |  2 |  1 | .\/____/ /    / /    / /_/
  9 3 1 |  3  |  5  | .....\ 14            |  2 |  1 | .....\  /    / /    / /
 10 2 1 |  2  |  6  | ......\/____/14_/    |  1 |  0 | ......\/____/ /    /_/
 11 1 1 |  3  | 10  | ..........\ 14       |  1 |  0 | ..........\  /    /
 12 0 1 |  4  | 11  | ...........\/____/   |  0 | -1 | ...........\/____/

```

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


# Question
Title: Number of characters skipped determines code printed
Write a program which, when every nth character is skipped, it prints n. For example, if every 2nd character is skipped, it prints 2.

# Example

**n=0**

```
foobar

```

Output:

```
0

```

**n=1**

```
foa

```

Output:

```
1

```

**n=2**

```
fobr

```

Output:

```
2

```

# Rules

* If n=0 (no characters are skipped), 0 must be returned.
* Must print to STDOUT.
* Standard loopholes are forbidden.
* The first character is never skipped.
* Obviously, it doesn't need to work for more characters than the code has (e.g. if your code is 11 characters long, it doesn't need to work for every 11th character)

# Scoring

This is *code golf*, so the shortest code in bytes wins.

# Answer
> 10 votes
# Polyglot, 1 byte

```
0

```

Try it in Retina

Try it in Jelly

Try it in 05AB1E

Try it in Husk

Try it in ///

Try it in GolfScript

Try it in BrainGolf

Try it in Pyth

Try it in Japt

Try it in ink

Try it in PHP

Try it in Brachylog

Try it in MATL

Try it in Keg

Try it in Carrot

---
Tags: code-golf, radiation-hardening
---


title: RNA to Protein Translation

text:
# Question
Title: RNA to Protein Translation
**RNA**, like DNA, is a molecule found in cells encoding genetic information. It consists of *nucleotides*, which are represented by the bases adenine (A), cytosine (C), guanine (G) and uracil (U).\* A **codon** is a sequence of three nucleotides.

**Proteins** are large molecules which perform a vast array of functions, such as keratin which is found in hair and nails and hemoglobin which carries oxygen in blood cells. They are made up of **amino acids**, which are encoded as codons in RNA molecules. Sometimes different codons may encode for the same amino acid. Each amino acid is commonly represented by a single letter, for example H stands for histidine.

Given a sequence of `ACGU`, can you translate it into the corresponding protein string?

* DNA consists of ACGT, where the T is thymine. During DNA to RNA transcription, thymine is replaced by uracil.

---

## Input

Input will be a single string consisting of only the characters `ACGU` in upper case. You may write either a function or a full program for this challenge.

## Output

You may choose to output via either printing or returning a string (the latter choice is only available in the case of a function).

Translation should begin at a start codon (`AUG`, represented as `M`) and end at a stop codon (one of `UAA`, `UAG` or `UGA`, represented as `*`). There are four cases where input may be invalid:

* The input does not begin with a start codon
* The input does not end with a stop codon
* The input's length isn't a multiple of 3
* The input contains a stop codon somewhere other than at the end

In all of these cases, `Error` should be outputted. Note that, unlike stop codons, start codons may appear after the start of the string.

Otherwise, you should convert each codon into its respective amino acid via the following RNA codon table:

```
* UAA UAG UGA
A GCU GCC GCA GCG
C UGU UGC
D GAU GAC
E GAA GAG
F UUU UUC
G GGU GGC GGA GGG
H CAU CAC
I AUU AUC AUA
K AAA AAG
L UUA UUG CUU CUC CUA CUG
M AUG
N AAU AAC
P CCU CCC CCA CCG
Q CAA CAG
R CGU CGC CGA CGG AGA AGG
S UCU UCC UCA UCG AGU AGC
T ACU ACC ACA ACG
V GUU GUC GUA GUG
W UGG
Y UAU UAC

```

...and output the translated string.

## Examples

Invalid cases:

```
<empty string> -> Error
AUG -> Error
UAA -> Error
AUGCUAG -> Error
AAAAAAA -> Error
GGGCACUAG -> Error
AUGAACGGA -> Error
AUGUAGUGA -> Error
AUGUUUGUUCCGUCGAAAUACCUAUGAACACGCUAA -> Error

```

Valid cases:

```
AUGUGA -> M*
AUGAGGUGUAGCUGA -> MRCS*
AUGGGUGAGAAUGAAACGAUUUGCAGUUAA -> MGENETICS*
AUGCCAGUCGCACGAUUAGUUCACACGCUCUUGUAA -> MPVARLVHTLL*
AUGCUGCGGUCCUCGCAUCUAGCGUUGUGGUUAGGGUGUGUAACUUCGAGAACAGUGAGUCCCGUACCAGGUAGCAUAAUGCGAGCAAUGUCGUACGAUUCAUAG -> MLRSSHLALWLGCVTSRTVSPVPGSIMRAMSYDS*
AUGAAAAACAAGAAUACAACCACGACUAGAAGCAGGAGUAUAAUCAUGAUUCAACACCAGCAUCCACCCCCGCCUCGACGCCGGCGUCUACUCCUGCUUGAAGACGAGGAUGCAGCCGCGGCUGGAGGCGGGGGUGUAGUCGUGGUUUACUAUUCAUCCUCGUCUUGCUGGUGUUUAUUCUUGUUUUAA -> MKNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVYYSSSSCWCLFLF*

```

*Edit: Added more test cases*

## Scoring

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

Note: I'm no expert in molecular biology, so feel free to correct me if I've misstated anything :)

# Answer
> 6 votes
## CJam (97 93 92 91 bytes)

```
q"GACU"f#3/{4b"GGEDAAVVRSKNTTMIRRQHPPLLWC*YSSLF"{_s"MW""I*"er}%=}%s_'*/(1<"M"=*Qa=\"Error"?

```

This is a port of my GolfScript solution with a slightly tweaked hash function because to my surprise one thing which CJam hasn't borrowed from GolfScript is treating strings as arrays of integers.

6 bytes saved thanks to suggestions by Optimizer (including two bytes from something which I thought I'd tried and didn't work - huh).

# Answer
> 10 votes
**JavaScript (ES6) 167 ~~177~~** chars encoded in UTF8 as **167 ~~177~~** bytes

... so I hope everyone is happy.

**Edit** In fact, no need for a special case for last block too short. If the last 2 (or 1) chars are not mapped, the result string does not end with '\*' and that gives error anyway.

```
F=s=>/^M[^*]*\*$/.test(s=s.replace(/.../g,x=>
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"
[[for(c of(r=0,x))r=r*4+"ACGU".search(c)]|r]))?s:'Error'

```

**Explained**

Each char in a triplet can have 4 values, so there are exactly 4^3 == 64 triplets. The C function map each triplet to a number between 0 and 63. No error check needed as input chars are only ACGU.

```
C=s=>[for(c of(r=0,s))r=r*4+"ACGU".search(c)]|r

```

Each triplet maps to an aminoacid identified by a single char. We can encode this in a 64 character string. To obtain the string, start with the Codon Map:

```
zz=["* UAA UAG UGA","A GCU GCC GCA GCG","C UGU UGC","D GAU GAC","E GAA GAG"
,"F UUU UUC","G GGU GGC GGA GGG","H CAU CAC","I AUU AUC AUA","K AAA AAG"
,"L UUA UUG CUU CUC CUA CUG","M AUG","N AAU AAC","P CCU CCC CCA CCG","Q CAA CAG"
,"R CGU CGC CGA CGG AGA AGG","S UCU UCC UCA UCG AGU AGC","T ACU ACC ACA ACG"
,"V GUU GUC GUA GUG","W UGG","Y UAU UAC"]
a=[],zz.map(v=>v.slice(2).split(' ').map(x=>a[C(x)]=v[0])),a.join('')

```

...obtaining "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV\*Y\*YSSSS\*CWCLFLF"

So we can scan the input string and use the same logic of the C function to obtain the code 0..63, and from the code the aminoacid char. The replace function wil split the input string in 3 chars blocks, eventually leaving 1 or 2 chars not managed (that will give an invalid result string, not ending in '\*').

At last, check if the encoded string is valid using a regexp: it must start with 'M', must not contain '\*' and must end with '\*'

**Test** In FireBug/FireFox console

```
;['AUGCUAG','GGGCACUAG','AUGAACGGA','AUGUAGUGA','AAAAAAA',
'AUGUUUGUUCCGUCGAAAUACCUAUGAACACGCUAA',
'AUGAGGUGUAGCUGA','AUGCCAGUCGCACGAUUAGUUCACACGCUCUUGUAA',
'AUGCUGCGGUCCUCGCAUCUAGCGUUGUGGUUAGGGUGUGUAACUUCGAGAACAGUGAGUCCCGUACCAGGUAGCAUAAUGCGAGCAAUGUCGUACGAUUCAUAG']
.forEach(c=>console.log(c,'->',F(c)))

```

*Output*

```
AUGCUAG -> Error
GGGCACUAG -> Error
AUGAACGGA -> Error
AUGUAGUGA -> Error
AAAAAAA -> Error
AUGUUUGUUCCGUCGAAAUACCUAUGAACACGCUAA -> Error
AUGAGGUGUAGCUGA -> MRCS*
AUGCCAGUCGCACGAUUAGUUCACACGCUCUUGUAA -> MPVARLVHTLL*
AUGCUGCGGUCCUCGCAUCUAGCGUUGUGGUUAGGGUGUGUAACUUCGAGAACAGUGAGUCCCGUACCAGGUAGCAUAAUGCGAGCAAUGUCGUACGAUUCAUAG -> MLRSSHLALWLGCVTSRTVSPVPGSIMRAMSYDS*

```

# Answer
> 8 votes
# C,190 bytes (function)

```
f(char*x){int a=0,i=0,j=0,s=1;for(;x[i];i%3||(s-=(x[j++]=a-37?a-9?"KNRSIITTEDGGVVAA*Y*CLFSSQHRRLLPP"[a/2]:77:87)==42,x[j]=a=0))a=a*4+(-x[i++]/2&3);puts(*x-77||i%3||s||x[j-1]-42?"Error":x);}

```

# ~~199~~ 194 bytes (program)

```
a,i,j;char x[999];main(s){for(gets(x);x[i];i%3||(s-=(x[j++]=a-37?a-9?"KNRSIITTEDGGVVAA*Y*CLFSSQHRRLLPP"[a/2]:77:87)==42,x[j]=a=0))a=a*4+(-x[i++]/2&3);puts((*x-77||i%3||s||x[j-1]-42)?"Error":x);}

```

Saved a few bytes by improving hash formula.

Here's a fun test case:

```
AUGUAUCAUGAGCUCCUUCAGUGGCAAAGACUUGACUGA --> MYHELLQWQRLD*

```

**Explanation**

The triplet of letters is converted to a base 4 number. Each letter is hashed as follows.

```
x[i]       ASCII code       Hashed to (-x[i]/2&3)
A        64+ 1  1000001            00
G        64+ 7  1000111            01
U        64+21  1010101            10
C        64+ 3  1000011            11

```

This gives a number in the range `0..63`. The idea now is to use a lookup table similar to the ones used by edc65 and Optimizer. However, the hash is designed so that G and A are next to each other and U and C are next to each other.

Looking at the table at https://en.wikipedia.org/wiki/Genetic\_code#RNA\_codon\_table, we see that with the letters ordered in this way, generally the last bit can be ignored. Only a 32-character lookup table is needed, except in two special cases.

See below first two letters, and corresponding amino acids (where 3rd letter is G/A, and where 3rd letter is U/C). Corrections for the two special cases that do not fit the 32-character table are hardcoded.

```
     A/G U/C          A/G U/C            A/G U/C         A/G U/C
AAX> K   N       AGX> R   S         AUX> I   I      ACX> T   T
GAX> E   D       GGX> G   G         GUX> V   V      GCX> A   A
UAX> *   Y       UGX> *   C         UUX> L   F      UCX> S   S
CAX> Q   H       CGX> R   R         CUX> L   L      CCX> P   P

Corrections for special cases (where last bit cannot be ignored)
AUG 001001=9 -->  M
UGG 100101=37-->  W

```

**Commented code**

In golfed version the `i%3` code is in the increment position of the `for` bracket, but it is moved into a more readable position in the commented code.

```
a,i,j;char x[999];                                                             //Array x used for storing both input and output. i=input pointer, j=output pointer.
main(s){                                                                       //s is commandline string count. if no arguments, will be set to zero. Will be used to count stops.
  for(gets(x);x[i];)                                                           //Get a string, loop until end of string (zero byte) found
    a=a*4+(-x[i++]/2&3),                                                       //Hash character x[i] to a number 0-3. leftshift any value already in a and add the new value. Increment i.
    i%3||(                                                                     //if i divisible by 3,
      s-=(x[j++]=a-37?a-9?"KNRSIITTEDGGVVAA*Y*CLFSSQHRRLLPP"[a/2]:77:87)==42,  //lookup the correct value in the table. for special cases a=24 and a=32 map to 'M' and 'W' (ASCII 77 and 87). If character is '*' (ASCII42) decrement s.
      x[j]=a=0                                                                 //reset a to 0. clear x[j] to terminate output string.
    );
  puts((*x-77||i%3||s||x[j-1]-42)?"Error":x);                                  //if first character not M or i not divisible by 3 or number of stops not 1 or last character not * print "Error" else print amino acid chain.
}

```

# Answer
> 6 votes
# CJam, ~~317 121~~ 104 bytes

```
q3/{{"ACGU"#}%4b"KN T RS IIMI QH P R L ED A G V *Y S *CWC LF"S/{_,4\/*}%s=}%_('M=\)'*=\'*/,1=**\"Error"?

```

This can still be golfed further.

*Updated* the mapping mechanism to the one used in edc65's answer. Even though I came up with this on my own, he beat me to it :)

**UPDATE** : Shortened the codon table map by observing the pattern in it.

Try it online here

# Answer
> 3 votes
### GolfScript (103 bytes)

```
{)7&2/}%3/{4base'GGEDAAVVRSKNTTMIRRQHPPLLWC*YSSLF'{..'MW'?'I*'@),+=}%=}%''+.'*'/(1<'M'=*['']=*'Error'or

```

Online demo (NB doesn't include the two largest test cases because it needs to run in 15 seconds).

### Dissection

As Steve Verrill pointed out in the sandbox, the lookup table can be reduced to 32 elements plus two special cases. It turns out that the special cases both involve characters (`M` and `W` respectively) which only occur once, and with the right mapping of the characters to base 4 digits it's possible to build the full 64-element lookup table from the 32 elements by doing a duplicate-and-`tr`:

```
'GGEDAAVVRSKNTTMIRRQHPPLLWC*YSSLF'  # 32-element lookup table
{                                   # Map over the 32 elements...
  .                                 #   Duplicate the element
  .'MW'?'I*'@),+=                   #   Apply tr/MW/I*/ to the duplicate
}%

```

Then once we've done the decode, the validation allows for many approaches. The shortest I've found is

```
.'*'/       # Duplicate and split the copy around '*' retaining empty strings
(1<'M'=*    # Pull out the first string from the split (guarantee to exist even if input is
            # the empty string); if it starts with 'M' leave the rest of the split intact;
            # otherwise reduce it to the empty array
['']=       # Check whether we have ['']. If so, the split produced [prefix ''] where
            # prefix begins with 'M'. Otherwise we want an error.
*           # If we have an error case, reduce the original decoded string to ''
'Error'or   # Standard fallback mechanism

```

# Answer
> 1 votes
# Python, 473 bytes

```
t={'U(A[AG]|GA)':'*','GC.':'A','UG[UC]':'C','GA[UC]':'D','GA[AG]':'E','UU[UC]':'F','GG.':'G','CA[UC]':'H','AU[UCA]':'I','AA[AG]':'K','(UU[AG]|CU.)':'L','AUG':'M','AA[UC]':'N','CC.':'P','CA[AG]':'Q','(CG.|AG[AG])':'R','(UC.|AG[UC])':'S','AC.':'T','GU.':'V','UGG':'W','UA[UC]':'Y'}
import re
i=raw_input()
a=''
for x in[i[y:y+3]for y in range(0,len(i),3)]:
 a+=[t[u]for u in t.keys()if re.match(u, x)][0]
print["Error",a][all((a[0]+a[-1]=="M*",len(i)%3==0,not"*"in a[1:-1]))]

```

# Answer
> 1 votes
# Python 2, ~~370~~ ~~358~~ 354 bytes

This is a very straight forward approach using no compression, just trying to pack the information quite densly:

```
s=lambda x:x and[x[:3]]+s(x[3:])or[]
def f(I):O=''.join(d*any(0==x.find(p)for p in e)for x in s(I)for d,e in zip('*ACDEFGHIKLMNPQRSTVWY',map(s,'UAAUAGUGA,GC,UGUUGC,GAUGAC,GAAGAG,UUUUUC,GG,CAUCAC,AUUAUCAUA,AAAAAG,UUAUUGCU,AUG,AAUAAC,CC,CAACAG,AGAAGGCG,AGUAGCUC,AC,GU,UGG,UAUUAC'.split(','))));return['Error',O][len(I)%3==0==len(O)-O.find('*')-(O[0]=='M')]

```

**Edit:** Shaved off a few characters following xnor's suggestion.

# Answer
> 1 votes
## Scala (317 chars)

```
def g(c:Char)="ACGU"indexOf c;def h(s:String,i:Int)=g(s(i))*16+g(s(i+1))*4+g(s(i+2));def p(a:Int)=a!=48&&a!=50&&a!=56;def f(s:String)=if(s.length%3!=0||h(s,0)!=14||p(h(s,s.length-3)))"Error"else{var r="";for(i<-0 to s.length-3 by 3)r+="KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"charAt h(s,i);r}

```

The main function is `f`. Of course, a better choice would be to return an `Option[String]`.

# Answer
> 0 votes
# JavaScript (ES6), 143 bytes

```
s=>/^M\w*\*$/.test(s=s.replace(/.../g,c=>"PVLVLHDVLGRGRAPGR*KYNVL*KTSTSGRTSILIFYNMLR*SCTSRWEQDHIFEQPAPASC.A"[parseInt(c,36)%128%65]))?s:'Error'

```

Try it online!

---
Tags: code-golf, bioinformatics
---


title: Implement the 2D Hadamard Transform

text:
# Question
Title: Implement the 2D Hadamard Transform
The Hadamard transform works similarly to the Fourier transform: it takes a vector and maps it to its frequency components, which are the Walsh functions. Instead of sine waves in the Fourier transform, the Walsh functions are discrete "square waves" so to speak. This makes it easier to compute.

The size of a Hadamard matrix is a power of two, `2^n x 2^n`. We can build a Hadamard matrix for a given `n` recursively. $$H\_1 = \begin{pmatrix}1&1\\1 & -1\end{pmatrix}$$ And then build block matrices in the same pattern to get $$H\_n = \begin{pmatrix}H\_{n-1}&H\_{n-1}\\H\_{n-1} & -H\_{n-1}\end{pmatrix}$$

For instance,

$$H\_3 = \begin{pmatrix}1&1&1&1&1&1&1&1\\1&-1&1&-1&1&-1&1&-1\\1&1&-1&-1&1&1&-1&-1\\1&-1&-1&1&1&-1&-1&1\\1&1&1&1&-1&-1&-1&-1\\1&-1&1&-1&-1&1&-1&1\\1&1&-1&-1&-1&-1&1&1\\1&-1&-1&1&-1&1&1&-1\end{pmatrix} = \begin{pmatrix}H\_2&H\_2\\H\_2&-H\_2\end{pmatrix}$$

Note how the entries are always `1` or `-1` and symmetric! Easy! Then the Hadamard transform is simply multiplying `H_n` by a column vector and dividing by `2^n`.

In order to apply the Hadamard transform to 2D images, we have to apply the 1D HT across every column and then every row. In short, for an input matrix X, the output will be a new matrix Y given by two matrix multiplications:

$$Y = \frac{1}{2^{2n}}H\_nXH\_n$$

Another way to implement this is by first applying the HT to every column in the image separately. Then apply it to every row, pretending they were column vectors. For example, to compute the 2D HT of $$\begin{pmatrix}2 & 3\\ 2 & 5\end{pmatrix}$$

we first do

$$\frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}2 \\ 2\end{pmatrix} = \begin{pmatrix}2 \\ 0\end{pmatrix} \quad\quad\quad \frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}3 \\ 5\end{pmatrix} = \begin{pmatrix}4 \\ -1\end{pmatrix} \quad\rightarrow\quad \begin{pmatrix}2&4\\0 & -1\end{pmatrix} $$

which takes care of the columns, and then we do the rows,

$$\frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}2 \\ 4\end{pmatrix} = \begin{pmatrix}3 \\ -1\end{pmatrix} \quad\quad\quad \frac{1}{2}\begin{pmatrix}1&1\\1 & -1\end{pmatrix}\begin{pmatrix}0 \\ -1\end{pmatrix} = \begin{pmatrix}-0.5 \\ 0.5\end{pmatrix} \quad\rightarrow\quad \begin{pmatrix}3&-1\\\-0.5 & 0.5\end{pmatrix} $$

Finally, one can also compute this recursively using the *fast Hadamard transform*. It's up to you to find out if this is shorter or not.

## Challenge

Your challenge is to perform the 2D Hadamard transform on a 2D array of arbitrary size `2^n x 2^n`, where `n > 0`. Your code must accept the array as input (2D array or a flattened 1D array). Then perform the 2D HT and output the result.

In the spirit of flexibility, you have a choice for the output. Before multiplying by the prefactor `1/(2^(2n))`, the output array is all integers. You may either multiply by the prefactor and output the answer as floats (no formatting necessary), **or** you may output a string `"1/X*"` followed by the array of integers, where `X` is whatever the factor should be. The last test case shows this as an example.

You may **not** import the Hadamard matrices from some convenient file that already contains them; you must build them inside the program.

## Test Cases

Input:

```
2,3
2,5

```

Output:

```
3,-1
-0.5,0.5

```

Input:

```
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

```

Output:

```
1,0,0,0
0,0,0,0
0,0,0,0
0,0,0,0

```

Input:

```
1,0,0,0
1,1,0,0
1,1,1,0
1,1,1,1

```

Output:

```
0.6250,0.1250,0.2500,0
-0.1250,0.1250,0,0
-0.2500,0,0.1250,0.1250
0,0,-0.1250,0.1250

```

Input:

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

```

Output:

```
1/64*
36,4,8,0,16,0,0,0
-4,-36,0,-8,0,-16,0,0
-8,0,-36,-4,0,0,-16,0
0,8,4,36,0,0,0,16
-16,0,0,0,-36,-4,-8,0
0,16,0,0,4,36,0,8
0,0,16,0,8,0,36,4
0,0,0,-16,0,-8,-4,-36

```

## Scoring

This is code golf, so the smallest program in bytes wins.

# Answer
> 13 votes
## Haskell, ~~111~~ ~~102~~ ~~97~~ 92 bytes

```
import Data.Matrix
t x|n<-nrows x=h n*x*h n
h 1=1
h i|m<-h$div i 2=(/2)<$>m<->m<|>(m<->(-m))

```

This uses the `Data.Matrix` module. The input matrix has to be of type `Matrix Float` or `Matrix Double`.

TIO doesn't provide `Data.Matrix`, so no link.

Edit: -9 bytes thanks to @ceased to turn counterclockwis, -5 bytes thanks to @H.PWiz, -5 bytes thanks to @xnor

# Answer
> 10 votes
# JavaScript (ES6), 114 bytes

This version is golfed a bit further by embedding the function \\$h\\$ within the callback of the deepest loop.

```
M=>(g=z=>M=M.map((r,y)=>r.map((_,x)=>r.map(v=>s+=(h=m=>m?-h(m&~-m):z?v:M[i-1][x])(i++&(z?x:y)),i=s=0)&&s/i)))(g())

```

Try it online!

---

# JavaScript (ES6),  ~~161 ... 117~~  116 bytes

```
M=>(h=m=>m?-h(m&~-m):1,g=z=>M=M.map((r,y)=>r.map((_,x)=>r.map(v=>s+=(z?v:M[i][x])*h(i++&(z?x:y)),s=i=0)&&s/i)))(g())

```

Try it online!

### How?

Each 0-indexed cell \\$(x,y)\\$ of a Hadamard matrix \\$H\_n\\$ is equal to:

$$H\_n(x,y)=\cases{ 1,&\text{if $(x\And y)$ is evil}\\ -1,&\text{otherwise} }$$

or:

$$H\_n(x,y)=(-1)^{\operatorname{popcount}(x \And y)}$$

where \\$\And\\$ is a bitwise AND and \\$\operatorname{popcount(m)}\\$ is the number of bits set in \\$m\\$.

The function \\$h\\$ computes \\$(-1)^{\operatorname{popcount}(m)}\\$ recursively:

```
h = m => m ? -h(m & ~-m) : 1

```

(This is similar to my answer to Is this number evil?)

The function \\$g\\$ computes either \\$\frac{1}{2^n}H\_nM\\$ or \\$\frac{1}{2^n}MH\_n\\$, depending on the flag \\$z\\$:

```
g = z =>                      // z = flag cleared on the 1st pass, set on the 2nd
  M =                         // update M[]:
    M.map((r, y) =>           //   for each row r[] at position y in M[]:
      r.map((_, x) =>         //     for each cell at position x in r[]:
        r.map(v =>            //       for each value v in r[]:
          s +=                //         add to s:
            (z ? v            //           v = M(i, y) if z is set,
               : M[i][x]) *   //             or M(x, i) otherwise
            h(i++ & (z ? x    //           multiplied by H(x, i) if z is set,
                       : y)), //             or H(i, y) otherwise
                              //           and increment i afterwards
          s = i = 0           //         start with s = i = 0
        )                     //       end of inner map() over the columns
        && s / i              //       yield s divided by the width of the matrix
      )                       //     end of outer map() over the columns
    )                         //   end of map() over the rows

```

We invoke it twice to compute \\$\frac{1}{2^{2n}}H\_nMH\_n\\$.

# Answer
> 9 votes
# MATL, 12 bytes

```
&nKYLw/Gy,Y*

```

Try it online! Or verify all test cases.

### Explanation

Consider input `[2,3; 2,5]` as an example.

```
&n     % Input (implicit). Push number of rows and number of columns
       % STACK: 2, 2
KYL    % Hadamard matrix of specified size
       % STACK: 2, [1 1; 1 -1]
w/     % Swap, divide element-wise
       % STACK: [0.5 0.5; 0.5 -0.5]
G      % Push input again
       % STACK: [0.5 0.5; 0.5 -0.5], [2,3; 2,5]
y      % Duplicate from below
       % STACK: [0.5 0.5; 0.5 -0.5], [2,3; 2,5], [0.5 0.5; 0.5 -0.5]
,      % Do twice
  Y*   %   Matrix multiply
       % End (implicit)
       % STACK: [3 -1; -0.5 0.5]
       % Display (implicit)

```

# Answer
> 5 votes
# Octave, ~~93~~ 79 bytes

```
@(x)(r=f(f=@(f)@(x){@()[x=f(f)(x-1) x;x -x],1}{1+~x}())(log2(r=rows(x)))/r)*x*r

```

This computes \\$\frac{1}{2^n}H\_nX\frac{1}{2^n}H\_n\\$

Try it online!

# Octave, ~~47~~ 33 bytes (uses builtin)

```
@(x)(r=hadamard(r=rows(x))/r)*x*r

```

Try it online!

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

```
{(⍵∘⌹+.×⌹)(,⍨⍪⊢,-)⍣(2⍟≢⍵)⍪1}

```

Try it online!

# Answer
> 3 votes
# Brachylog, 23 bytes

```
{ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ\↰₁ᵐ

```
* Input: A list of columns
* Output: A list of rows

## How:

It uses the Fast Hadamard Transformation. AFAIK Brachylog doesn't have matrix multiplication, nor binary operations so I doubt using the "evil numbers technique" will help shorten the code.

```
    {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ\↰₁ᵐ   #
    {ḍ\⟨+ᵐ↰₁ᵐ-ᵐ⟩c/₂ᵐ|}ᵐ       # Fast transform:
    {               }ᵐ       #   for each column:
     ḍ                       #     Split in 2
                   |         #       (if this fails, return the collum.
                             #         This is the case in the final recursion step)
      \                      #      Zip,
        +ᵐ                   #         and add each pair  (adds the 2 subvectors)
             -ᵐ              #         and sub each pair  (subs the 2 subvectors)
       ⟨  ↰₁ᵐ  ⟩              #      and apply the transformation on both results
               c             #      concat both transformed results.
                 /₂^m        #        and half each element
                      \      #  Transpose
                       ↰₁ᵐ   #    and apply the transformation again

```

Try it online!

# Answer
> 2 votes
# Jelly, 18 bytes

```
J’&þ`B§-*ðæ×⁺@÷L$⁺

```

A monadic Link accepting a list of lists of integers (any numbers really), the square input matrix of side \\$2^n\\$, which yields a list of lists of floats.

**Try it online!**

### How?

It feels like one should be able to outer-product the dot-product of the binary representations of the 0-indexed coordinates, however to do so one would need to left-pad the binary representations with zeros which, I believe, costs too many bytes.

```
J’&þ`B§-*ðæ×⁺@÷L$⁺ - Link: list of lists of integers, M
J                  - range of length = [1,2,...,rows(M)]
 ’                 - decrement (vectorises) = [0,1,...,rows(M)-1]
    `              - use left argument as both arguments of:
   þ               -   outer-product with:
  &                -     bit-wise AND         [[0&0, 0&1, ...],[1&0, 1&1, ...], ...]
     B             - convert to binary (vectorises)
      §            - sums (vectorises at depth 1) - i.e. bit-sums
       -           - literal minus one
        *          - exponentiate (vectorises) - i.e. the appropriately sized Hadamard matrix, H
         ð        - start a new dyadic chain - i.e. f(H, M)
          æ×       - matrix multiply - i.e. H×M
             @     - with swapped arguments i.e. f(H×M, H):
            ⁺      -   repeat previous link i.e. H×M×H
                $  - last two links as a monad:
               L   -   length (number of rows)
              ÷    -   divide (vectorises)
                 ⁺ - repeat the previous link (divide by the length again)

```

# Answer
> 1 votes
# , ~~80~~ ~~78~~ 74 bytes

```
function(M){for(i in 1:log2(nrow(M)))T=T%x%matrix(1-2*!3:0,2)/2
T%*%M%*%T}

```

Try it online!

Calculates \\$\frac{1}{2^n}H\_nX\frac{1}{2^n}H\_n\\$; constructs \\$\frac{1}{2^n}H\_n\\$ by Kronecker product `%x%`.

Looks like I can still golf, recalling that `1-2*!3:0` is shorter than `c(1,1,1,-1)` as I realized in the comments to this answer.

# Answer
> 1 votes
# Pari/GP, 51 bytes

```
a->h=1;while(#h<#a,h=matconcat([h,h;h,-h])/2);h*a*h

```

Try it online!

---
Tags: code-golf, matrix
---


title: Don't get banned from stack exchange!

text:
# Question
Title: Don't get banned from stack exchange!
I'm sure this is going to spark some controversy, but let's do a practical demonstration.

The objective of this is simple, using the new code of conduct and no input, print out my pronouns ( "he/him", "he him" is also acceptable).

Here's the challenge. This is a classical polyglot contest!

This means that the first answer can be in any language, and the only requirement is that the user post their number (1), their language, and their code. The second user must then rework this code to satisfy the condition with the first answers language, and any other language that hasn't been used. Adding code is the preferred method of polyglotting, but subtraction is ok too. This keeps going until we have a program which works simultaneously in many languages. No language should appear twice. Breaking the contest functionality in any previous language would make an answer invalid

An example:

First person to post code:
1. C++
\[Code\]

Second person to post code:
2. Python.
\[Altered Code\]

Third person to post code:
3. Java.
\[Further altered code\]

The winner will be the last answer that stands uncontested for 4 weeks.

This is a high steaks round, as the penalty for intentionally posting code which mis-genders me, could be a ban from the site itself (though I, unlike stack exchange, am able to overlook this)! Best of luck!

For Additional reference, he'res the clarification on chaining rules.

> # Additional rules
>
> * Your program must run without erroring out or crashing. Warnings (and other stderr output) are acceptable, but the program must exit normally (e.g. by running off the end of the program, or via a command such as `exit` that performs normal program termination).
> * Each answer must be no more than 20% or 20 bytes (whichever is larger) longer than the previous answer. (This is to prevent the use of languages like Lenguage spamming up the thread, and to encourage at least a minor amount of golfing.)
> * Tricks like excessive comment abuse, despite being banned in some polyglot competitions, are just fine here.
> * You don't have to use the previous answers as a guide to writing your own (you can rewrite the whole program if you like, as long as it complies with the spec); however, basing your answer mostly on a previous answer is allowed and probably the easiest way to make a solution.
> * You cannot submit two answers in a row. Let someone else post in between. This rule applies until victory condition is met.
> * As this challenge requires other competitors to post in the same languages you are, you can only use languages with a free implementation (much as though this were a contest).
> * In the case where a language has more than one interpreter, you can pick any interpreter for any given language so long as all programs which are meant to run successfully in that language do so in that interpreter. (In other words, if a program works in more than one interpreter, future posts can pick either of those interpreters, rather than a post "locking in" a particular choice of interpreter for a language.)
> * This challenge now uses the new PPCG rules about language choice: you can use a language, or a language interpreter, even if it's newer than the question. However, you may not use a language/interpreter that's newer than the question if a) the language was designed for the purpose of polyglotting or b) the language was inspired by this question. (So newly designed practical programming languages are almost certainly going to be OK, as are unrelated esolangs, but things like A Pear Tree, which was inspired by this question, are banned.) Note that this doesn't change the validity of languages designed for polyglotting that are older than this question.
> * Note that the victory condition (see below) is designed so that breaking the chain (i.e. making it impossible for anyone else to answer after you via the use of a language that is hard to polyglot with further languages) will disqualify you from winning. The aim is to keep going as long as we can, and if you want to win, you'll have to respect that.

# For reference, this is the exact CoC I'm referring to, consolidated as per the request of many users for clairity:

> We expect today’s changes to the Code of Conduct to generate a lot of questions. We’ve tried to anticipate some of the most common questions people may have here, and we’ll be adding to this list as more questions come up.
>
> **Q1: What are personal pronouns, and why are they relevant to the Code of Conduct?**
>
> Personal pronouns are a way to refer to a person without using their name, when the subject is known. From mypronouns.org:
>
> > *The vast majority of people go by the pronouns sets “he/him” or “she/her.” A small but increasing number of people use “they/them” pronouns or another pronouns set -- sometimes simply because they don’t want to go by pronouns with a gender association (just as some folks go by “Ms.” whether or not they are married, because they don’t think their marital status should be a relevant issue), and sometimes people use pronouns that aren’t associated with one of those two most common (binary) genders because they are nonbinary (i.e. people who are neither exclusively a man nor exclusively a woman -- e.g. genderqueer, agender, bigender, fluid, third/additional gender in a cultural tradition, etc.).*
>
> The goal of our Code of Conduct is to help us “build a community that is rooted in kindness, collaboration, and mutual respect.” Using someone’s pronouns is a way of showing respect for them and refusing to do so causes harm.
>
> **Q2: What does the Code of Conduct say about gender pronouns?**
>
> The Code of Conduct has two direct references to gender pronouns:
>
> 1. “Use stated pronouns (when known).”
> 2. “Prefer gender-neutral language when uncertain.”
>
> We’re asking everyone to do two things. First, if you do know someone’s pronouns (e.g. because they told you), then use them as you normally would use any pronoun. Second, if you don’t know someone’s pronouns, use gender-neutral language rather than making an assumption.
>
> **Q3: What should I do if I make a mistake and use the wrong pronouns?**
>
> If you make a mistake, apologize and correct your mistake if possible (e.g. by editing your post). We recognize that this may be new to many people, particularly members of our community who do not speak English as a first language, and so mistakes will happen as we all learn together.
>
> **Q4: What should I do if I see someone using the wrong pronouns?**
>
> If you notice someone who is using the wrong pronouns for someone else who has stated them (e.g. in a comment or on their profiles), we encourage you to gently correct them in a comment. Do not state pronouns for third parties who have not done so in Stack Exchange (eg. You know them in person). If the situation escalates, please flag what you see. A moderator or community manager will look into it further.
>
> **Q5: How will this be moderated? Will we ban people based on one mistake?**
>
> We understand that miscommunication or mistakes may happen, so most situations will just result in a gentle correction or warning. As with any violation of the Code of Conduct, in cases of willful, repeated, or abusive behavior, warnings may escalate to account suspensions and/or expulsion.
>
> **Q6: What should I do if I don't know someone's pronouns?**
>
> When in doubt, use gender-neutral language or refer to the user by name.
>
> **Q7: Are we going to force everyone to identify their pronouns?**
>
> No. Just as we do not force users to identify their real name, we will never force users to identify their pronouns. This is a voluntary decision by each user to share as much or as little as they are comfortable.
>
> **Q8: How should I identify my pronouns if I choose to do so?**
>
> Whether and how you identify your pronouns is up to you. If you choose to do so, add it to the “About Me” section of your user profile.
>
> **Q9: Do I have to use pronouns I’m unfamiliar or uncomfortable with (e.g., neopronouns like xe, zir, ne... )?**
>
> Yes, if those are stated by the individual.
>
> **Q10: What if I believe it is grammatically incorrect to use some pronouns (e.g. they/them to refer to a single person)?**
>
> If they are the pronouns stated by the individual, you must respect that and use them. Grammar concerns do not override a person’s right to self identify.
>
> **Q11: If I’m uncomfortable with a particular pronoun, can I just avoid using it?**
>
> We are asking everyone to use all stated pronouns as you would naturally write. Explicitly avoiding using someone’s pronouns because you are uncomfortable is a way of refusing to recognize their identity and is a violation of the Code of Conduct.
>
> **Q12: Does this mean I’m required to use pronouns when I normally wouldn’t?**
>
> We are asking everyone to use all stated pronouns as you would naturally write. You are not required to insert pronouns where you otherwise would not.
>
> From @CesarM (staff): You have to use their stated pronouns in places where you'd include a pronoun. If you wouldn't include a pronoun in the sentence, you don't have to go out of your way to find a place to include one.
>
> **Q13: How does this apply to languages other than English?**
>
> For now, while the intent of being inclusive and respectful of all gender identities applies to all our communities, the specific requirements around pronoun usage apply only to English language sites. As we determine best practices in other languages, we’ll work with those communities and update guidance for those languages.
>
> **Q14: Should all posts be written using gender-inclusive language? Should we edit all old posts to be gender-inclusive?**
>
> The focus of this change is on using correct pronouns when addressing other members of the community. However, writing posts in a gender-inclusive way is encouraged and a great way to make the community more accessible to more people. If you are writing or editing a post and can make it gender-inclusive without changing the meaning, you are encouraged to do so.
>
> **Q15: Is it expected that people go to "About me" to check whether someone has pronouns there when interacting in Q&A?**
>
> No. That would be good practice, but it is not *required*.
>
> From @jnat (staff): We ask that you use gender-neutral language when uncertain, and use the stated pronouns once they're made known. If you wanna "go the extra mile," looking at the user's "about me" before interacting is certainly nice, but we're not requiring it.
>
> From @CesarM (staff): *Made known* is when you become aware of the fact. If it's in the comments, then, fine. Correct and move on. There's no obligation to go out of your way to seek it out, but if someone tells you directly, comply.
>
> **Q16: May I use *they/them* by default?**
>
> Yes, but be prepared to make adjustments if so requested.
>
> From @Catija (staff) If you use *they/them* by default, that's fine. If someone requests that you use other pronouns and you immediately continue to use *they/them* for that person, we may point it out to you. "Penalized" in most cases is generally going to be as minor as a comment being removed or adjusted to meet the request of the person being spoken about. Only in extreme cases of repeated requests to change, will it lead to a mod message or suspension.
>
> **Q17: What should I do if I think someone requests me to use a certain pronoun in bad faith?** From @Cesar M(Staff)
>
> > If people are requesting things in bad faith, you are welcome to escalate to mods and mods can contact us CMs when in doubt too.
>
> It is advised to use a custom (Something Else) flag for this. Please explain, as detailed as possible, what the issue is.
>
> Return to FAQ index

# Answer
# 1. Keg, 6 bytes

```
he him

```

Try it online!

Real easy one for Keg, just print the desired output.
> 5 votes

---
Tags: kolmogorov-complexity, polyglot, answer-chaining
---


title: An A , or An An?

text:
# Question
Title: An A , or An An?
In English, there is the fun and simple difference between `an` and `a`: you use `an` when preceding a word starting with a vowel sound, and `a` when the word starts with a consonant sound.

For the sake of simplicity in this challenge, `an` precedes a word that starts with a vowel (`aeiou`), and `a` precedes a word that starts with a consonant.

**Input**

A string comprising only printable ASCII characters, with `[?]` appearing in places where you must choose to insert `an` or `a`. `[?]` will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.

**Output**

The input string with `[?]` replaced with the appropriate word (`an` or `a`). You do have to worry about capitalization!

**When to Capitalize**

Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of `.?!` followed by a space.

**Examples**

```
Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?

```

**This is , so shortest code in bytes wins!**

# Answer
> 6 votes
# , 41 bytes

```
ÍãÛ?Ý ¨[aeiou]©/an
ÍÛ?Ý/a
Í^aü[.!?] a/A

```

Try it online!, which conveniently can also be used to verify all test cases with no extra byte count.

This takes advantage of V's "Regex Compression". It uses a lot of unprintable characters, so here is a hexdump:

```
0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9  ...?.. .[aeiou].
0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b  /an...?./a..^a.[
0000020: 2e21 3f5d 2093 612f 41                   .!?] .a/A

```

# Answer
> 7 votes
# Perl, 48 bytes

*Saved 1 byte due to Ton Hospel.*

```
#!perl -p
s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg

```

Counting the shebang as one, input is taken from stdin.

**Explanation**

```
#!perl -p               # for each line of input, set $_, auto-print result

s;                      # begin regex substitution, with delimiter ;
\[\?]                   # match [?] literally, and replace with:
;
A.n x$'=~/^ [aeiou]/i   # 'A', concatenate with 'n' if post-match ($')
                        #   matches space followed by a vowel
^$"x/[^.?!] \G/         # if the match is preceded by /[^.?!] /, xor with a space
                        #   this will change An -> an

;eg                     # regex options eval, global

```

**Sample Usage**

```
$ echo Hello, this is [?] world! | perl a-an.pl
Hello, this is a world!

$ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl
How about we build a big building. It will have an orange banana hanging out of a window.

$ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl
A giant en le sky. A yarn ball?

$ echo [?] hour ago I met [?] European. | perl a-an.pl
A hour ago I met an European.

```

# Answer
> 7 votes
# Ruby, ~~78~~ 72 bytes

```
->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}}

```

**Ungolfed**

```
def f(s)
    s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m|
        capitalize = $1
        vowel = $2
        replacement = if vowel then
            capitalize ? "An" : "an"
        else
            capitalize ? "A" : "a"
        end
        m.sub('[?]', replacement)
    end
end

```

# Answer
> 6 votes
# PHP, 207 bytes

```
foreach(explode("[?]",$s)as$i=>$b){$r=Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])].n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))];echo$i?$r.$b:$b;$a=$i?''==$d?a:$b:(''==$d?".":a);}

```

I like solutions more complete from time to time ...
but I must admit that this is a little overkill, although it´s not at all finished.

Save to file, run with `php <filename>` with input from STDIN.

**test cases**

```
How about we build [?] big building ... with [?] orange banana hanging out of [?] window.
=>  How about we build a big building ... with an orange banana hanging out of a window.

Hello, this is [?] world!               =>  Hello, this is a world!
Should I use [?] '[?]' or [?] '[?]'?    =>  Should I use an 'an' or an 'a'?
[?] elephant in [?] swimsuit.           =>  An elephant in a swimsuit.

How I met your moth[?].                 =>  How I met your motha.
b[?][?][?] short[?]ge!                  =>  banana shortage!

```

**breakdown**

```
foreach(explode("[?]",$s)as$i=>$b)
{
    $r=
        // lookbehind: uppercase if the end of a sentence precedes
        Aa[$k=0|!strstr(".!?",''==($c=trim($a))?".":$c[strlen($c)-1])]
        .
        // lookahead: append "n" if a vowel follows (consider quote characters blank)
        n[!preg_match("#^['\"´`\s]*([aeiou]|$)#i",$d=trim($b))]
    ;
    // output replacement and this part
    echo$i?$r.$b:$b;
    // prepare previous part for next iteration
    $a=$i               // this part was NOT the first:
        ?   ''==$d
            ? a             // if empty -> a word ($r from the previous iteration)
            : $b            // default: $b
        :  (''==$d      // this WAS the first part:
            ? "."           // if empty: end of a sentence (= uppercase next $r)
            : a             // else not
        )
    ;
    // golfed down to `$a=!$i^''==$d?a:($i?$b:".");`
}

```

# Answer
> 5 votes
## Minkolang 0.15, 75 bytes

```
od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r

```

Try it here!

### Explanation

```
od                                                                    Take character from input and duplicate (0 if input is empty)
  4&                                                                  Pop top of stack; jump 4 spaces if not 0
    r$O.                                                              Reverse stack, output whole stack as characters, and stop.

    "]?["                                                             Push "[?]" on the stack
         30$Z                                                         Pop the top 3 items and count its occurrences in the stack
              3&                                                      Pop top of stack; jump 3 spaces if not 0
                00w                                                   Wormhole to (0,0) in the code box

                3X                                                    Dump the top 3 items of stack
                  "Aa"                                                Push "aA"
                      I2-                                             Push the length of stack minus 2
                         "Aa ."40$Z,                                  Push ". aA" and count its occurrences, negating the result
                                    *                                 Multiply the top two items of the stack
                                     2&$r                             Pop top of stack and swap the top two items if 0
                                         x                            Dump top of stack
                                          r                           Reverse stack
                                           $O                         Output whole stack as characters
                                             " aeiou"                 Push a space and the vowels
                                                     od               Take a character from input and duplicate
                                                       0Z             Pop top of stack and count its occurrences in the stack (either 1 or 2)
                                                         1=           1 if equal to 1, 0 otherwise
                                                           3&         Pop top of stack; jump 3 spaces if not 0
                                                             "n"      Push "n" if top of stack is 0

                                                             r        Reverse stack
                                                              5X      Dump top five items of stack
                                                                $r    Swap top two items of stack

```

Note that because Minkolang is toroidal, when the program counter moves off the right edge, it reappears on the left. Certainly golfable, but because I had to add 21 bytes because of the spec, I may not try.

# Answer
> 3 votes
# JavaScript (ES6), 90  ~~86 87 85~~

*Edit once more* as the spec for capitalization has changed (more sensible now)

*Edit again* 1 byte save thx @Huntro

*Edit* 2 more bytes to manage quotes and the like, as pointed out by IsmaelMiguel (even if I don't know if it's requested by op). Note that previously I had counted 86 bytes but they were 85

~~Trying to follow the capitalization rule stated in the comments event if it's incomplete (at least)~~

```
x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

```

**Test**

```
f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

function go() {
  var i=I.value, o=f(i)
  O.innerHTML = '<i>'+i+'</i>\n<b>'+o+'</b>\n\n'+O.innerHTML
}

go()
```

```
#I { width:80% }
```

```
<input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button><pre id=O></pre>
```

# Answer
> 2 votes
## Batch, 136 bytes

```
@set/ps=
@for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%%
@set s=%s:[?]=a%
@if %s:~0,1%==a set s=A%s:~1%
@echo %s:. a=. A%

```

Takes a line of input on STDIN.

# Answer
> 2 votes
# Python 3.5.1, ~~153~~ ~~147~~ 141 ~~124~~ Bytes

```
*s,=input().replace('[?]','*');print(*['aA'[i<1or s[i-2]in'.?!']+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*' else c for i,c in enumerate(s)],sep='')

```

Input :

`[?] apple [?] day keeps the doctor away. [?] lie.`

Output :

`An apple a day keeps the doctor away. A lie.`

123 Bytes version - This does not handle capitalization rule.

```
s=list(input().replace('[?]','*'));print(*['a'+'n'*(s[i+2]in 'aeiouAEIOU')if c=='*'else c for i,c in enumerate(s)],sep='')

```

Try it online!

# Answer
> 2 votes
# PHP, ~~100~~ 92 bytes

```
<?=preg_filter(["/\[\?]\K(?= [aeiou])/i","/([.?!] |^)\K\[\?]/","/\[\?]/"],[n,A,a],$argv[1]);

```

It was possible to further golf the regular expressions.

Gives a notice about an undefined constant but still works.

Edit: 8 bytes saved thanks to primo

# Answer
> 2 votes
# Java, ~~180~~178 bytes

My first post here, I did use a part of the **Kevin Cruijssen** post but and up with a different approach, he helped me to reduce a bit more so, thanks to him !

```
String c(String s){String x[]=s.split("\\[\\?]",2),r=x[0];return x.length>1?r+(r.matches("(.+[.!?] )|(^)$")?"A":"a")+("aeiouAEIOU".contains(""+x[1].charAt(1))?"n":"")+c(x[1]):r;}

```

Here it is ungolfed :

```
static String c(String s) {
        String x[] = s.split("\\[\\?\\]", 2), r = x[0];
        return x.length > 1 ? r + (r.matches("(.+[.!?] )|(^)$") ? "A" : "a")
                + ("aeiouAEIOU".contains("" + x[1].charAt(1)) ? "n" : "") + c(x[1]) : r;
    }

```

And the result

A simple explanation, I use a recursive approch to find every `[?]`.

I couldn't find a way to use the matches with insensitive case (not sure it is possible).

178bytes : Thanks to Martin Ender !

# Answer
> 2 votes
# 05AB1E, ~~38~~ ~~36~~ 35 bytes

```
2FžNžM‚NèSðì…[?]©ìDu«D®'a'nN×«::}.ª

```

Try it online or verify all test cases.

**Explanation:**

```
2F            # Loop 2 times:
  žN          #  Push consonants "bcdfghjklmnpqrstvwxyz"
  žM          #  Push vowels "aeiou"
    ‚         #  Pair them together into a list
     Nè       #  And use the loop-index to index into this pair
  S           #  Convert this string to a list of characters
   ðì         #  Prepend a space in front of each character
     …[?]     #  Push string "[?]
         ©    #  Store it in variable `®` (without popping)
          ì   #  And prepend it in front of each string in the list as well
  }D          #  Then duplicate the list
    u         #  Uppercase the characters in the copy
     «        #  And merge the two lists together
              #   i.e. for the vowel-iteration we'd have ["[?] a","[?] e","[?] i","[?] o",
              #    "[?] u","[?] A","[?] E","[?] I","[?] O","[?] U"]
   D          #  Duplicate it
    ®         #  Push "[?]" from variable `®`
     'a      '#  Push "a"
       'n    '#  Push "n"
         N×   #  Repeated the 0-based index amount of times (so either "" or "n")
           «  #  And append it to the "a"
    :         #  Replace all "[?]" with "an"/"a" in the duplicated list
     :        #  And then replace all values of the lists in the (implicit) input-string
 }.ª          #  After the loop: sentence-capitalize everything (which fortunately retains
              #  capitalized words in the middle of sentences, like the "European" testcase)
              # (and after the loop the result is output implicitly)

```

# Answer
> 1 votes
# C#, ~~204~~ 235 bytes

```
string n(string b){for(int i=0;i<b.Length;i++){if(b[i]=='['){var r="a";r=i==0||b[i-2]=='.'?"A":r;r=System.Text.RegularExpressions.Regex.IsMatch(b[i+4].ToString(),@"[aeiouAEIOU]")?r+"n":r;b=b.Insert(i+3,r);}}return b.Replace("[?]","");}

```

Ungolfed full program:

```
using System;

class a
{
    static void Main()
    {
        string s = Console.ReadLine();
        a c = new a();
        Console.WriteLine(c.n(s));
    }

    string n(string b)
    {
        for (int i = 0; i < b.Length; i++)
        {
            if (b[i] == '[')
            {
                var r = "a";
                r = i == 0 || b[i - 2] == '.' ? "A" : r;
                r = System.Text.RegularExpressions.Regex.IsMatch(b[i + 4].ToString(), @"[aeiouAEIOU]") ? r + "n" : r;
                b = b.Insert(i + 3, r);
            }
        }
        return b.Replace("[?]", "");
    }
}

```

I'm sure this could be improved, especially the Regex part, but can't think of anything right now.

# Answer
> 1 votes
## Racket 451 bytes (without regex)

It is obviously a long answer but it replaces a and an with capitalization also:

```
(define(lc sl item)(ormap(lambda(x)(equal? item x))sl))
(define(lr l i)(list-ref l i))(define(f str)(define sl(string-split str))
(for((i(length sl))#:when(equal?(lr sl i)"[?]"))(define o(if(lc(string->list"aeiouAEIOU")
(string-ref(lr sl(add1 i))0))#t #f))(define p(if(or(= i 0)(lc(string->list".!?")
(let((pr(lr sl(sub1 i))))(string-ref pr(sub1(string-length pr))))))#t #f))
(set! sl(list-set sl i(if o(if p"An""an")(if p"A""a")))))(string-join sl))

```

Testing:

```
(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")

```

Output:

```
"A giant en le a sky."
"A yarn ball?"
"A hour ago I met an European."
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"

```

Detailed version:

```
(define(contains sl item)
  (ormap(lambda(x)(equal? item x))sl))

(define(lr l i)
  (list-ref l i))

(define(f str)
  (define sl(string-split str))
  (for((i(length sl))#:when(equal?(lr sl i)"[?]"))
    (define an   ; a or an
      (if(contains(string->list "aeiouAEIOU")
                  (string-ref(lr sl(add1 i))0))
         #t #f ))
    (define cap   ; capital or not
      (if(or(= i 0)(contains(string->list ".!?")
                            (let ((prev (lr sl(sub1 i)))) (string-ref prev
                                       (sub1(string-length prev))))))
         #t #f))
    (set! sl(list-set sl i (if an (if cap "An" "an" )
                                 (if cap "A" "a")))))
  (string-join sl))

```

# Answer
> 1 votes
# Java 7, ~~239~~ ~~214~~ 213 bytes

```
String c(String s){String x[]=s.split("\\[\\?\\]"),r="";int i=0,l=x.length-1;for(;i<l;r+=x[i]+(x[i].length()<1|x[i].matches(".+[.!?] $")?65:'a')+("aeiouAEIOU".contains(x[++i].charAt(1)+"")?"n":""));return r+x[l];}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static String c(String s){
    String x[] = s.split("\\[\\?\\]"),
           r = "";
    int i = 0,
        l = x.length - 1;
    for (; i < l; r += x[i]
                     + (x[i].length() < 1 | x[i].matches(".+[.!?] $")
                        ? 65
                        : 'a')
                     + ("aeiouAEIOU".contains(x[++i].charAt(1)+"")
                        ? "n"
                        : ""));
    return r + x[l];
  }

  public static void main(String[] a){
    System.out.println(c("Hello, this is [?] world!"));
    System.out.println(c("How about we build [?] big building. It will have [?] orange banana hanging out of [?] window."));
    System.out.println(c("[?] giant en le sky."));
    System.out.println(c("[?] yarn ball? [?] big one!"));
    System.out.println(c("[?] hour ago I met [?] European. "));
    System.out.println(c("Hey sir [Richard], how 'bout [?] cat?"));
    System.out.println(c("[?] dog is barking. [?] cat is scared!"));
  }
}

```

**Output:**

```
Hello, this is a world!
How about we build a big building. It will have an orange banana hanging out of a window.
A giant en le sky.
A yarn ball? A big one!
A hour ago I met an European.
Hey sir [Richard], how 'bout a cat?
A dog is barking. A cat is scared!

```

# Answer
> 1 votes
# C (gcc), ~~225~~ ~~207~~ ~~202~~ 201 bytes

Thanks to ceilingcat for -24 bytes

```
#define P strcpy(f+d,index("!?.",i[c-2])+!c?
c;d;v(i,g,f)char*i,*g,*f;{for(d=0;i[c];c++,d++)strcmp("[?]",memcpy(g,i+c,3))?f[d]=i[c]:(index("aeiouAEIOU",i[c+4])?P"An ":"an "),d++:P"A ":"a "),d++,c+=3);}

```

Try it online!

# Answer
> 1 votes
# , 113 bytes

```
[:;:inv 3(0 2&{(((('aA'{~[)<@,'n'#~])~('.?!'e.~{:))~('AEIOUaeiou'e.~{.))&>/@[^:(<@'[?]'=])1{])\' 'cut' . '([,~,)]

```

Try it online!

Shame, shame!

# Answer
> 1 votes
# Retina, ~~66~~ 60 bytes

```
i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])
a$.2*n$1
(^|[.?!] )a
$1A

```

Try it online.

**Explanation:**

Do a case-insensitive search for `[?]`  followed by a vowel or consonant, where the optional vowel is saved in capture group 2, and the entire match in capture group 1:

```
i`\[\?\]( ([aeiou]?)[a-z&&[^aeiou])

```

Replace this with an `a`, followed by the length of the second group amount of `n` (so either 0 or 1 `n`), followed by the letter(s) of capture group 1:

```
a$.2*n$1

```

Then match an `a` at either the start of the string, or after either of `.?!` plus a space:

```
(^|[.?!] )a

```

And uppercase that A, without removing the other characters of capture group 1:

```
$1A

```

# Answer
> 1 votes
# Java (JDK), 154 bytes

```
s->{String v="(?= [aeiou])",q="(?i)\\[\\?]",b="(?<=^|[?.!] )";return s.replaceAll(b+q+v,"An").replaceAll(q+v,"an").replaceAll(b+q,"A").replaceAll(q,"a");}

```

Try it online!

### Explanation:

```
s->{
    String v="(?= [aeiou])",          // matches being followed by a vowel
    q="(?i)\\[\\?]",                  // matches being a [?]
    b="(?<=^|[?.!] )";                // matches being preceded by a sentence beginning
    return s.replaceAll(b+q+v,"An")   // if beginning [?] vowel, you need "An"
        .replaceAll(q+v,"an")         // if           [?] vowel, you need "an"
        .replaceAll(b+q,"A")          // if beginning [?]      , you need "A"
        .replaceAll(q,"a");}          // if           [?]      , you need "a"

```

# Answer
> 0 votes
# Groovy, ~~73~~ 162 bytes

```
def a(s){s.replaceAll(/(?i)(?:(.)?( )?)\[\?\] (.)/){r->"${r[1]?:''}${r[2]?:''}${'.?!'.contains(r[1]?:'.')?'A':'a'}${'aAeEiIoOuU'.contains(r[3])?'n':''} ${r[3]}"}}

```

*edit: damn, the capitalization totally complicated everything here*

# Answer
> 0 votes
# C# 209 bytes

`string A(string b){var s=b.Split(new[]{"[?]"},0);return s.Skip(1).Aggregate(s[0],(x,y)=>x+(x==""||(x.Last()==' '&&".?!".Contains(x.Trim().Last()))?"A":"a")+("AEIOUaeiou".Contains(y.Trim().First())?"n":"")+y);}`

Formatted

```
string A(string b)
{
    var s = b.Split(new[] { "[?]" }, 0);
    return s.Skip(1).Aggregate(s[0], (x, y) => x + (x == "" || (x.Last() == ' ' && ".?!".Contains(x.Trim().Last())) ? "A" : "a") + ("AEIOUaeiou".Contains(y.Trim().First()) ? "n" : "") + y);
}

```

# Answer
> 0 votes
## Pip, ~~62~~ ~~55~~ ~~54~~ 50 bytes

Takes the string as a command-line argument.

```
aR-`([^.?!] )?\[\?]( [^aeiou])?`{[b"aA"@!b'nX!cc]}

```

Try it online!

Explanation:

```
a                                                   Cmdline argument
 R                                                  Replace...
  -`                           `                    The following regex (case-insensitive):
    ([^.?!] )?                                      Group 1: not end-of-sentence (nil if it doesn't match)
              \[\?]                                 [?]
                   ( [^aeiou])?                     Group 2: not vowel (nil if there is a vowel)
                                {                }  ... with this callback function (b = grp1, c = grp2):
                                 [              ]   List (concatenated when cast to string) of:
                                  b                 Group 1
                                   "aA"@!b          "a" if group 1 matched, else "A"
                                          'nX!c     "n" if group 2 didn't match, else ""
                                               c    Group 2

```

# Answer
> 0 votes
# Perl 6, 78 bytes

```
{S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{$0 xx?$0}{<a A>[?$0]}{'n'x?~$1} $1/}

```

## Explanation:

```
{
  S
    :ignorecase
    :global
  /
    ( # $0
    | ^             # beginning of line
    | <[.?!]> ' '   # or one of [.?!] followed by a space
    ) ?             # optionally ( $0 will be Nil if it doesn't match )

    '[?] '          # the thing to replace ( with trailing space )

    ( # $1
      <[aeiou]> ?   # optional vowel ( $1 will be '' if it doesn't match )
    )

  /{
    $0 xx ?$0      # list repeat $0 if $0
                   # ( so that it doesn't produce an error )
  }{
    < a A >[ ?$0 ] # 'A' if $0 exists, otherwise 'a'
  }{
    'n' x ?~$1     # 'n' if $1 isn't empty
                   # ｢~｣ turns the Match into a Str
                   # ｢?｣ turns that Str into a Bool
                   # ｢x｣ string repeat the left side by the amount of the right

  # a space and the vowel we may have borrowed
  } $1/
}

```

## Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &code = {S:i:g/(^|<[.?!]>' ')?'[?] '(<[aeiou]>?)/{<a A>[?$0]~('n'x?~$1)} $1/}

my @tests = (
  'Hello, this is [?] world!'
  => 'Hello, this is a world!',

  'How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.'
  => 'How about we build a big building. It will have an orange banana hanging out of a window.',

  '[?] giant en le sky.'
  => 'A giant en le sky.',

  '[?] yarn ball?'
  => 'A yarn ball?',

  '[?] hour ago I met [?] European.'
  => 'A hour ago I met an European.',

  "Hey sir [Richard], how 'bout [?] cat?"
  => "Hey sir [Richard], how 'bout a cat?",
);

plan +@tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  is code($input), $expected, $input.perl;
}

```

```
1..6
ok 1 - "Hello, this is a world!"
ok 2 - "How about we build a big building. It will have an orange banana hanging out of a window."
ok 3 - "A giant en le sky."
ok 4 - "A yarn ball?"
ok 5 - "A hour ago I met an European."
ok 6 - "Hey sir [Richard], how 'bout a cat?"

```

# Answer
> 0 votes
# Lua, 131 Bytes.

```
function(s)return s:gsub("%[%?%](%s*.)",function(a)return"a"..(a:find("[AEIOUaeiou]")and"n"or"")..a end):gsub("^.",string.upper)end

```

Although lua is a terrible Language for golfing, I feel I've done pretty well.

# Answer
> 0 votes
## Racket (with regex) 228 bytes

```
(define(r a b c)(regexp-replace* a b c))
(define(f s)
(set! s(r #rx"[a-zA-Z ]\\[\\?\\] (?=[aeiouAEIOU])"s" an "))
(set! s(r #rx"[a-zA-Z ]\\[\\?\\]"s" a"))
(set! s(r #rx"\\[\\?\\] (?=[aeiouAEIOU])"s"An "))
(r #rx"\\[\\?\\]"s"A"))

```

Testing:

```
(f "[?] giant en le [?] sky.")
(f "[?] yarn ball?")
(f "[?] apple?")
(f "[?] hour ago I met [?] European. ")
(f "How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.")
(f "Hello, this is [?] world!")

```

Output:

```
"A giant en le a sky."
"A yarn ball?"
"An apple?"
"A hour ago I met an European. "
"How about we build a big building. It will have an orange banana hanging out of a window."
"Hello, this is a world!"

```

# Answer
> 0 votes
# Python 3, ~~104~~ 103 bytes

-1 bytes, unescaped `]`

```
lambda s:r('(^|[.?!] )a',r'\1A',r('a( [aeiouAEIOU])',r'an\1',r('\[\?]','a',s)));from re import sub as r

```

Try it online!

Starts by replacing all occurences of `[?]` with `a`,
Then replaces all `a` followed by a vowel, with `an`.
Then replaces all `a` at the start of input or a sentence with `A`.

Assumes that `[?]` will never be touching another word, and that lower-case `a` should never begin a sentence.

# Answer
> 0 votes
# PowerShell, 124 bytes

inspired by Avi's answer for Java.

```
$args-replace(($b='(?<=^|[?.!] )')+($q='\[\?]')+($v='(?= [aeiou])')),'An'-replace"$q$v",'an'-replace"$b$q",'A'-replace$q,'a'

```

Try it online!

---
Tags: code-golf, string, natural-language
---