title: Find the closest swap

text:
# Question
Title: Find the closest swap
Take as input two strings \\$A\\$ and \\$B\\$. Output a string \\$C\\$ that is \\$A\\$ but with two characters swapped such that the Levenshtein distance \\$d(C,B)\\$ is as small as possible. You must swap two characters and you cannot swap a character with itself, although you may swap two identical characters in different positions.

This is the goal is to minimize the size of your source code as measured in bytes.

Instead of strings you may instead choose to handle lists of positive integers.

## Examples

Here are some examples of inputs and possible outputs along with the Levenshtein distance achieved.

| A | B | C | Distance |
| --- | --- | --- | --- |
| `abcd` | `adcb` | `adcb` | 0 |
| `ybgh` | `epmn` | `ygbh` | 4 |
| `slime` | `slime` | `silme` | 2 |
| `yeboc` | `yoqqa` | `yobec` | 3 |
| `unnua` | `muuna` | `uunna` | 2 |
| `oobis` | `oobi` | `oobis` | 1 |
| `yuace` | `yuac` | `yuaec` | 1 |

# Answer
> 3 votes
# 05AB1E, 17 bytes

```
\ā<.ÆεèyRǝ}Σ¹.L}н

```

Inputs in the order \\$B,A\\$.

Try it online or verify all test cases.

`ā<.Æεèy` could alternatively be `.ā.Æεø`` for the same byte-count:
Try it online or verify all test cases.

**Explanation:**

```
\           # Discard the first (implicit) input `B`
 ā          # Push a list in the range [1, length of second (implicit) input `A`]
  <         # Decrease it to range [0, length_A)
   .Æ       # Get all pairs without duplicates
     ε      # Map over each pair:
      è     #  Index them into the second (implicit) input `A`
       yR   #  Push the pair reversed
         ǝ  #  Insert them into the second (implicit) input `A`
     }Σ     # After the map: sort the strings by:
        .L  #  The Levenshtein distance with
       ¹    #  the first input `B`
      }н    # After the sort: pop and leave the first string
            # (which is output implicitly as result)

 .ā         # Enumerate the second (implicit) input,
            # pairing each character with its index
   .Æ       # Get all pairs without duplicates
     ε      # Map over each pair:
      ø     #  Zip/transpose; swapping rows/columns
       `    #  Pop and push the pair of characters and pair of indices separated to
            #  the stack
        R   #  Reverse the indices-pair

```

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

Expects `(a)(b)`, where **a** and **b** are arrays of characters. Returns another array of characters.

This really just tries all possibilities and computes the Levenshtein distance for each of them. It seems very likely that there's a smarter/shorter way.

```
a=>M=b=>a.map((x,i)=>a.map((y,j,[...s])=>j<=i|(s[i]=y,s[j]=x,n=b.length,g=m=>v=m*n?1+Math.min(g(m,--n),g(--m)-(s[m]==b[n++]),g(m)):m+n)(s.length)>M||(M=v,o=s)))&&o

```

Try it online!

# Answer
> 2 votes
# Vyxal, 15 bytes

```
ė2ḋƛ∩÷Ṙ¹∇Ȧ;‡⁰꘍∵

```

Try it Online!

`ė2ḋƛ∩÷` could be `ẏ2ḋƛ¹İ` for the same byte count.

```
ė2ḋƛ∩÷Ṙ¹∇Ȧ;‡⁰꘍∵
ė                # Enumerate, make a list [index, x] for each x in the first input.
 2ḋ              # Combinations without replacement of length 2; pairs.
   ƛ             # For each:
    ∩            #  Transpose
     ÷           #  Dump; push both items onto the stack.
      Ṙ          #  Reverse the top pair (the pair of two characters). Call this Y, and the other pair X.
       ¹         #  Push the first input
        ∇        #  Push it under the top two values of the stack, aka c,a,b.
         Ȧ       #  Assign; replace each of the indices in X with the corresponding value in Y.
          ;      # Close map.
           ‡  ∵  # Minimum by:
            ⁰꘍   #  Levenshtein distance with the second input.

```

# Answer
> 1 votes
# , ~~130~~ 97 bytes

```
\(A,B,x=combn(seq(a<-utf8ToInt(A)),2,\(i)intToUtf8(`[<-`(a,i,a[rev(i)]))))x[order(adist(x,B))[1]]
```

Attempt This Online!

Another brute-force solution.

# Answer
> 0 votes
# Python, 216 bytes

```
lambda a,b:(n:=len(a))and min(w(c:=[*a],k%n,k//n)or d(c,[*b])for k in range(n*n)if k%n<k//n)
d=lambda s,t:-~min(d(S:=s[1:],T:=t[1:])-(s[0]==t[0]),d(S,t),d(s,T))if s>""<t else len(s+t)
def w(a,i,j):a[i],a[j]=a[j],a[i]
```

Attempt This Online!

A very bloated answer which just iterates through all pairs of swaps. The Levenshtein distance is adapted from an answer to this question, but slightly shortened.

---
Tags: code-golf, edit-distance
---


# Question
Title: Check if number is a sum of consecutive numbers or not
Write a program that checks if a given positive integer can be represented as sum of two or more consecutive positive integers.

### Example:

43 can be represented as 21 + 22

10 = 1+2+3+4

but 4 cannot be represented in this way.

**Input spec:** positive integer (as argument or stdin)

**Output spec:** truthy or falsy

### Sample i/o

```
43 -> true
4 -> false

```

Shortest code wins.

# Answer
## JavaScript (31)

```
alert(!!((n=~~prompt())&(n-1)))

```

From my testing, I believe this gives correct solutions.

http://jsfiddle.net/3e9FZ/

**Edit**: (SPOILER ALERT!) Here is the justification for this answer:

1. All odd numbers greater than 1 can be trivially written as the sum of two consecutive numbers (ex 15 = 7+8, 23=11+12, etc.).
2. For even numbers having an odd factor where the odd factor is less than twice the even factor. For example, 4\*7, because 7 \< (2\*4 = 8). Simply add 7 numbers with 4 at the center, 1+2+3+4+5+6+7.
3. For even numbers having an odd factor where the odd factor is more than twice the even factor. For example, 4\*9, because 9 \> (2 * 4 = 8). Double the even factor, and halve the odd factor to get 8\*4.5. You will add the 8 numbers centered at 4.5, i.e., 1+2+3+4+5+6+7+8.
4. The only numbers left are the even numbers having no odd factor, i.e., the powers of two. The formula for the sum of a consecutive set of numbers is (avg * count). Now if the count is odd, then avg is a whole number, and (avg * count) has an odd factor. If count is even, then avg must be #.5, and thus avg * 2 is odd, and so avg * count has an odd factor. Therefore, any sum using the formula (avg * count) must have an odd factor, which powers of two do not, and therefore have no solution.
> 28 votes

# Answer
### Golfscript, 20 chars

```
~.(&!!"falsetrue"5/=

```

Someone had to.
> 3 votes

# Answer
# Ruby (23)

only 3 chars longer than golfscript :)

```
p 0<(n=$*[0].to_i)&n-1

```

output:

```
$ ruby gc2958.rb 4
false
$ ruby gc2958.rb 43
true
$ wc gc2958.rb
  1       2      23 gc2958.rb

```
> 3 votes

# Answer
## Haskell, 74

Felt like doing the brute force way.

```
import List
main=print.f=<<readLn
f n=elem n$map sum$tails=<<inits[1..n-1]

```
> 2 votes

# Answer
## JavaScript (81)

```
n=prompt(r=i=1)|0;while(r&++i*i/2<n)if(i%2&!(n%i)|!(i%2|(n+i/2)%i))r=!r;alert(!r)

```

I'm cheating with `&` and `|` \- even though they are technically bit-wise operations, they do the job quite nicely because the result is a 1/0 which are valid conditionals!

http://jsfiddle.net/HCqK2/4/
> 1 votes

# Answer
## C, 67

As mellamokb suggested all numbers, except powers of two, can be written as sum of positive consecutive numbers:

```
main(int i,char**a){
printf((i=atoi(a[1]))&i-1?"true\n":"false\n");
}

```
> 1 votes

# Answer
## Python 3 REPL, 34

```
bool(int(bin(2*int(input()))[3:]))

```

I took an alternative approach to the solution, but can't seem to squeeze anything else out of it. This code takes the input, multiplies it by two (this fixes the input case of `1` which breaks otherwise), converts it to binary, strips out the first 3 characters (`0b1`), converts the remainder to an integer (which is 0 iff the input was a power of two), and then converts that to a boolean.

As mentioned above, you can remove the `2*` to get a 32-char solution that fails on an input of `1` but is otherwise perfect.
> 1 votes

# Answer
## C

return 1 or 0:

```
int i(int j){return((j%2)?!(j==1):i(j/2));}

```
> 1 votes

# Answer
# Python 2 REPL, 24 chars

Shortest python atm, borrowing `bin()` from @Fraxtil :)

```
bin(input()).count('1')>1

```
> 1 votes

# Answer
# Python 2 REPL, 19 17 16

```
x=input()
x>x&-x

```
> 1 votes

# Answer
# Mathematica, 23 bytes

```
N[2~Log~#]~MatchQ~_Real

```

For once it's actually useful
> 1 votes

# Answer
# TI-Basic, 6 bytes

```
fPart(logBASE(Ans,2

```

Operating system ≥2.53 required due to `logBASE(`. Without logBASE, there are alternatives:

```
7 bytes: fPart(ln(Ans)/ln(2
7 bytes: fPart(log(Ans)/log(2

```
> 1 votes

# Answer
# Befunge-93, 28 bytes

Try it Online!

```
&v@.1<@.0<
:</2_^#!_^#-1\%2:

```

Instead of checking if the given integer is an element in this sequence, it's much easier to check if it isn't in the complimentary sequence (powers of 2 with 0 instead of 1). This functions very similarly to mellamokb's answer in that sense.

Note that the linked sequences are not exact representations of all truthy/falsey results of each integer, because the sequence uses non-negative integers instead of strictly positive. Thus, 1 *is* in the linked sequence, even though for this specific problem it should be in its compliment.
> 1 votes

# Answer
# Wren, ~~18~~ 17 bytes

Umm, it's shorter than GolfScript...

```
Fn.new{|n|n&-n<n}

```

Try it online!
> 1 votes

# Answer
# Vyxal, 2 bytes

```
‹⋏

```

Try it Online!

Just a port of Jelly and JS. Bitwise AND with n-1. Returns positive integer for true, 0 for false.

# Prolog (SWI), 13 bytes

```
\N:-0<N-1/\N.

```

Try it online!

-4 thanks to Jo King
> 1 votes

# Answer
# Dyalog APL, 7 bytes

```
0≠1|2∘⍟

```

Checks if a number is not a power of 2.

Attempt This Online!

```
    2∘⍟  log base 2 of
  1|     mod 1
0≠       is not zero

```

My 14-byte brute-force attempt before learning that the question is equivalent to asking if a number is not a power of 2:

```
⊢∊∘∊1↓+/¨∘⊂⍥⍳⍨

```

Using 3 as an example:

```
             ⍨  put the argument on both sides: 3 ... 3
           ⍥⍳   integers from 1 to n on both sides: 1 2 3 ... 1 2 3
      +/¨∘⊂     sums of length-1, 2, and 3 windows in 1 2 3: (1 2 3)(3 5)(6)
    1↓          drop the length-1 sums
   ∊            flatten into a list
⊢∊∘             is the argument in this list?

```
> 1 votes

# Answer
# Python 2 REPL, 33 chars

It seems that there's a way shorter way to do this though:

```
s=input()
n=2
while n<s:n*=2
n!=s

```
> 0 votes

# Answer
# Perl, 51 bytes

```
print(((log($ARGV[0])/log(2))=~ /\./ )?true:false);

```

Example:

```
$perl Soc.pl 45

true

$perl Soc.pl 8

false

```
> 0 votes

# Answer
# J, 12

It doesn't follow the spec 'true'/'false'. Rather I stick with 1/0. It checks if log base 2 of a number has a decimal mark.

`+/=&'.'":2^.`

```
   +/=&'.'":2^.1
0
   +/=&'.'":2^.4
0
   +/=&'.'":2^.43
1

```
> 0 votes

# Answer
# Jelly, 2 bytes

```
&’

```

Try it online!

Just a translation of the accepted JavaScript solution.
> 0 votes

# Answer
# Vyxal, 10 bytes

```
Ṅ's¯1J≈;Ṫḃ

```

Try it Online!

A non-bitwise answer that doesn't port Javascript.

## Explained

```
Ṅ's¯1J≈;Ṫḃ
Ṅ           # Integer partitions of the input
 '     ;    # Filtered by:
  s¯        #  Are the deltas of the sorted partition
    1J≈     #  All 1?
        Ṫḃ  # Remove the tail of the list because that's just the input as a single item and then return whether there's any items in the list.

```
> 0 votes

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


# Question
Title: "Hello world" that creates a different "Hello world" program
Create a program, that outputs a hello world string ("Hello world", "Hello, World" etc.), and source code. Output is written to stdout or equivalent. Hello world string is embedded in the source code.

For example, the output for might be

```
(some source code here)hello world(some source code here)

```

**When the output is compiled or interpreted again, it should create a similar output, but the hello world string must have a different punctuation or capitalization.** For example, the previous example could create the following output

```
(some source code here)hello, wORld(some source code here)

```

Each "(some source code here)" in these examples can change after each execution, or it can be the same.

**Your output must contain a valid hello world string exactly once.** It may contain any amount of invalid hello world strings. Source code may contain any amount of comments, and the hello world string may be embedded in comments. The first program can have either zero or one valid hello world strings, but no more.

Following punctuation is valid:

```
hello, world
hello world
helloworld

```

Any capitalization is acceptable. For example, these are valid hello world strings:

```
Hello, world
hellO WORld
HELLoworlD

```

These strings are not valid:

```
Hello     world
Hello(newline)world
Hello,world
Hello, Steve

```

Your program fails as soon as one of the following conditions are met:

* It outputs a hello world string that has been output during some earlier execution,
* output is no longer valid source code in the same language, or
* output does not contain exactly one valid hello world string.

**Your program is not valid for this contest unless at least two first executions are successful.** This means that the third output is allowed to be invalid. Output of your program may not be random. First execution should always create the same second output, second execution should always create the same third output, etc.

Score is calculated as amount of bytes in the source code of the initial program. Lowest score wins.

Following bonuses do apply (up to -60%):

* -5% * (N - 2), where N is the index of the execution after which your program produces invalid output. This bonus caps at -50%. If your program succeeds 12 times or more, you get the max bonus.
* -10%, if your outputs (including first source code) include all three valid punctuation alternatives.

Your submission should include the first source code, and it should also contain the outputs of the successful executions. If your program succeeds more than 12 times, add output for 12 executions.

## Example

Next line is the first source code. When we execute it, it is the first execution.

```
hello world(some source code here)

```

Next line is the output from the first source code code. It is the first output.

```
hello, world(some source code here)

```

Next line is the output from the second execution. It is the second output.

```
helloworld(some source code here)

```

When we executed the first output, this program became eligible for the -10% bonus. That means we have two outputs, and one original code, which all have different punctuation. Moreover, because the second output was valid, this program is eligible for this contest.

Next line is the output from the third execution. It is the third output.

```
Helloworld(some source code here)

```

Next line is the output from the fourth execution. It is the fourth output.

```
hellworld(some source code here)

```

This output was invalid. Index of the last valid execution was 4. This program is eligible for -5% * (4 - 2) bonus and -10% bonus from the punctuation. This makes total of -20%. The length of the first source code ("hello world(some source code here)") was 34 bytes, so the final score is 27.2.

# Answer
> 9 votes
# Pyth, 17 bytes

A different Pyth solution:

```
"r\"helloworld\"1

```

Output:

```
r"helloworld"1

```

Second output:

```
HELLOWORLD

```

# Answer
> 11 votes
# Mathematica, ~~214~~ 194 - 50% = 97 bytes

```
(a = "helloworld"; b = Apply[StringJoin, Tuples[Thread[Characters[{ToLowerCase[a], ToUpperCase[a]}]]], {1}]; StringReplacePart[ToString[#0, InputForm], b[[FirstPosition[b, a] + 1]], {7, 16}]) &

```

I decided to optimize for string count here. This runs for 1024 programs without stopping, going through every combination of uppercase and lowercase letters. The execution can be seen here.

# Answer
> 7 votes
# Vitsy, 33 - 33\*.05\*(11-2) = 18.15 Bytes

Heh! Beat that! You probably will. :c

## First output:

```
'0DV\{25^-V\}}1+{rd3*Z;helloworld
'                                 Start capturing as a string
 0DV                              Push 0 to the stack and set it as the final variable.
    \                             Repeat the next item this many times. (1, 2, 3... on outputs.)
     {                            Rotate the stack leftwards.
      25^                         Push 32 to the stack.
         -                        Subtract the top item by it - this will make lowercase uppercase.
          V\                      Do the next item final variable times.
            }                     Rotate the stack rightwards.
             }                    And again...
              1+                  Add one. This makes the 0 in this code a 1, then 2...
                r                 Reverse the stack.
                 d3*              Get the character '
                    Z             Output all items in the stack.
                     ;            End execution.
                      helloworld  String to manipulate.

```

## Second output:

```
'1DV\{25^-V\}}1+{rd3*Z;helloworlD
```

## Third output:

```
'2DV\{25^-V\}}1+{rd3*Z;helloworLD
```

## Fourth output:

```
'3DV\{25^-V\}}1+{rd3*Z;hellowoRLD
```

## Fifth output:

```
'4DV\{25^-V\}}1+{rd3*Z;hellowORLD
```

## Sixth output:

```
'5DV\{25^-V\}}1+{rd3*Z;helloWORLD
```

## Seventh output:

```
'6DV\{25^-V\}}1+{rd3*Z;hellOWORLD
```

## Eighth output:

```
'7DV\{25^-V\}}1+{rd3*Z;helLOWORLD
```

## Ninth output:

```
'8DV\{25^-V\}}1+{rd3*Z;heLLOWORLD
```

## Tenth output:

```
'9DV\{25^-V\}}1+{rd3*Z;hELLOWORLD
```

## Eleventh output:

```
':DV\{25^-V\}}1+{rd3*Z;HELLOWORLD
```

This is the last output, as it will cause an error.

# Answer
> 5 votes
## CJam, N = ~~3~~ 4, 28 bytes - 10 % - 10 % = 22.4

```
{`_E=-"_~Hello!, World"2<}_~

```

this starts the following chain:

```
{`_E=-"_~Hello, World"2<}_~
{`_E=-"_~Hello World"2<}_~
{`_E=-"_~HelloWorld"2<}_~
{`_E=-"_~Helloorld"2<}_~

```

where the last one no longer contains a valid "Hello, World".

Test it here.

### Explanation

```
{`     e# Quine framework. Leaves a string representation of the block on the stack.
  _E=  e# Make a copy and get the 14th element, which is the character of the first 'o'.
  -    e# Remove that character from the string.
  "_~Hello!, World" e# Push this string, so the "Hello, World!" is part of the code.
  2<   e# Truncate to just "_~" to get the output right.
}_~

```

Note that the initial program does not contain a valid "Hello, World", but that allows us to go one iteration further.

# Answer
> 5 votes
# CJam ~~69~~ 60 - 50% = 30

I'm still beginner, Please tell me how to golf in CJam.

```
{`_40>\40<_38>~)`2Te[\25<"helloworld"00YbATe[.{{el}{eu}?}`+]W%"_~"}_~

```

It's tedious to print each iteration, as it will valid for 99 iterations.

It works by enumerate the capitalization of hello word. The tedium is to splitting strings into parts as both "hello world" and the counter have to be updated.

Explanation

```
{`_40>\40<_38>~)`2Te[\25<"helloworld"00YbATe[.{{el}{eu}?}`+]W%"_~"}_~
{`                                                                      e# standard quine framework. Thanks for Dennis.
  _40>                                                                  e# get the Yb11..
      \40<                                                              e# get those that not included in top
          _38>~)`2Te[                                                   e# get the accumulator and increment it
                     \25<                                               e# get those before "hello world"
                         "helloworld"                                   e# the Hello World
                                     00                                 e# accumulator
                                        YbATe[                          e# convert to binary and align right.
                                              .{{el}{eu}?}              e# Uppercase if the corresponding bit is 0
                                                          `             e# add quote
                                                           +]W%         e# reorder stack
"_~"}_~

```

NOTE: I don't read the Mathematica answer, sorry, I think it was original

With reordering, and different capitalization, I lose 9 bytes.

```
{`_6<\"helloworld"01YbW%.{{eu}{el}?}`\I>_2<~)`2Te[\2>"_~"}_~
{`                                                   "_~"}_~ e# Standard quine framework
  _6<\                                                       e# Get "{~_6<\"
      "helloworld"                                            e# The helloworld
                  01                                          e# The accumulator
                    Yb                                        e# Convert to base 2
                      W%                                      e# Reverse the binary
                        .{{eu}{el}?}                          e# Convert to uppercase while the corresponding bit is 1.
                                    `                         e# Add quote
                                     _2<                      e# Get accumulator
                                        ~)`2Te[               e# Increment the accumulator
                                               \2>            e# get the rest

```

## CJam 73 - 60% = 29.2

This time also enumerate the punctuation.

```
{`:Z6<"HELLOWORLD"0:AYbW%.{{eu}{el}?}`", ":B-_6<BA3%>@6>A)ZW%52<W%"_~"}_~
{`:Z                                                              "_~"}_~ e# Standard Quine Framework
    6<                                                                    e# take the first 6 character
      "HELLOWORLD"                                                        e# Hello, world
                  0:A                                                     e# Accumulator
                     YbW%.{{eu}{el}?}`                                    e# See above
                                      ", ":B                              e# Punctuation
                                            -                             e# Delete punctuation
                                             _6<                          e# "hello
                                                BA3%>                     e# punctuation
                                                     @6>                  e# world"
                                                        A)                e# incremented accumulator
                                                          ZW%52<W%        e# Remaining part

```

# Answer
> 4 votes
# GolfScript, 35 bytes − 50% = 17.5

```
0"HelloWorld"{@@{^.32&\}%`@".~"}.~

```

I decided to go for overkill on the number of executions before a repeat. This program, with its output fed back into the GolfScript interpreter, will produce **890** distinct Hello World strings before the first repeat. As a brief sample, here are the first 15 iterations:

```
0"HelloWorld"{@@{^.32&\}%`@".~"}.~
0"HeLlOWoRlD"{@@{^.32&\}%`@".~"}.~
0"HelLOWorLD"{@@{^.32&\}%`@".~"}.~
0"HeLLOWoRLD"{@@{^.32&\}%`@".~"}.~
0"HellowORLD"{@@{^.32&\}%`@".~"}.~
32"HeLlOworld"{@@{^.32&\}%`@".~"}.~
0"hELloWoRlD"{@@{^.32&\}%`@".~"}.~
32"helLowORld"{@@{^.32&\}%`@".~"}.~
0"HeLLoWORlD"{@@{^.32&\}%`@".~"}.~
32"HellOWORld"{@@{^.32&\}%`@".~"}.~
0"hElLOWORlD"{@@{^.32&\}%`@".~"}.~
32"heLLOWORld"{@@{^.32&\}%`@".~"}.~
32"HelloworLd"{@@{^.32&\}%`@".~"}.~
32"hElLoWoRLd"{@@{^.32&\}%`@".~"}.~
0"HEllOWorlD"{@@{^.32&\}%`@".~"}.~

```

The way it works is by iterating through the string, flipping the capitalization of each letter (by XORing its ASCII code with 32) if the previous letter (after possibly having its case flipped) is lowercase. The first letter will have its case flipped if the number at the beginning program is 32 rather than 0 — and the number output for the next iteration will be 32 whenever the last letter of the string is lowercase, thus causing any changes at the end of the string to propagate back to the beginning on the next iteration.

(This particular feedback process was obtained in a totally *ad hoc* manner. I originally wanted to just run a simple binary counter using uppercase and lowercase as the bits, but that took too many bytes to implement, so I started tweaking it to find something shorter that would still yield a fairly high cycle length. Since the theoretical maximum, using case-flipping only, is 210 = 1024, getting an 890-iteration cycle is pretty nice.)

Alas, the bonus for additional iterations is capped at −50%; without the cap, this program would have a whopping −4440% bonus. ;-)

# Answer
> 3 votes
# Pyth, 18 bytes

```
"-\"hello world\"d

```

Which returns:

```
-"hello world"d

```

Which in turn prints:

```
helloworld

```

I had a solution that did all three spellings, but it's longer even with the bonus.

# Answer
> 3 votes
# Simplex, 21 bytes.

This is what Simplex was *born* for. I can definitely go farther with this.

(I keep on hitting Ctrl+Enter, sorry! I blame it on the tablet keyboard)

## Attempt 3, v.0.8+, 31 -5% = 29.45 bytes (UTF-8 methinks)

That emote in the middle expresses myself. Sort of. Why did I do this, again? .\_.

```
"\"f[helloworld]-:D-``\"§R'Hg"g
"                            "  ~~ write that string
 \"f[helloworld]-:D-``\"§R'Hg   ~~ escaped quotes
                              g ~~ output that string

```

2nd Output:

```
"f[helloworld]-:D-``"§R'Hg
"                   "      ~~ write that string
 f[helloworld]-:D-``       ~~ string to be written
                     §R    ~~ go to second cell
                       'H  ~~ set it to H charcode
                         g ~~ output that string

```

3rd output:

```
f[Helloworld]-:D-``
f                   ~~ turns off safety mode (heck yeah error suppression!)
 [          ]-      ~~ write inside to outer program
  H                 ~~ sort strip
   e                ~~ write e = 2.718281828459045... to the strip
    ll              ~~ writes 1 twice to the cell
      o             ~~ outputs 1
       wo           ~~ apply o backwards through the strip (outputs 1)
         r          ~~ error! tries to access register for modification. nope!
          l         ~~ write 1 to to the current cell
           d        ~~ reverse the strip (NOP)
              :     ~~ removes last char of outer program
               D    ~~ double the current byte (2)
                -   ~~ writes previous char to outer program
                 `` ~~ suppress outer program evaluation and instead output it

```

Final output:

```
HelloworlD

```

## Attempt 2, v.0.8+, 21 bytes (UTF-8, I think)

```
"\"helloworld\"§'Hg"g
"                  "  ~~ write that string
 \"helloworld\"§'Hg   ~~ escaped quotes
                    g ~~ output that string

```

Output:

```
"helloworld"§'Hg
"          "     ~~ write that string
 helloworld      ~~ string to be written
            §    ~~ go to first cell
             'H  ~~ set it to H charcode
               g ~~ output that string

```

Final output:

```
helloworld

```

## Attempt 1, v.0.7+ ~~28~~ 26 bytes

I'm not sure if this qualifies for the first bonus…

```
"BhelloworldB"t[s32S;]'gs;
"            "             ~~ write that string
 BhelloworldB              ~~ the string
              t[     ]     ~~ apply the inner from left to right
                s          ~~ output as character
                 32S       ~~ subtract 32 ("capitalize")
                    ;      ~~ add the current byte's char to the outer program
                      'g;s ~~ add g to the outer program

```

First output:

```
"HELLOWORLD"g

```

The outer program is evaluated at the end of execution (it does it for y; this is what the outer program looks like:

```
"HELLOWORLD"g
"          "  ~~ write that string
            g ~~ output that string as string characters

```

Final output:

```
HELLOWORLD

```

# Answer
> 3 votes
# Ruby, 81 - 50% = 40.5

Original code:

```
_='_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)';puts _%[_,'HELLOWORL'+?D]

```

Successive outputs:

```
_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"HELLOWORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hELLOWORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"heLLOWORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helLOWORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hellOWORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloWORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hellowORLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"hellowoRLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloworLD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloworlD"]).sub(/[[:upper:]]/,&:swapcase)

_="_=%p;puts (_%%[_,%p]).sub(/[[:upper:]]/,&:swapcase)";puts (_%[_,"helloworld"]).sub(/[[:upper:]]/,&:swapcase)

```

I think this counts as the full 50%? Might be off by one. Also, there's probably a better-scoring non-bonus solution in Ruby.

The original code doesn't contain "helloworld", but it builds a quine that replaces the first capital letter in its source code with the lowercase version. So each successive run of the quine outputs one fewer capitalized letter.

The trick here is to use a format string to interpolate both the string itself, for quining, and the Hello World string, so that it only appears once.

# Answer
> 2 votes
# Vyxal, score 8

```
`kh#`kH+

```

Try it Online!

Outputs:

```
kh#Hello, World!

```

Try it Online!

Outputs:

```
Hello World

```

## Explained

```
`kh#`

```

Push the string `"kh#"` onto the stack (which, when literally executed, is the constant `"Hello World"` and a comment)

```
kH+

```

Push the string `"Hello, World!"` onto the stack and concatenate the two strings together. Implicitly print the string.

# Answer
> 1 votes
# PHP, 297 - 40% = 178.2 bytes

Not really competitive but it was fun to write

```
<?ob_start(function($s){$s=substr(str_replace(0,0+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[0]=$h[0]^' ';return "<"."?".$s."?".">".$s.$h;});?>ob_start(function($s){$s=substr(str_replace(0,0+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[0]=$h[0]^' ';return "<"."?".$s."?".">".$s.$h;});

```

It's a variation of this quine:

```
<?
ob_start(function($b){ return "<"."?\n$b?".">\n$b"; });?>
ob_start(function($b){ return "<"."?\n$b?".">\n$b"; });

```

but it also adds "helloworld" to the output and replaces `0` with `0+1` (in the next iteration `1` with `1+1` and so on). Using `substr` any existing "helloworld" output gets removed before the new "helloworld" gets added.

To get different output, one letter of "helloworld" gets capitalized (determined by the incrementing number). This is the relevant code:

```
$h=hello.world;$h[0]=$h[0]^' '

```

A challenge was to not use any numbers except here and for the number replacement

```
str_replace(0,0+(int)true,$s)

```

There you already see that `+1` is realized as `+(int)true`.

For the substring arguments I needed `0, 146`:

```
!i, ord(I)+ord(I)

```

The non-empty string "i" gets coerced to `true` and negated. `false` is a valid integer argument and is treated like `0`. `ord(I)` is the ASCII value of "I": 73

### Output (1st iteration):

```
<?ob_start(function($s){$s=substr(str_replace(1,1+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[1]=$h[1]^' ';return "<"."?".$s."?".">".$s.$h;});?>ob_start(function($s){$s=substr(str_replace(1,1+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[1]=$h[1]^' ';return "<"."?".$s."?".">".$s.$h;});Helloworld

```

### Output (2nd iteration):

```
<?ob_start(function($s){$s=substr(str_replace(2,2+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[2]=$h[2]^' ';return "<"."?".$s."?".">".$s.$h;});?>ob_start(function($s){$s=substr(str_replace(2,2+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[2]=$h[2]^' ';return "<"."?".$s."?".">".$s.$h;});hElloworld

```

### Output (10th iteration):

This is the last valid output but not a valid program anymore

```
<?ob_start(function($s){$s=substr(str_replace(10,10+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[10]=$h[10]^' ';return "<"."?".$s."?".">".$s.$h?>ob_start(function($s){$s=substr(str_replace(10,10+(int)true,$s),!i,ord(I)+ord(I));$h=hello.world;$h[10]=$h[10]^' ';return "<"."?".$s."?".">".$s.$hhelloworlD

```

> Scroll far to the right to find the "Hello world" strings!

# Answer
> 1 votes
# Pip, 48 - 50% = 24

```
V Y"`V Y`.RPyRh:ST`helloworld`UCh@<0.h@>0R0o+0"

```

which evolves as follows:

```
V Y"`V Y`.RPyRh:ST`helloworld`UCh@<1.h@>1R1o+1"
V Y"`V Y`.RPyRh:ST`Helloworld`UCh@<2.h@>2R2o+2"
V Y"`V Y`.RPyRh:ST`HElloworld`UCh@<3.h@>3R3o+3"
V Y"`V Y`.RPyRh:ST`HELloworld`UCh@<4.h@>4R4o+4"
V Y"`V Y`.RPyRh:ST`HELLoworld`UCh@<5.h@>5R5o+5"
V Y"`V Y`.RPyRh:ST`HELLOworld`UCh@<6.h@>6R6o+6"
V Y"`V Y`.RPyRh:ST`HELLOWorld`UCh@<7.h@>7R7o+7"
V Y"`V Y`.RPyRh:ST`HELLOWOrld`UCh@<8.h@>8R8o+8"
V Y"`V Y`.RPyRh:ST`HELLOWORld`UCh@<9.h@>9R9o+9"
V Y"`V Y`.RPyRh:ST`HELLOWORLd`UCh@<10.h@>10R10o+10"
V Y"`V Y`.RPyRh:ST`HELLOWORLD`UCh@<11.h@>11R11o+11"
V Y"`V Y`.RPyRh:ST`HELLOWORLD`UCh@<12.h@>12R12o+12"

```

with the last output being invalid because the `HELLOWORLD` hasn't changed. (Correct me if I haven't done the bonus right.)

Thanks to this question, I just discovered a new quine technique! The base quine is `V Y"`V Y`.RPy"`:

```
  Y"         "  Yank that string into the variable y
V               Evaluate it as a Pip expression:
          RPy   y wrapped in double quotes (repr)
    `V Y`.      Prepend that regex pattern
                When this is evaluated, it returns a pattern object, which is
                auto-printed--conveniently, without the `` delimiters

```

Our extra code modifies the string in `y`, before repr-ing it, as follows:

* Replace the current helloworld with one in which the leftmost `0` characters are uppercased;
* Replace all occurrences of `0` with `o+0` (where `o` is a builtin variable that equals 1).

The next time around the number in the code is `1` instead of `0`, and so forth.

# Answer
> 1 votes
# Javascript, 52 bytes

```
function(){return '("hello world").replace(" ","")'}

```

## Test

`=>`

`<='("hello world").replace(" ","")'`

`=> eval('("hello world").replace(" ","")')`

`<= 'helloworld'`

# Answer
> 1 votes
## ///, 23 bytes

```
/,//\/ \/\/hello, world

```

Try it online!

First output:

```
/ //hello world

```

Second output:

```
helloworld

```

# Answer
> 1 votes
# BBC BASIC, 56 bytes

I had a crack at this before I realized how late to the game I am. For what it's worth, here's my version and my first attempt at StackExchange code golf.

Here, *V.* echoes out the characters given by the ASCII codes in the following comma separated list and *P.* is shorthand for print. I make use of the backspace character to overwrite the existing 'helloworld' string.

**Input code:**

```
V.80,46,34:P."helloworld";:V.8,68,34,59:P.":V.8,8,76,68"

```

**First Output:**

```
P."helloworlD";:V.8,8,76,68

```

**Second Output:**

```
helloworLD

```

It can be tested online at https://bbc.godbolt.org/

# Answer
> 1 votes
# Keg, ~~32~~ ~~28~~ ~~23~~ ~~22~~ 21 bytes

```
CKQNVNKKDG`(⑨,)`‘H%c¡

```

Try it online!

This prints:

```
CKQNVNKKDG(⑨,)HelloWorld

```

Which prints:

```
HELLOWORLD

```

# Answer
> 1 votes
# 05AB1E, score ~~15~~ 9

*-9 bytes thanks to ovs.*

```
’"Ÿ™ ‚ï"á

```

Try it online!

Output:

```
"hello world"á

```

Second output:

```
helloworld

```

---

```
’...  # trimmed program
’...  # push "\"hello world\"á"
      # implicit output

"..."á  # trimmed program
     á  # push only letters in...
"..."   # literal
        # implicit output

```

# Answer
> 1 votes
# Vyxal `D`, 20.5 bytes

```
`⌐÷:aBk⁋+›bḢ¨£ßN∑kTtp+q‛:Ė+,helloworld`:Ė

```

Try it Online!

This outputs all 1024 different capitalisations of `helloworld`.

```

`                     q‛:Ė+           `:Ė # Quine structure
                           ,              # Eventually print the result
                            helloworld    # Ignored
 ⌐÷                                       # Push the bits before and after the comma
   :a                                     # Check capitalisation
     Bk⁋+›bḢ                              # Binary increment
            ¨£ßN∑                         # Capitalise
                 kTtp                     # Prepend a comma
                     +                    # Append to the rest of the code

```

---
Tags: code-golf, string, quine, hello-world
---


# Question
Title: Find the smallest triangle encompassing the specified polygon
Input: An integer N which represents the polygon's vertices and a list of their x and y coordinates.

Expected output: The smallest difference possible between the area of the(not necessarily convex) polygon and the triangle containing it. The triangle also has to share at least 2 vertices with the polygon. If there is no such triangle print -1.

Example:

```
4
0,0
2,0
1,1
0,2

```

Output: 0, because the polygon matches up perfectly with the triangle.

This is so answers will be scored in bytes with less bytes being better.

# Answer
> 6 votes
# Python 3.9.12: <sup>~~588~~ ~~585~~ ~~583~~ ~~580~~ ~~578~~</sup> 572 bytes

3 bytes saved thanks to Jiří, and 2 bytes saved thanks to clarification from att!

```
from numpy import*
from itertools import*
def J(V):
 c,a,X,I=combinations,array,cross,vstack;V=[*map(a,V)];s=lambda A,B,P:sign(X(B-A,P-A));Q=lambda v,w,G:all((_:=[x for p in G if any(p-v)*any(p-w)*(x:=s(v,w,p))])==_[0]);F=lambda Z:abs(sum([linalg.det(I((Z[i],Z[i+1])))for i in range(len(Z)-1)]))/2;W=[a([_[0]/_[2],_[1]/_[2]])for k,l in c([a([v,w])for v,w in c(V,2)if Q(v,w,V)],2)if(_:=X(X((h:=hstack((I((k,l)),ones((4,1)))))[0],h[1]),X(h[2],h[3])))[2]!=0];return min([F(e)-F(V)for v,w in c(V,2)for k in W if s(*(e:=[v,w,k]))and Q(w,v,D:=V+e)*Q(k,w,D)*Q(v,k,D)],default=-1)

```

ATO link

The input for the number of vertices is ignored since it is not used or needed.

The function J takes in the input vertices, V, as a list of tuples/lists. An example function call would be `J([(0,0),(1,3),(1,1),(2,0)])`.

The code assumes that a polygon is defined as most people would define a polygon (made of vertices connected by non-intersecting edges)

## Code explained by line/function

```
from numpy import*
from itertools import*
def J(V):
 c,a,X,I=combinations,array,cross,vstack;

```

Normal byte-saving code. Nothing fancy.

```
V=[*map(a,V)];

```

Converting the list of tuples into a list of numpy arrays. This can't be left as a map object because of some stuff that is done later.

```
s=lambda A,B,P:sign(X(B-A,P-A));

```

s takes in three points A,B,P and returns which side of the line connecting AB is point P using the cross product. The two vectors have two elements so numpy treats them as vectors of the form \[x,y,0\] and returns only the z component. If P is on the "right" of the line AB, s = -1. On the left, s = +1. If P is on the line AB then s = 0.

```
Q=lambda v,w,G:all((_:=[x for p in G if any(p-v)*any(p-w)*(x:=s(v,w,p))])==_[0]);

```

Q takes in two points, v and w, and a set of vertices G. Essentially, this is checking if the line vw places all points in G into the same half of the plane (or onto the line). If that is the case, then it returns True. Otherwise, False. `any(p-v)` is used instead of the more traditional `p==v` because numpy arrays can't be directly compared in that way due to "ambiguity".

```
F=lambda Z:abs(sum([linalg.det(I((Z[i],Z[i+1])))for i in range(len(Z)-1)]))/2;

```

F takes in Z, a list of vertices of a polygon, and returns the area of that polygon using the shoelace formula. This doesn't work with polygons whose edges intersect, but those polygons have ill-defined areas anyway.

```
W=list([a([_[0]/_[2],_[1]/_[2]])for k,l in c([a([v,w])for v,w in c(V,2)if Q(v,w,V)],2)if(_:=X(X((h:=hstack((I((k,l)),ones((4,1)))))[0],h[1]),X(h[2],h[3])))[2]!=0]));

```

Breaking this down:

`[a([v,w])for v,w in c(V,2)if Q(v,w,V)]` returns a list of 2x2 numpy array the represents the line formed by the points vw, where every combination of two points in the input polygon V gets a chance at being vw, if the line vw places all points in V onto one side of the plane (or on the line). The reason for this is to get a set of lines that forms the boundary of the polygon. Think of it as taking all the vertices that would make the input polygon convex, connecting them with edges, then extending those edges into lines.

The rest of this line is devoted to determining where those lines intersect (if they were extended infinitely far). This is done using homogenous coordinates. Another example can be found in this stackoverflow thread, whose code this is based on.

The reason for this is to determine exactly where could the vertices of the all of the triangles that could envelop the input polygon lie.

```
min([F(e)-F(V)for v,w in c(V,2)for k in W if s(*(e:=[v,w,k]))and Q(w,v,D:=V+e)*Q(k,w,D)*Q(v,k,D)],default=-1)

```

This one is very simple. For every combination of points v,w in V and then every point in W (the line intersections), first check to see if all three points are collinear using the function `s`. If they're not, then we check to see if all points in V are inside of the triangle formed by vwk. This is done by checking if all of the points in V, also including the three points v,w,k, are all on the same side of the plane when intersected by a line made of two of the points. Since it's a triangle, if all the "third points" are on the same side of the plane as the two points forming a line (for all three combinations of v,w,k), then all points must be inside the triangle or on the edge of it.

Lastly, we take get the area of each triangle that satisfies our conditions and subtract off the area of the input polygon. Then, the minimum area is returned. If there is no minimum area to return (because no triangle exists that satisfies all conditions), then -1 is returned instead.

---

This is my first code golf answer so please let me know if I missed anything major with the question or if there is somewhere bytes can be saved!

---
Tags: code-golf, geometry
---


title: Partition and Restructure

text:
# Question
Title: Partition and Restructure
Given two contiguous shapes of the same area, determine the optimal way to divide the first shape into a minimum number of contiguous segments such that they can be rearranged to form the second shape. In other words, find the minimum number of segments required that can form both of the shapes.

"Contiguous" means that every square in the shape can be reached from any other square by walking across edges. Shapes and segments are allowed to have holes.

"Rearrange" means you move the segments around; you can translate, rotate, and reflect them.

The shapes are contained on a grid; in other words, each shape consists of a collection of unit squares joined by their corners/edges.

# Input Specifications

The input will be provided in some reasonable format - list of points, array of strings representing each grid, etc. You can also take the sizes of the grid if requested. The grids will have the same dimensions and the two shapes are guaranteed to have the same area, and the area will be positive.

# Output Specifications

The output should just be a single positive integer. Note that there will always be a positive answer because in the worst case scenario, you just divide the shapes into `N` unit squares.

# Examples

The examples are presented as a grid with `.` representing a blank and `#` representing part of the shape.

## Case 1

**Input**

```
.....
.###.
.#.#.
.###.
.....

###..
..#..
..#..
..###
.....

```

**Output**

```
2

```

**Explanation**

You can divide it into two L-shaped blocks of 4:

```
#
###

```

## Case 2

**Input**

```
#...
##..
.#..
.##.

.##.
####
....
....

```

**Output**

```
2

```

**Explanation**

You can split the shapes like so:

```
A...
AA..
.A.
.BB.

.AA.
BBAA
....
....

```

You could also do:

```
A...
AA..
.B..
.BB.

.AB.
AABB
....
....

```

## Case 3

**Input**

```
#....#
######

.####.
.####.

```

**Output**

```
2

```

**Explanation**

```
A....B
AAABBB

.ABBB.
.AAAB.

```

(This test case demonstrates the necessity to rotate/reflect shapes for optimal output)

## Case 4

**Input**

```
.###.
..#..

.##..
.##..

```

**Output**

```
2

```

**Explanation**

No matter how you select blocks, selecting a 2x1 from the first shape necessarily prevents the other two from being grouped together; thus, you can use one 2x1 and two 1x1s. However, (thanks @Jonah), you can split it into a 3-block L shape and a single square like so:

```
.AAB.
..A..

.AA..
.BA..

```

## Case 5

**Input**

```
##
#.

#.
##

```

**Output**

```
1

```

**Explanation**

The input and output shapes may be identical.

## Case 6

**Input**

```
#..
##.
.##

#####

```

**Output**

```
3

```

**Explanation**

There is no way to divide the original shape into two pieces such that both pieces are straight, so at least three are needed.

# Answer
> 6 votes
# Python 3.6, ~~799~~ 791 bytes

7 bytes saved by Jonathan Frech and motavica

```
B=frozenset
M=min
X={}
T=lambda s:((x,y)for y,x in s)
N=lambda s:B((x-M(s)[0],y-M(T(s))[0])for x,y in s)
G=lambda s:{(x,y):s&{(x-1,y),(x+1,y),(x,y-1),(x,y+1)}for(x,y)in s}
C=lambda g,s,i=0:i<=len(g)and(len(g)==len(s)or C(g,s.union(*map(g.get,s)),i+1))
F=lambda s:N([(-x,y)for x,y in s])
P=lambda s,i=4:M([N(s),F(s),P(F(T(s)),i-1)],key=list)if i else s
S=lambda s,t=B(),i=0:t|S(s,B().union(u|{p}for u in t for p in s-u if C(G(u|{p}),{p}))if i else B([B([next(iter(s))])]),i+1)if-~i<len(s)else t
def U(s):
 k=P(s)
 if k in X:return
 j=[t for t in S(k)if C(G(k-t),{next(iter(k-t))})];X[k]={P(t):B()for t in j}
 for t in j:X[k][P(t)]|=B([B(P(k-t))]);U(t);U(k-t)
V=lambda s,t:1+M(V(v,w)for u in B(X[s])&B(X[t])for v in X[s][u]for w in X[t][u])if s^t else 1
A=lambda s,t:U(s)or U(t)or V(P(s),P(t))

```

Try it online!

## Usage

`A(s, t)` takes in two shapes where each shape is given by a list of `x, y` grid positions.

A helper function to convert the graphical representation to a list of positions is below:

```
def H(g):
 g=g.split("\n")
 return[(x,y)for x in range(len(g[0]))for y in range(len(g))if"#"==g[y][x]]

```

Example:

```
case1_1 = \
""".....
.###.
.#.#.
.###.
....."""

case1_2 = \
"""###..
..#..
..#..
..###
....."""

print(A(H(case1_1), H(case1_2))) # Prints 2

```

## Explanation

The algorithm used here is a little better than brute force by caching sub-shapes. For a given shape, it caches all the ways to split that shape into two contiguous shapes, I then normalise these shapes (shift the coordinates so it starts at the origin, then find a rotation/reflection of it which is used in the cache) and store them in the cache to look up quickly later. All sub-shapes then have their sub-shapes cached as well until it gets to the single block shape.

These sub-shapes are generated by converting it to a graph adjacency list and using a BFS to generate all sub-graphs. We can then filter these subgraphs to ones where the vertices which weren't included are a connected component. Determining whether the graph is connected is done with another BFS.

After the cache is complete, the solution is found by comparing the two shapes to find the sub-shapes that it has in common. Once it has these list of sub-shapes, it takes the pair of sub-shapes left over after removing the common shape and recursively applies the same algorithm again to find the minimum number of blocks needed to reconstruct the shape. This then returns the sub-shape with the minimum of all those values and we have our solution.

I've put an annotated version below to kinda explain what each line is doing.

```
B=frozenset
M=min
# Shapes are stored as a frozenset of tuples where each tuple represents an (x, y) position
# Cache of shape partitions. This is a two-level dictionary where the outer key is a shape, and the inner key is a sub-shape where the value is a list of the shapes left when the sub-shape is removed.
# there may be multiple shapes in the inner-most list if the sub-shape appears multiple times
X={}
# Transpose list of coords (flip around diagonal axis)
T=lambda s:((x,y)for y,x in s)
# Translate shape so its upper-left corner is at the origin
N=lambda s:B((x-M(s)[0],y-M(T(s))[0])for x,y in s)
# Convert shape to graph in adjacency list form
G=lambda s:{(x,y):s&{(x-1,y),(x+1,y),(x,y-1),(x,y+1)}for(x,y)in s}
# Check if graph is connected given a set of nodes, s, known to be connected
C=lambda g,s,i=0:i<=len(g)and(len(g)==len(s)or C(g,s.union(*map(g.get,s)),i+1))
# Flip shape around vertical axis
F=lambda s:N([(-x,y)for x,y in s])
# Converts shape to the minimal reflection or rotation. rotation is equivalent to transpose then flip.
P=lambda s,i=4:M([N(s),F(s),P(F(T(s)),i-1)],key=list)if i else s
# returns all the contiguous sub-shapes of s that contain the first pos, given by next(iter(s))
S=lambda s,t=B(),i=0:t|S(s,B().union(u|{p}for u in t for p in s-u if C(G(u|{p}),{p}))if i else B([B([next(iter(s))])]),i+1)if-~i<len(s)else t
# updates the sub-shape cache, X, recursively for an input shape s
def U(s):
 k=P(s)
 if k in X:return
 j=[t for t in S(k)if C(G(k-t),{next(iter(k-t))})];X[k]={P(t):B()for t in j}
 for t in j:X[k][P(t)]|=B([B(P(k-t))]);U(t);U(k-t)
# Gets the minimum number of partitions for two shapes
V=lambda s,t:1+M(V(v,w)for u in B(X[s])&B(X[t])for v in X[s][u]for w in X[t][u])if s^t else 1
# The function to run, will update the cache for the two input shapes then return the minimum number of partitions
A=lambda s,t:U(s)or U(t)or V(P(s),P(t))

```

# Answer
> 2 votes
# Python3, 788 bytes:

```
import itertools as I
E=enumerate
R=lambda x,n=4:set()if n==0 else{str(x),*R([i[::-1]for i in zip(*x)],n-1)}
S=lambda t:{(x,y)for x,k in E(t)for y,p in E(k)if p}
V=lambda x:1==len(x)or all(any((j+J,k+K)in x for J,K in[(0,1),(0,-1),(1,0),(-1,0)])for j,k in x)
G=lambda p,i,F=min:F(j[i]for j in p)
N=lambda p:[(x-G(p,0),y-G(p,1))for x,y in p]
M=lambda j:[[int((x,y) in j)for y in range(G(j,1,max)+1)]for x in range(G(j,0,max)+1)]
O=lambda j:{*R(m:=M(j)),*R([i[::-1]for i in m])}
def P(b,n):
 q=[(b,[],n)]
 while q:
  b,C,n=q.pop(0)
  if n==0 and not b:yield C
  if n and b:
   for i,_ in E(b,1):
    for c in I.combinations(b,i):
     if V(c):q+=[(b-{*c},C+[N(c)],n-1)]
def f(a,b):
 c=0
 while c:=c+1:
  if any(all(O(J)&O(K)for J,K in zip(x,y))for x in P(S(a),c)for y in P(S(b),c)):return c

```

Try it online!

---
Tags: code-golf, math, geometry, grid
---


title: AoCG2021 Day 11: Garbageful streams

text:
# Question
Title: AoCG2021 Day 11: Garbageful streams
Part of **Advent of Code Golf 2021** event. See the linked meta post for details.

Related to AoC2017 Day 9.

*Weekends are Bubbler's days off from posting these lol*

---

A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters.

You sit for a while and record part of the stream (the input). The characters represent groups - sequences that begin with `{` and end with `}`. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a `}` only closes the most-recently-opened unclosed group - that is, they are nestable. The input represents a single group which itself may or may not contain smaller ones.

Sometimes, instead of a group, you will find garbage. Garbage begins with `<` and ends with `>`. Between those angle brackets, almost any character can appear, including `{` and `}`. Within garbage, `<` has no special meaning.

In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using `!`: inside garbage, any character that comes after `!` should be ignored, including `<`, `>`, and even another `!`.

You don't see any characters that deviate from these rules. Outside garbage, you only find well-formed groups, and garbage always terminates according to the rules above.

The following are some example streams with the number of groups they contain:

* `{}`, 1 group.
* `{{{}}}`, 3 groups.
* `{{},{}}`, also 3 groups.
* `{{{},{},{{}}}}`, 6 groups.
* `{<{},{},{{}}>}`, 1 group (which itself contains garbage).
* `{<a>,<a>,<a>,<a>}`, 1 group (containing four pieces of garbage).
* `{{<a>},{<a>},{<a>},{<a>}}`, 5 groups.
* `{{<!>},{<!>},{<!>},{<a>}}`, 2 groups (since all `>`s except the last one are cancelled, creating one large garbage).
* `{{<!!>,{<abc>},<!!!>>,{{<{!>}>},<yes<<<no>}},<>}`, 5 groups.

**Input:** A self-contained, well-formed group as a string.

**Output:** The total number of groups it contains, including itself.

Standard rules apply. The shortest code in bytes wins.

# Answer
# Retina 0.8.2, 12 bytes

```
!.

<.*?>

}

```

Try it online! Link includes test cases. Explanation: The first stage deletes `!`s and the character they protect, the second stage deletes garbage, and the final stage counts the number of remaining groups.
> 15 votes

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

```
x=>x.replace(/<(!?.)*?>|[^}]/g,'').length

```

Try it online!

If it's acceptable to output in unary, remove the `.length` for 34 bytes.

This removes garbage and characters that aren't `}`, then counts what's left.
> 5 votes

# Answer
# Zsh, 35 bytes

```
tr -dc }<<<${1//<(!?|[^>])#>}|wc -c
```

Attempt This Online!

Removes all matches of the pattern `<(!?|[^>])#>`, which matches all garbage.

A few notes:

* Zsh doesn't support greedy vs. non-greedy matching, so I have to use `[^>]` rather than just `?`. (`?` matches any single character, but in order to get the garbage properly, `>`s must not be matched)
* I count closing braces rather than opening braces at the end - they give the same result since they're always balanced, but `}` does not need to be escaped thanks to the `ignore_closing_braces` option
> 4 votes

# Answer
# Ruby, ~~39 36~~ 33 bytes

```
->s{s.scan(/{(<(!?.)*?>)*/).size}

```

Try it online!

Thanks lonelyelk for -3 bytes, I suck at regex.
> 4 votes

# Answer
# TypeScript Types, 192 bytes

```
//@ts-ignore
type M<T,N=[],A=[0]>=T extends`${infer C}${infer T}`?M<C extends"!"?T extends`${string}${infer T}`?T:0:T,C extends"{"?[...N,...A]:N,C extends"<"?[]:C extends">"?[0]:A>:N["length"]

```

Try It Online!

## Ungolfed / Explanation

```
// Mode is [0] if parsing groups, or [] if parsing garbage
type Main<Str, Count=[], Mode=[0]> =
  // Get the first character of Str
  Str extends `${infer Char}${infer Rest}`
    ? Main<
      // If char is "!", set Str to Str[2..]; otherwise, set Str to Str[1..]
      Char extends "!" ? Rest extends`${string}${infer RestRest}` ? RestRest : 0 : Rest,
      // If char is "{", add Mode to Count
      Char extends "{" ? [...Count, ...Mode] : Count,
      // If char is "<", set Mode to [] (garbage); if char is ">", set Mode to [0] (not garbage)
      Char extends "<" ? [] : Char extends">" ? [0] : Mode
    >
    // Str is empty; return Count
    : Count["length"]

```
> 4 votes

# Answer
# Pari/GP, 78 bytes

```
s->a=b=0;#[1|d<-Vec(s),if(a,a=0,d=="!",!a=1,b,d==">"&&b=0,d=="<",!b=1,d=="{")]

```

Try it online!

When your language doesn't have regexp or any string pattern matching built-in...
> 2 votes

# Answer
# Charcoal, 39 bytes

```
≔⁰η≔¹ζ≔⁰εＦＳ«¿ε≔⁰ε≡ι!≔¹ε<≔⁰ζ>≔¹ζ}≧⁺ζη»Ｉη

```

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

```
≔⁰η

```

Start off with no groups.

```
≔¹ζ

```

Start off with no garbage.

```
≔⁰ε

```

Start off without cancellation.

```
ＦＳ«

```

Loop over the input characters.

```
¿ε≔⁰ε

```

If the previous character was a `!` then cancel this character.

```
≡ι

```

Otherwise, switch on the current character.

```
!≔¹ε

```

If it's a `!` then cancel the next character.

```
<≔⁰ζ

```

If it's a `<` then turn on garbage.

```
>≔¹ζ

```

If it's a `>` then turn off garbage.

```
}≧⁺ζη

```

If it's a `}` that's not inside garbage then increment the number of groups.

```
»Ｉη

```

Output the final number of groups.
> 2 votes

# Answer
# BQN, 56 bytesSBCS

```
{⌈2÷˜≠','⊸≠⊸/{/˜¬∨⟜»×{+×1⌈|}`-˝"<>"=⌜}/˜¬∨⟜»'!'=}

```

Run online!

-10 bytes from ovs.

Individually removes each main pattern (`!`, `<>`, `,`) and checks length. Then divide that by 2 and take ceiling.
> 2 votes

# Answer
# Python 3, 117 bytes

```
n=0;g=1;s=input()
for x,y in zip(s,s[1:]):
 if '!'not in x+y:
  if y in'<>':g='<>'.index(y)
  if g:n+=y=='}'
print(n)

```

Try it online!

A regex less solution, shorter than @Ajax1234

**Python 2, 114 bytes (Unsure if allowed)**

```
n=0;g=1;s=input()
for x,y in zip(s,s[1:]):
 if '!'not in x+y:
  if y in'<>':g='<>'.index(y)
  if g*y=='}':print 1,

```

Try it online!

outputs in unary with space between each digit
> 2 votes

# Answer
# Python 3, 74 bytes

```
f=lambda s,m=1:s>''and(s[0]=='{'*m)+f(s[1+('!'==s[0]):],m^('><'[m]==s[0]))

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 68 bytes

```
Fold[StringDelete,#,{"!"~~_,"<"~~Shortest@__~~">"}]~StringCount~"{"&

```

Try it online!
> 2 votes

# Answer
# Rust, 170 166 bytes

```
|i:&str|{let(mut g,mut s)=(0,vec![123]);for c in i.bytes(){match&[s[s.len()-1],c]{b"<!"|b"{<"|b"{{"=>s.push(c),[33,_]|b"<>"=>{s.pop();}b"{}"=>{g+=1;s.pop();}_=>()}}g}

```

Try it online!

* -4 bytes by not using `Option` (thanks @AnttiP)
> 2 votes

# Answer
# x86 32-bit machine code, 31 bytes

```
56 96 31 d2 31 c9 4a 42 41 ac 3c 21 75 01 46 3c 3e 74 f1 e2 f3 7a f1 73 ee 48 7b ed 5e 92 c3

```

Try it online!

Following the `regparm(1)` calling convention, this takes the address of a null-terminated byte string in EAX.

Assembly:

```
.text                   # In the main loop, EDX will count the number of {
.global gstr            #  and ECX will be 1 outside garbage, 0 inside garbage.
.intel_syntax noprefix
gstr:
    push esi        # Save the value of ESI onto the stack
    xchg esi, eax   # Switch the string address into ESI
    xor edx, edx    # Set EDX to 0
c1: xor ecx, ecx    # Set ECX to 0
    dec edx         #  (These two instructions have a net effect of nothing,
iD: inc edx         #    but we can jump into the middle to add 1 to EDX.)
r:  inc ecx         # Increment ECX, at first to 1
l:  lodsb           # Read a character from the string into AL
    cmp al, 0x21    # Check for !
    jne s           #  Jump if not !
    inc esi         #  If !, increment ESI to skip the next character
s:  cmp al, 0x3E    # Compare with >
    je c1           #  Jump on > to reset ECX to 1
    loop r          # Decrement ECX and jump (to restore it and proceed)
                    #  if it was 0 (within garbage)
    jpe r           # Jump (same) to ignore } and ,
    jnc iD          # Jump on { to count up in EDX (and restore ECX)
    dec eax         # Decrement EAX, setting PF from the low 8 bits
    jpo l           # Jump on < to proceed (ECX remains 0)
    pop esi         # NUL: Restore the value of ESI from the stack
    xchg edx, eax   # Switch the count into EAX
    ret             # Return

```
> 2 votes

# Answer
# 05AB1E, ~~17~~ 16 bytes

```
'!š¬ìKDŒ€…<ÿ>K¤¢

```

Despite 05AB1E's lack of regex, it turned out surprisingly short. :)

Try it online or verify all test cases.

**Explanation:**

```
         # Remove all "!" and the character after it:
'!š     '#  Split the (implicit) input-string to a list of characters, and prepend a "!"
   ¬     #  Push the first item (without popping), which is the "!"
    ì    #  Prepend this "!" in front of each character
     K   #  Remove all those 2-char strings from the (implicit) input-string
         #  (the `š¬` is necessary to first remove all "!!")
         # Remove all "<...>" garbage groups:
D        #  Duplicate the string
 Œ       #  Pop the copy, and push all its substrings
  €      #  Map each substring to:
   …<ÿ>  #  Prepend a "<" and append a ">"
       K #  Remove all those from the string as well
         # Count how many groups are left:
¤        #  Push the last character (without popping), which is "}"
 ¢       #  Count how many "}" are in the string
         # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Python3, 156 bytes:

```
f=lambda x,g=0,c=0,i=0:c if not x else f(x[1:],(g:=(x[0]=='<'or(x[0]!='>'and g))),c+(not g and x[0]=='}' and not i),x[0]=='!'or(i and x[0]not in [",","}"]))

```

Try it online!
> 1 votes

# Answer
# Python 3, 54 bytes

```
lambda x:re.sub('<(!?.)*?>','',x).count('{')
import re

```

Try it online!

Port of my JS answer. Go read that, it's almost the same thing.
> 1 votes

# Answer
# Perl 5 `-p`, 26 bytes

```
s/!.//g;s/<.*?>//g;$_=y;{;

```

Try it online!
> 1 votes

# Answer
# SM83, 24 bytes

Input in `hl` as null-terminated string. Output in `bc`.

```
2A B7 C8 FE 7B 20 01 03
FE 3C 20 F4 2A FE 3E 28
EF FE 21 20 F7 23 18 F4

```

```
f:
    ld a,(hl+)      ;; 2A       ;; load char
    or a            ;; B7       ;; test for 0
    ret z           ;; C8       ;; if so, at end; return
    cp '{'          ;; FE 7B
    jr nz,x         ;; 20 01    ;; if not '{'
    inc bc          ;; 03       ;; increment result
x:
    cp '<'          ;; FE 3C    ;; if not '<'
    jr nz,f         ;; 20 F4    ;; loop
l:                              ;; degarbaging:
    ld a,(hl+)      ;; 2A       ;; load char
    cp '>'          ;; FE 3E    ;; if '>'
    jr z,f          ;; 28 EF    ;; go back to start
    cp '!'          ;; FE 21    ;; if not '!'
    jr nz,l         ;; 20 F7    ;; continue degarbaging
    inc hl          ;; 23       ;; skip char
    jr l            ;; 18 F4    ;; and continue degarbaging

```
> 1 votes

---
Tags: code-golf, string, parsing, balanced-string
---


title: Matrix Meets ASCII Art

text:
# Question
Title: Matrix Meets ASCII Art
A binary matrix represents a shape in the plane. 1 means a unit square at that position. 0 means nothing. The background is 0.

For example, the array `[[0,1,0],[0,0,1],[1,1,1]]` represents the following shape:

```
     o----o
     |////|
     |////|
     o----o----o
          |////|
          |////|
o----o----o----o
|////|////|////|
|////|////|////|
o----o----o----o

```

# Challenge

You take input as the array and output the matching ASCII art.

### As with all code-golfing challenges, the shortest code in terms of bytes wins.

# Examples

`[[1,1,1],[0,0,0]]`

```
o----o----o----o
|////|////|////|
|////|////|////|
o----o----o----o

```

(You may or may not trim)

`[[0,1,0],[1,0,1]]`

```
     o----o
     |////|
     |////|
o----o----o----o
|////|    |////|
|////|    |////|
o----o    o----o

```

`[[1,0,1,0],[0,0,0,0],[1,1,1,0]`

```
o----o    o----o
|////|    |////|
|////|    |////|
o----o    o----o

o----o----o----o
|////|////|////|
|////|////|////|
o----o----o----o

```

`[[1]]`

```
o----o
|////|
|////|
o----o

```

You can choose whether or not to trim surrounding whitespace, from either rows, columns, both or neither

# Answer
> 7 votes
# Python, ~~232~~ ~~223~~ 209 bytes

*-9 bytes thanks to @Kevin Cruijssen*

*-11 bytes thanks to @a stone arachnid*

*-3 bytes thanks to @Steffan*

```
def f(a):R=range;E=enumerate;s=[[*" "*6*len(_)]for _ in 4*a];[s[I+3*i].__setitem__(J+j*5,"/|-o"[2*(I%3<1)+(J%5<1)])for i,r in E(a)for j,x in E(r)if x for I in R(4)for J in R(6)];print(*map("".join,s),sep="\n")
```

Attempt This Online!

# Answer
> 5 votes
# Charcoal, 33 bytes

```
ＦＡ«Ｆι«ＦκＰ”{⊟∨¹↖﹪Ｈ✂sρSjυ%‖”Ｍ⁵→»⸿⸿⸿

```

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

```
ＦＡ«

```

Loop through the rows.

```
Ｆι«

```

Loop through the cells of this row.

```
ＦκＰ”{⊟∨¹↖﹪Ｈ✂sρSjυ%‖”

```

If this cell is `1` then output a compressed representation of the shape without moving the cursor.

```
Ｍ⁵→

```

In any case move the cursor five characters to the right. This causes adjacent shapes to overlap by one character.

```
»⸿⸿⸿

```

After each row move the cursor to the start of the bottom row of the current line, so that the next row will overlap by one character.

Drawing the shape using Charcoal commands turns out to also take 33 bytes:

```
ＦＡ«Ｆι«Ｆκ«Ｆ²Ｆ²«o⁻⁴⊗ν↷»↘¤/↖»Ｍ⁵→»⸿⸿⸿

```

Try it online! Link is to verbose version of code. Explanation: As above, except instead of `Ｐ”{⊟∨¹↖﹪Ｈ✂sρSjυ%‖”`:

```
Ｆ²Ｆ²«o⁻⁴⊗ν↷»

```

Draw a rectangle with `o`s at the corners.

```
↘¤/↖

```

Fill the rectangle with `/`s.

If `+`s had been acceptable for corners then `Ｆ²Ｆ²«o⁻⁴⊗ν↷»` could have been replaced with `Ｂ⁶¦⁴` saving eight bytes.

```
ＦＡ«Ｆι«Ｆκ«Ｂ⁶¦⁴↘¤/↖»Ｍ⁵→»⸿⸿⸿

```

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

# Answer
> 3 votes
# , 58 bytes

```
' -o/|'{~(1 3 3 1+/#:33)>./@((]$_3 _5&*@#:I.@,)|.*&$~{.[)]

```

Try it online!

Consider input:

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

```
* `(1 3 3 1+/#:33)` Create a numeric matrix representing the ascii "cell":

```
2 1 1 1 1 2
4 3 3 3 3 4
4 3 3 3 3 4
2 1 1 1 1 2

```
* `*&$~{.[` Multiply dimensions of that times dimensions of input, ie, `4 6 * 3 3`, giving `12 18`, and extend our cell to those dimensions, which will always be slightly bigger than we need:

```
2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0
4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0
4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0
2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```
* Our strategy will be to rotate the above matrix in 2 dimensions, one time for each 1, moving the cell into each require position.

+ `$...#:I.@,` Convert the positions of the ones into 2d coordinates:

    ```
     0 1
     1 2
     2 0
     2 1
     2 2

    ```
    + `_3 _5&*@` Multiply row-wise by "dimensions of cell, minus 1, negated". The negation is needed because we want to rotate right rather than left.

    ```
     0  _5
    _3 _10
    _6   0
    _6  _5
    _6 _10

    ```
    + `|.` Create multiple copies of our "extended" cell, rotating by those amounts:

    ```
    0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0
    0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0
    0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0
    0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0
    0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0
    0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0
    0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0
    4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0
    4 3 3 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0
    2 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0
    0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0
    0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0
    0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0
    0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0
    0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0
    0 0 0 0 0 0 0 0 0 0 2 1 1 1 1 2 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    ```
* `>./@` Max reduce these "planes" to create a single matrix, which handles the overlapping corners:

```
0 0 0 0 0 2 1 1 1 1 2 0 0 0 0 0 0 0
0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0
0 0 0 0 0 4 3 3 3 3 4 0 0 0 0 0 0 0
0 0 0 0 0 2 1 1 1 1 2 1 1 1 1 2 0 0
0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0
0 0 0 0 0 0 0 0 0 0 4 3 3 3 3 4 0 0
2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 0 0
4 3 3 3 3 4 3 3 3 3 4 3 3 3 3 4 0 0
4 3 3 3 3 4 3 3 3 3 4 3 3 3 3 4 0 0
2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```
* `' -o/|'{~` Convert to ascii:

```
o----o
|////|
|////|
o----o----o
     |////|
     |////|
o----o----o----o
|////|////|////|
|////|////|////|
o----o----o----o

```

# Answer
> 2 votes
# Perl 5 \+ `-pl`, 77 bytes

```
$"="..[6D";s!.!@{[$&?qw(o----o |////|)[0,1,1,0]:(".[6C")x4]}.[3A.!g;$\=".[3E"
```

Try it online!

Contains unprintable characters and uses ANSI escape codes to reposition the cursor and output the required ASCII art. Long arrays may not display correctly in the browser (as the terminal is a fixed height and the cursor cannot move out of bounds). Happy to delete if this is not to spec!

## Explanation

First, we set the list separator variable (`$"` \- this is automatically added to string when a list is interpolated into it) to a string that will move the cursor down 1 line (form feed - `\x0c`) and back 6 characters (`\x1b[6D`). Then `s///`ubstitute each char (`.`) in (the implicit, stored in `$_`, via `-p`) input with an inline interpolated array (`@{[...]}`) that contains either the four parts of the box (`qw(o----o |////|)[0,1,1,0]`) or four repetitions of moving the cursor forward six characters (`("\x1b[6C")x4`), depending on whether or not the currently matched character (`$&`) is truthy. At the end of the string the cursor is moved back up three lines (`\x1b[3A`) and a literal backspace moves the cursor back one character (`\x08`). Finally, the output record separator (`$\`) is set to a string that moves the cursor to the beginning of the line three lines down (`\x1b[3E`), which is automatically printed (along with the modified input).

# Answer
> 2 votes
# JavaScript, 182 bytes

```
m=>m.map(g=r=>((p=(L=(` |`[r[0]]+r.map((d,x)=>d?`////|`:`    `+` |`[r[x+1]|0]).join``+`
`))[R='replace'](/\//g,'-')[R](/\|/g,'o'))[R](/ /g,(c,i)=>P[i]||' '))+(P=p,L)+L,P='').join``+P

```

Can probably be golfed a lot more.

```
f=
m=>m.map(g=r=>((p=(L=(` |`[r[0]]+r.map((d,x)=>d?`////|`:`    `+` |`[r[x+1]|0]).join``+`
`))[R='replace'](/\//g,'-')[R](/\|/g,'o'))[R](/ /g,(c,i)=>P[i]||' '))+(P=p,L)+L,P='').join``+P
;

console.log(f([
  [1,1,1],
  [0,0,0]
]));
console.log(f([
  [0,1,0],
  [1,0,1]
]));
console.log(f([
  [1,0,1,0],
  [0,0,0,0],
  [1,1,1,0]
]));
console.log(f([
  [1]
]));
console.log(f([
  [1,0,1,0],
  [1,0,0,0],
  [0,0,0,1],
  [1,1,1,0]
]));
```

# Answer
> 1 votes
# C (clang), ~~198~~ 197 bytes

-1 byte thanks to @ceilingcat.

---

Based on @Matteo C.'s Python answer.

```
#define F(_,t)for(_=t;_--;)
i;j;I;J;f(*a,X,Y){char*s[3*X+1];F(i,4*X)asprintf(s+i,"%*c",Y*5,0);F(i,X)F(j,Y)if(a[i*Y+j])F(I,4)F(J,6)s[I+3*i][J+j*5]="/|-o"[2*!(I%3)+!(J%5)];F(i,j=3*X+1)puts(s[j+~i]);}

```

Try it online! Takes input as the matrix as a flattened array, the number of rows in the matrix, and the number of elements in each row.

# Answer
> 0 votes
# PowerShell, 186 bytes

```
$args|%{$l=$m=' '
$_|%{if($_){$l=($l-replace'.$')+'o----o';$m=($m-replace'.$')+'|////|'}else{$l+=' '*5;$m+=' '*5}}
$p+=$l*!$p
&{-join($l|% t*y|%{($_,$p[$i++])[$_-eq32]})}
$m;$m;$p=$l}
$p

```

Try it online!

Less golfed:

```
$args|%{
    $line=$midl=' '

    $_|%{                               # for each row element
        if($_){
            $line=($line-replace'.$')+'o----o'
            $midl=($midl-replace'.$')+'|////|'
        }else{
            $line+=' '*5
            $midl+=' '*5
        }
    }

    $prev+=$line*!$prev                 # use $line as previous if $prev is empty

    &{                                  # run in new context to reset the local variable $i.
        -join($line|% toCharArray|%{    # output a new line, where
            ($_,$prev[$i++])[$_-eq32]   # each space char from $line
        })                              # replaced by related char from $prev
    }

    $midl                               # implicit output
    $midl                               # implicit output

    $prev=$line
}
$prev                                   # implicit output

```

---
Tags: code-golf, ascii-art, geometry, binary-matrix
---


title: Case Conversion Polyglot

text:
# Question
Title: Case Conversion Polyglot
Your task is to write a program that performs case conversion from plain text, and other case formats, into one of the specified formats below. Inputs will be either plain lowercase text, or one of the detailed cases below. You must remove non-alphabetic characters except  (space), `_` (underscore) and `-` (hyphen), then split the string into words by the locations of /`_`/`-` and places where two adjacent characters have different cases (e.g. `bA`). Then change the capitalization of each word and join the words on some delimiting character. The specifics of capitalization and delimiter depend on the case conversion chosen.

Your program must be a polyglot in at least two different languages. For example, running your code in Python 2 transforms input to `snake_case`, running it in JavaScript transforms to `kebab-case`, Ruby transforms to `PascalCase` and 05AB1E transforms to `camelCase`.

## Tasks

The following case conversions can be completed:

| Case | Capitalization | Delimiter |
| --- | --- | --- |
| camelCase | First word should be all lowercase; the rest should be all lowercase except for the first letter, which should be uppercase. | None |
| PascalCase | The first letter of each word should be uppercase, the rest lowercase. | None |
| snake\_case | Words should be all lowercase. | `_` |
| UPPER\_SNAKE\_CASE | Words should be all uppercase. | `_` |
| kebab-case | Words should be all lowercase. | `-` |

### camelCase

```
this is a test         thisIsATest
camelCaseTest          camelCaseTest
PascalCaseTest         pascalCaseTest
snake_case_test        snakeCaseTest
kebab-case-test        kebabCaseTest
testing!!one!!!1!!!    testingOne1
aBCDef                 aBCDef
ABCDef                 aBCDef
a_b_c_def              aBCDef
a-b-c-def              aBCDef

```

Try it online!

### PascalCase

```
this is a test         ThisIsATest
camelCaseTest          CamelCaseTest
PascalCaseTest         PascalCaseTest
snake_case_test        SnakeCaseTest
kebab-case-test        KebabCaseTest
testing!!one!!!1!!!    TestingOne1
aBCDef                 ABCDef
ABCDef                 ABCDef
a_b_c_def              ABCDef
a-b-c-def              ABCDef

```

Try it online!

### snake\_case

```
this is a test         this_is_a_test
camelCaseTest          camel_case_test
PascalCaseTest         pascal_case_test
snake_case_test        snake_case_test
kebab-case-test        kebab_case_test
testing!!one!!!1!!!    testing_one_1
aBCDef                 a_b_c_def
ABCDef                 a_b_c_def
a_b_c_def              a_b_c_def
a-b-c-def              a_b_c_def

```

Try it online!

## UPPER\_SNAKE\_CASE / SCREAMING\_SNAKE\_CASE

```
this is a test        THIS_IS_A_TEST
camelCaseTest         CAMEL_CASE_TEST
PascalCaseTest        PASCAL_CASE_TEST
snake_case_test       SNAKE_CASE_TEST
kebab-case-test       KEBAB_CASE_TEST
testing!!one!!!1!!!   TESTING_ONE_1
aBCDef                A_B_C_DEF
ABCDef                A_B_C_DEF
a_b_c_def             A_B_C_DEF
a-b-c-def             A_B_C_DEF

```

Try it online!

### kebab-case

```
this is a test         this-is-a-test
camelCaseTest          camel-case-test
PascalCaseTest         pascal-case-test
snake_case_test        snake-case-test
kebab-case-test        kebab-case-test
testing!!one!!!1!!!    testing-one-1
aBCDef                 a-b-c-def
ABCDef                 a-b-c-def
a_b_c_def              a-b-c-def
a-b-c-def              a-b-c-def

```

Try it online!

## Rules

* Your code should produce the same output as the linked examples.
* Entries with the most conversions in each language win, with code length being a tie-breaker.

# Answer
> 3 votes
## Java, Retina, 05AB1E, 05AB1E (legacy), 2sable, 166 characters

```
//'_UðX:'-X:AuDSX«í‡X¡õKDтнi™Jć„ul®dè.VìëXýu}q
s->s.replaceAll("[A-Z]","-$0").toLowerCase().replaceAll(" |_","-").replaceAll("^-","")/*
[A-Z]
_$0
T`L`l
 |-
_
^_

\*/

```

Try it online in Java: `kebab-case`
Try it online in Retina: `snake_case`
Try it online in 05AB1E: `PascalCase`
Try it online in 05AB1E (legacy): `camelCase`
Try it online in 2sable: `SCREAMING_SNAKE_CASE`

**Explanation:**

***Java:***

```
//...                   // No-op comment
s->                     // Method with String as both parameter and return-type
  s.replaceAll(         //  Regex-replace all:
     "[A-Z]",           //   Uppercase letters
     "-$0")             //   To the same uppercase letter with a prepended "-"
   .toLowerCase()       //  Then convert it to lowercase
   .replaceAll(         //  Then regex-replace all:
     " |_",             //   Spaces or "_"
     "-")               //   To "-"
   .replaceAll("^-","") //  And remove a potential leading "-"
/*...*/                 // No-op comment
                        // No-op newline

```

***Retina:***

```
//A...™Jq
s->...)/*

```

Replace the first line to the second in the (implicit) input-string; which is basically a no-op replacement.

```
[A-Z]
_$0

```

Prepend a `_` in front of each uppercase letter.

```
T`L`l

```

Convert everything to lowercase.

```
 |-
_

```

Replace any space or `-` to `_`.

```
^_

```

Remove a potential leading `_`.

```
\*/

```

No-op replacement to close the Java comment.

***05AB1E / 05AB1E (legacy) / 2sable:***

Let's start with a bit of history of these three versions. The development of 05AB1E started at the start of 2016 (or actually, the very first git-commit was on December 21st, 2015). This new codegolf language was being built in Python as backend. Mid 2016 2sable was branched of that current 05AB1E version (July 7th, 2016 to be exact), and the strength of 2sable in comparison to that old 05AB1E version was added: implicit inputs. Later on implicit input was also added to 05AB1E, and 2sable became obsolete and basically a forgotten version right after it was created on that day July 7th, 2016.
Then in mid-2018, a new 05AB1E version was being started, this time completely rewritten in Elixir instead of Python, with loads of new builtins added and some builtins changed or even removed.

So, let's go over the code and see what it does in each of the three versions:

```
/                # Divide the (implicit) input-string with itself, which is a no-op
                 # for strings
 /               # And again
'_              '# Push string "_"
  U              # Pop and store it in variable `X`
ðX:              # Replace all spaces with "_"
'-X:            '# Replace all "-" with a "_" as well
Au               # Push the uppercase alphabet
  D              # Duplicate it
   S             # Convert the copy to a list of characters
    X«           # Append "_" to each
      í          # Reverse each so "_" is prepended instead
                 # (2sable lacks prepend-builtin `ì`, hence the `«í` instead)
       ‡         # Transliterate, basically prepending a "_" before each uppercase
                 # letter in the input-string
X¡               # Then split on "_"
  õK             # Remove all empty strings, in case the input started with an
                 # uppercase letter
D                # Duplicate the current list of strings
 т               # 05AB1E / 05AB1E (legacy): push 100
                 # 2-sable: no-op
  н              # Pop and push the first character:
                 #  05AB1E / 05AB1E (legacy): pops 100, pushes 1
                 #  2-sable: pops the string: pushes its first character
   i             # If this is 1 (continue for 05AB1E / 05AB1E (legacy)):
    ™            #  Titlecase each inner string
     J           #  Join it together
      ć          #  Extract the first character
       „ul       #  Push string "ul"
          ®      #  Push -1
           d     #  05AB1E: check if it's a non-negative (>=0) integer: pop -1, push 0
                 #  05AB1E (legacy): check if it's an integer: pop -1, push 1
            è    #  Use that to index into the "ul" string
             .V  #  Execute it as 05AB1E code
                 #   05AB1E: uppercase the letter
                 #   05AB1E (legacy): lowercase the letter
               ì #  Prepend it back to the string
   ë             # Else (continue for 2sable):
    Xý           #  Join the list with "_" delimiter
      u          #  Uppercase the letters in the string
   }             # (for all three again): close the if-else statement
    q            # Exit the program, making everything after it no-ops
                 # (after which the result is output implicitly)

```

Minor note: `®dilëu` would have been shorter than `„ul®dè.V`, but unfortunately 2sable doesn't deal very well with nested if-else statements.

# Answer
> 2 votes
# Ruby & J, 189 bytes

```
NB.x rescue puts$<.read.split(/(?=[A-Z])|[^a-zA-Z]+/).map{_1.downcase.gsub(/[^a-z]/,'')}*"_"
#]exit'']echo tolower(,'-'&,)&:>/a:-.~(<@(-.-.&AlphaNum_j_)@u:;.1~1:0}<&97+.>&122)&(3&u:)(1!:1)3
```

Ruby (snake)

J (kebab)

These are really terrible as golfs, and I was hoping to get at least one more lang, but this was all I could manage for tonight...

* `NB.` is the J comment prefix, and `NB.x` is valid ruby code for attempting to invoke the method `x` on the constant `NB`. It will fail since `NB` is undefined, but we can then just `rescue` that error and proceed as normal.
* `#` is a ruby comment, and a J verb. It gets ignored when J runs because J executes right to left, and we `exit` before it gets interpreted.

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


title: Generate all Possibilities of Words

text:
# Question
Title: Generate all Possibilities of Words
This is not the same as m-ss-ng-lette-s

**Challenge:**

Given a string with masked characters, generate all possible words, inclusive of non-meaningfull words.

**Rules:**

* The sequence of the characters in the string does not change.
* The masked character (\*) will be one of an English alphabets \[a-z\].
* There are no line breaks, space, numbers, special characters or punctuations.
* The output can be a list of non-meaningfull words too.
* Any characters in a string can be masked. Not necessarily alternating characters.
* For memory constraint, lets keep the maximum length of input as 10.

**Example 1:**

Input:

```
*o*

```

Output:

```
aoa
aob
aoc
...
...
...
boa
bob
boc
...
...
...
zoa
zob
zoc
...
...
...
zoz

```

**Example 2:**

Input:

```
*e*c*m*

```

Output:

```
aeacama
aeacamb
...
...
...
welcome
...
...
zezczmz

```

This is , so shortest answer in bytes wins!

# Answer
> 8 votes
# Zsh, 25 bytes

```
eval echo ${1//\*/{a..z}}
```

Attempt This Online!

# Answer
> 9 votes
# Haskell, 31 bytes

```
mapM q
q '*'=['a'..'z']
q c=[c]

```

Try it online!

# Answer
> 8 votes
# Ruby, 39 bytes

```
->s{(?a..?z*10).grep /^#{s.tr'*',?.}$/}

```

Try it online!

The range is set to terminate after 10 `z`s, to fit the constraint. Realistically this takes forever to run unless a smaller number is used.

# Answer
> 7 votes
# Vyxal `j`, 5 bytes

```
×kaVΠ

```

Try it Online! Input as char lists.

```
   V  # Replace
×     # Asterisks
 ka   # With the lowercase alphabet
    Π # Take cartesian product

```

# Answer
> 6 votes
# Perl 5 \+ `-n -M5.10.0`, 37 bytes

1 byte saved thanks to @Sisyphus!

```
$"=",";s/\*/{@{[a..z]}}/g;say<"$_\n">
```

Try it online!

## Explanation

Turns the input into a `glob` (`<"$_\n">`) which is then evaluated as a list and printed (`say`) with newline separators.

**Note:** This does struggle to produce all the output for multiple `*`s when running on my phone!

# Answer
> 5 votes
# Python 3, ~~88~~ 86 bytes

```
def A(x):p=x.find("*");~p and[A(x[:p]+chr(i+97)+x[p+1:])for i in range(26)]or print(x)

```

Removed 2 bytes thanks to @Adam

# Answer
> 4 votes
# Vyxal `j`, ~~14~~ 13 bytes

```
×Oka↔ƛ?×\%V$%

```

Try it Online!

Could be 8 bytes by using `%` instead of `*`

# Answer
> 4 votes
# Vyxal `j`, 9 bytes

```
×Ẇ⌈yvkaYΠ

```

Try it Online!

Based on emanresu A's answer, but shaves off another byte.

# Answer
> 4 votes
# , 65 bytes

```
f=\(s)`if`(grepl("[*]",s[1]),f(sapply(letters,sub,pa="[*]",s)),s)
```

Attempt This Online!

Basically the same recursive idea as in Cong Chen's answer.

# Answer
> 4 votes
# Julia, 61 bytes

```
!s=join.(Iterators.product((x>'*' ? x : 'a':'z' for x=s)...))
```

Attempt This Online!

(This returns a matrix of all possible words, rather than a list/vector.)

# Answer
> 3 votes
# Charcoal, 25 bytes

```
⊞υＳＦυ¿№ι*Ｆβ⊞υ⭆ι⎇⁻μ⌕ι*λκ⟦ι

```

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

```
⊞υＳ

```

Start with the input string.

```
Ｆυ

```

Check each string.

```
¿№ι*

```

If it contains a `*`, then:

```
Ｆβ

```

Loop over the lowercase alphabet.

```
⊞υ⭆ι⎇⁻μ⌕ι*λκ

```

Replace the first `*` in the string with the current letter and push it to the search list.

```
⟦ι

```

Otherwise output the string on its own line.

23 bytes using the newer version of Charcoal on ATO:

```
⊞υωＦＳ≡ι*≔ΣＥυＥβ⁺κμυ≧⁺ιυυ

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
⊞υω

```

Start with the empty string.

```
ＦＳ

```

Loop over the characters of the input string.

```
≡ι*

```

If the current character is a `*`, then...

```
≔ΣＥυＥβ⁺κμυ

```

... append each lowercase letter to each of the strings so far and join the resulting lists, otherwise...

```
≧⁺ιυ

```

... append the current character to each of the strings so far.

```
υ

```

Output the final list of strings.

# Answer
> 3 votes
# Retina, 30 bytes

```
/\*/{%`$
25*$(¶$`
,Y0`*`l`\*.*

```

Try it online! Explanation:

```
/\*/{

```

Repeat while there are still any `*`s to process.

```
%`$
25*$(¶$`

```

Add 25 copies of each line.

```
,Y0`*`l`\*.*

```

Cyclically transliterate the first `*` on each line to the lowercase alphabet. The `,` tells Retina to process all matches and the `0` tells Retina to process the first character of each match.

# Answer
> 3 votes
# lin, 49 bytes

```
"\*".?g.+_.+_"%s"?s.#t ?i len $a.~ `/\".t.~ sf"`'

```

Try it here! Returns an iterator of strings.

For testing purposes:

```
"*e*c*m*" ; \outln `' `_
"\*".?g.+_.+_"%s"?s.#t ?i len $a.~ `/\".t.~ sf"`'

```

## Explanation

Prettified code:

```
"\*".?g.+_.+_ "%s"?s.#t ?i len $a.~ `/\ (.t.~ sf ) `'

```

Not very short, but surprisingly straightforward.

* `"\*".?g` regex `/\*/g`
* `.+_.+_ "%s"?s.#t` replace `*` with `%s` and store as *t*
* `?i len` get number of `*`s as *n*
* `$a.~ `/\` create length-*n* "digit" sequences from alphabet
* `(.t.~ sf ) `'` use *t* to `sprintf` each sequence

# Answer
> 3 votes
# sh + coreutils + hashcat, 31 bytes

```
sed s/*/?l/g|xargs hashcat -a 3

```

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
'*A:.»â€S

```

Input as a list of characters.

Try it online or verify both test cases.

**Explanation:**

```
'*A:      '# Replace all "*" in the (implicit) input-list with the lowercase alphabet
    .»     # Left-reduce the list of strings by:
      â    #  Taking the cartesian product
       €S  # Then convert each inner list to a flattened list of characters
           # (after which the result is output implicitly)

```

Minor note: `'*` could be `W` in the legacy version of 05AB1E if the input is guaranteed to always contain a `"*"`, but unfortunately the `€S` should be `€˜J` in that case, not saving any bytes.

# Answer
> 2 votes
# , 91 bytes

```
\(a,j=Vectorize(\(x,y)sub('*',y,x,,,T),'y'))`if`(grepl('*',a,,,T),sapply(j(a,letters),f),a)
```

Recursive solution.

Attempt This Online!

# Answer
> 2 votes
# Factor \+ `spelling`, ~~60~~ 56 bytes

```
[ 1 group { "*"} ${ ALPHABET } replace [ ] product-map ]

```

Attempt This Online!

```
                              ! "*o*"
1 group                       ! { "*" "o" "*" }
{ "*"} ${ ALPHABET } replace  ! { "abcdefghijklmnopqrstuvwxyz" "o" "abcdefghijklmnopqrstuvwxyz" }
[ ] product-map               ! { "aoa" "boa" ... "zoz" }

```

# Answer
> 2 votes
# Brachylog, 13 bytes

```
ẹ{"*"∧!Ạ∋|}ᵐc

```

Try it online!

This is a generator predicate that will unify its output with each possible combination. The TIO example uses `ᶠ - findall` to generate all answers, but in a Prolog REPL you could just press `;` repeatedly to get each answer.

### Explanation

```
ẹ                Split the string into a list of characters
 {         }ᵐ    Map for each char:
  "*"              If the char is "*"
     ∧!              Cut (i.e. discard the "else" possibility)
        Ạ∋           The output is an element of the alphabet
          |        Else don’t modify the char
             c   Concatenate back to a string

```

The cut `!` is necessary, otherwise the predicate would also generate answers with the asterisk unchanged.

# Answer
> 2 votes
## JavaScript, 111 bytes

I feel like it's way too long and I'm missing something big.

```
s=>(r=s=>s[1]?.at?[...'abcdefghijklmnopqrstuvwxyz'].flatMap(c=>r(s.slice(1)).map(p=>s[0]+c+p)):s)(s.split('*'))

```

# Answer
> 2 votes
# Also **Python 3, 86 Bytes**:

```
def f(x):
 for i in range(26):y=x.replace('*',chr(i+97),1);f(y)if'*'in y else print(y)

```

# Answer
> 2 votes
# Julia, 61 bytes

```
!s=foldl((x,y)->[x.*y...],[x<'a' ? 'a'.+(0:25)' : x for x=s])
```

Attempt This Online!

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