title: Suggest me a challenge!

text:
# Question
Title: Suggest me a challenge!
I am too bored and want a challenge to solve. But I do not see any interesting challenges, and I am too lazy to search for one. Can you (Well, technically your code) suggest me one?

---

# I/O

**Input:** None.

**Output:** A link to a random open(i.e. non-closed) challenge("Challenge" excludes !) on PPCG. You may not link to an answer in a challenge, Just a challenge. (I didn't ask for an interesting answer!)

---

# Examples

**Valid:**

```
http://codegolf.stackexchange.com/questions/93288/make-me-a-mooncake
http://codegolf.stackexchange.com/questions/113796/raise-a-single-number
http://codegolf.stackexchange.com/questions/113898

```

**Invalid:**

```
http://codegolf.stackexchange.com/questions/78152/tips-for-golfing-in-matl (tips question)
http://codegolf.stackexchange.com/questions/113896/josephus-problem (closed)
http://codegolf.stackexchange.com/questions/84260/add-two-numbers/84365#84365 (linked to answer)

```

# Answer
> 4 votes
# JavaScript (ES6), 209 bytes

Does work, but will most likely hit the StackExchange API limit very quickly. It will probably take a while to output the link, as it's checking randomly for a valid question.

```
_=>fetch(`//api.stackexchange.com/2.2/questions/${new Date%2e4}?site=codegolf`).then(_=>_.json()).then((a,b=a.items)=>{if(!b.length||b[0].tags.includes`tips`||b[0].closed_date)f();else console.log(b[0].link)})

```

```
f=_=>fetch(`//api.stackexchange.com/2.2/questions/${new Date%2e4}?site=codegolf`).then(_=>_.json()).then((a,b=a.items)=>{if(!b.length||b[0].tags.includes`tips`||b[0].closed_date)f();else console.log(b[0].link)})

f();
```

# Answer
> 2 votes
# Python 3, ~~452~~ 339 bytes

```
from requests import*
from random import*
while 1:
    n=randrange(999999)
    r=get("http://api.stackexchange.com/questions/%d?site=codegolf"%n).json()
    if r["items"]:
        m=r["items"][0]
        if "tips" not in m["tags"]:
            try:m["closed_date"]
            except:print("http://codegolf.stackexchange.com/q/%d"%n);break

```

A bit unsightly and not very golf-y, but I couldn't figure out a better way to do it. Since this more or less brute-forces the API, you'll spend up your quota quite quickly and start getting errors, but after a few hours it'll work again.

EDIT: Saved 113 bytes by removing multiple unnecessary things, thanks to NoOneIsHere.

# Answer
> 1 votes
# SEDE SQL: 79 bytes

```
Select Id from posts where ClosedDate IS NULL AND Tags !='tips' ORDER BY RAND()

```

There are 2 catches. One you have to wait for a while before running again or you have a cache hit (as a mod told me) and you only get the question id number.

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


title: Visualise Bit Weaving

text:
# Question
Title: Visualise Bit Weaving
The esoteric programming language evil has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

* Bit 0 is moved to bit 2
* Bit 1 is moved to bit 0
* Bit 2 is moved to bit 4
* Bit 3 is moved to bit 1
* Bit 4 is moved to bit 6
* Bit 5 is moved to bit 3
* Bit 6 is moved to bit 7
* Bit 7 is moved to bit 5

For convenience, here are two other representations of the permutation. As a cycle:

```
(02467531)

```

And as a list of pairs of the mapping:

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

```

Your task is to visualise this permutation, using the box-drawing characters , , , , , ,  (Unicode code points: U+2500, U+2502, U+250C, U+2510, U+2514, U+2518, U+253C). This visualisation should satisfy the following constraints:

The first and last line are exactly:

```
0 1 2 3 4 5 6 7

```

Between those, you can use as many lines as you want of up to 15 characters each to fit your box drawing characters (you will need at least 4 lines). The lines should start vertically beneath one of the digits on the first row and end vertically above the corresponding digit on the last row. The eight lines must be connected, and may only cross via  (which is always a crossing, never two turning lines which are touching). The exact paths of the lines are up to you (and finding a particularly golfable layout is the core of this challenge). One valid output would be:

```
0 1 2 3 4 5 6 7
│ │ └─┼┐│ │ └┐│
└─┼─┐ ││└─┼─┐││
┌─┘ │ ││  │ │││
│ ┌─┼─┘│  │ │││
│ │ │ ┌┼──┘ │││
│ │ │ │└┐ ┌─┼┼┘
│ │ │ │ │ │ │└┐
0 1 2 3 4 5 6 7

```

However, any other layout that correctly connects the right digits is fine too. Please show your chosen output in your answer.

You may write a program or function and will not take any input. Output the diagram either to STDOUT (or closest alternative) or as a function return value in the form of a string or a list of strings (each representing one line).

Standard rules apply, so the shortest code (in bytes) wins.

# Answer
## Actually, 69 bytes

```
"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+8r' j;)

```

Try it online! (the alignment is a little messed up in the online interpreter)

Actually has a **HUGE** advantage here - all of the box drawing characters are in CP437, so they're only a byte each. Though each character needed could theoretically be encoded in 4 bits (since there are only 9 unique characters), the 31 bytes saved by compressing the string would be lost due to Actually's very poor string processing capabilities. This also means that any 8x4 configuration would result in the same score. Since 8x4 appears to be the (vertically) shortest possible configuration, this is optimal.

Thanks to Martin for 3 bytes!

Thanks to TimmyD for 4 more bytes!

Explanation:

```
"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+8r' j;)
"│ ┌┘│ │└┐ │└┐└┐""┌┘└┼┐└┼┐ └┼┐└┐""└┼┐│└┐┌┘└┐┌┘│""┌┼─┘"3*"│┌┘"+         push the individual lines, using string multiplication to shorten repeated sections
                                                              8r' j   push the string "0 1 2 3 4 5 6 7" (range(8), join on spaces)
                                                                   ;)  make a copy and move it to the bottom of the stack

```
> 13 votes

# Answer
## PowerShell v2+, ~~172~~ ~~153~~ ~~148~~ ~~145~~ ~~142~~ ~~131~~ 123 bytes (81 chars)

```
($a=""+0..7)
$b='┌┘'
"│$b$('┌┼─┘'*3)
└┼┐$('│└─┐'*3)
$b$('└┼─┐'*3)│
│ $($b*6)│"
$a

```

I golfed the weaving further, eliminating the need for several variables by using inline code blocks. This is probably within a few bytes of optimal.

We start by setting `$a` equal to the range `0..7` that's been joined together with spaces. This is because the default `$ofs` (Output Field Separator) for an array is a space, so when the array is stringified with `""+` (with an operator like this, PowerShell will try to implicitly cast the right-hand object as the left-hand object), the result is the range space-separated.

That's encapsulated in parens, which adds the result onto the pipeline. We then setup a one helper variable `$b`, followed by four lines of output with the appropriate variable in place (split with literal newlines), and using inline code-blocks for repeat sections, followed by `$a` again. The four lines and `$a` are also placed on the pipeline, and output is implicit at the end.

```
PS C:\Tools\Scripts\golfing> .\visualize-bit-weaving.ps1
0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7

```
> 21 votes

# Answer
# Javascript ES6, ~~168~~ 167 bytes

Edit: Whoops, turned out I was using the pipe `|` char instead of U+2502  in part of the function, updated byte count.

```
_=>((n=`0 1 2 3 4 5 6 7 `)+[...`6452301`].map(i=>`${(d=n=>`│ `.repeat(n))(i)}└┐│ ${r=d(6)}┌┼┘ ${r}│└┐ ${d(6-i)}`).join``+n).match(/.{16}/g).join`
`

```

Returns a string.

Output:

```
0 1 2 3 4 5 6 7
│ │ │ │ │ │ └┐│
│ │ │ │ │ │ ┌┼┘
│ │ │ │ │ │ │└┐
│ │ │ │ └┐│ │ │
│ │ │ │ ┌┼┘ │ │
│ │ │ │ │└┐ │ │
│ │ │ │ │ └┐│ │
│ │ │ │ │ ┌┼┘ │
│ │ │ │ │ │└┐ │
│ │ └┐│ │ │ │ │
│ │ ┌┼┘ │ │ │ │
│ │ │└┐ │ │ │ │
│ │ │ └┐│ │ │ │
│ │ │ ┌┼┘ │ │ │
│ │ │ │└┐ │ │ │
└┐│ │ │ │ │ │ │
┌┼┘ │ │ │ │ │ │
│└┐ │ │ │ │ │ │
│ └┐│ │ │ │ │ │
│ ┌┼┘ │ │ │ │ │
│ │└┐ │ │ │ │ │
0 1 2 3 4 5 6 7

```

---

Extra: Using @TimmyD's method, I have another 167 byte solution:

```
(n=`0 1 2 3 4 5 6 7
`,a=`│┌┘ `,b=`└┼─┐`,d=`┌┼─┘`,f=` │└┐`)=>[n,a,a,a,a,`
`,b,b,b,`└┼┐
┌┘`,d,d,d,`│
│`,f,f,f,` │
`,n].join``

```
> 11 votes

# Answer
## JavaScript (ES6), ~~137~~ 134 bytes

```
f=
_=>`0
│2525252
1 1 1 1
24242423525252 3 1 1 1 3 242424│
0`.replace(/\d/g,d=>`0 1 2 3 4 5 6 7,└┼┐,┌┘,│
│,│ , │`.split`,`[d])
;
o.textContent=f();
```

```
<pre id=o></pre>
```

As a bell-ringer I immediately recognised this as the first two rows of Plain Hunt Major (note that the linked image uses 1-8 instead of 0-7).
> 9 votes

# Answer
# Pyth - ~~119~~ ~~104~~ ~~100~~ 81 bytes

Extremely simple. (Its actually bytes this time).

```
js[KjdU8cX."sz¨ú¨ãÆhÆ?\ÕüÓ¼xFNøa"_G"│┌┘└┼─┐ "15K

```

Try it online here.

I also stole @TimmyD's output:

```
0 1 2 3 4 5 6 7
│┌┘ │┌┘ │┌┘ │ │
└┼─┐└┼─┐└┼─┐└┐│
┌┘┌┼─┘ └┐│┌┼─┼┘
│ │└┐ ┌─┼┘│└┐└┐
0 1 2 3 4 5 6 7

```
> 4 votes

# Answer
## MS-DOS Batch, 136 bytes

```
@echo 0 1 2 3 4 5 6 7
@echo ³ÚÙ ³ÚÙ ³ÚÙ ³ÚÙ
@echo ÀÅÄ¿ÀÅÄ¿ÀÅÄ¿ÀÅ¿
@echo ÚÙÚÅÄÙÚÅÄÙÚÅÄÙ³
@echo ³ ³À¿ ³À¿ ³À¿ ³
@echo 0 1 2 3 4 5 6 7

```

Using @TimmyD's output. This might work in Windows Batch too, but my code page there is CP850, not CP437.
> 3 votes

# Answer
# ///, 112 bytes (100 chars)

```
/8/0 1 2 3 4 5 6 7//9/│//A/└┐//B/┌┼┘/8/C/9 A9 A9 A9//D/9A 9A 9A 9/
AC
B B B B
DA
C 9
9 B B B 9
9 D
8

```

*Thanks @MartinEnder for -3 bytes!*
*Thanks @MartinEnder for -9 bytes!*
*Thanks @MartinEnder (OP) for pointing 15-char rule out*

Uses ~~@TimmyD's~~ @Marco's output

```
0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7
```
> 3 votes

# Answer
## MATLAB / Octave, ~~112~~ 109 bytes

```
a='0 1 2 3 4 5 6 7';d=['└┐│ ';'┌┼┘ ';'│└┐ '];e=repmat('│ ',3,1);[a;d d d d;e d d d e;a]

```

Output:

```
0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7

```

My code is based on the ouputs of @Dendrobium and @Neil.
> 3 votes

# Answer
**Python3, 209 bytes**

```
lambda s="0 1 2 3 4 5 6 7\n":s+"│┌┘ │┌┘ │┌┘ │ │\n└┼─┐└┼─┐└┼─┐└┐│\n┌┘┌┼─┘ └┐│┌┼─┼┘\n│ │└┐ ┌─┼┘│└┐└┐\n"+s

```

Returns a string.

Thanks to @Mego for saving 2 bytes!

Credits of the character body go to @TimmyD !
> 0 votes

# Answer
# Sprects, 99 bytes (87 chars)

```
$8
AC
BE
DA
C 9
9E 9
9 D
8$E B B B$D9A 9A 9A 9$C9 A9 A9 A9$B┌┼┘$A└┐$9│$80 1 2 3 4 5 6 7

```

Uses @Marco's output (replace every 16th character with a newline (regex: `(.{15}).` -\> `\1\n`)).

```
0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7
```
> 0 votes

# Answer
## Bash + GNU sed, 140 bytes

```
sed 'h
s/$/nxxxacnb b b bnyyycanc xxxcnc b b b cnc yyyc/
:
s/x/ac /
s/y/ca /
s/a/└┐/
s/b/┌┼┘/
t
y/cn/│\n/
G'<<<'0 1 2 3 4 5 6 7'

```

Output:

```
0 1 2 3 4 5 6 7
└┐│ └┐│ └┐│ └┐│
┌┼┘ ┌┼┘ ┌┼┘ ┌┼┘
│└┐ │└┐ │└┐ │└┐
│ └┐│ └┐│ └┐│ │
│ ┌┼┘ ┌┼┘ ┌┼┘ │
│ │└┐ │└┐ │└┐ │
0 1 2 3 4 5 6 7

```

Using @TimmyD's output: 142 bytes

```
sed 'h
s/$/npbcccnsurdddnbeeepnp bbbbbbp/
:
s/b/qt/
s/c/quot/
s/d/psor/
s/e/suor/
t
y/nopqrstu/\n─│┌┐└┘┼/
G'<<<'0 1 2 3 4 5 6 7'

```

Output:

```
0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7

```
> 0 votes

# Answer
# Tcl, 205 bytes

```
puts "[set B "0 1 2 3 4 5 6 7"]
│┌┘ │┌┘ │┌┘ └┐│
└┼┐ └┼─┐└┼──┐││
┌┘└─┐│ └┐│┌─┼┼┘
│ ┌─┼┘┌─┼┘│ │└┐
$B"

```

Try it online!

outputs

```
0 1 2 3 4 5 6 7
│┌┘ │┌┘ │┌┘ └┐│
└┼┐ └┼─┐└┼──┐││
┌┘└─┐│ └┐│┌─┼┼┘
│ ┌─┼┘┌─┼┘│ │└┐
0 1 2 3 4 5 6 7

```
> 0 votes

# Answer
# SOGL V0.12, 64 bytes

```
└┼─┐³
┘┌┼─┘²
┐│└─┐¹
┌┘┌┘┌┘⁰
│┌²┌┼─²¶└┼¹│└─¹¶┌┘³³³│¶│ ⁰⁰│”8δ@∑Q;O

```

Try it Here!

Pattern stolen from the powershell
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


# Question
Title: Compute the antipode of a point on curve
A curve is a set of points on a square grid such that each point has exactly two neighbors in the four-neighbor neighborhood and the points form a single connected component. That is, the graph induced by the points on a grid graph is isomorphic to a single cycle. "Induced" means that two points cannot touch in the input without being neighbors in the cycle.

An antipode of a vertex V in a graph is a vertex furthest away from V. The antipode is always unique on an even-length cycle (and every cycle on a grid graph is even-length). The distance shall be measured as induced by the cycle itself without respect for the underlying square grid.

Your input shall be an image of a curve. The curve will be marked out with a sequence of number sign characters (`#`) on a background out of space characters (). One of the points on the curve will be marked with the `P` character ("pode"). Your output shall be the same as the input except one curve point shall be replaced with `A` ("antipode").

You may assume the characters will be padded to a rectangular shape. You may assume the first and last row and column of input will be composed entirely of spaces (input is padded with background). Alternatively you may assume that the first and last row and column will each contain a curve point (input has minimum padding).

You may input and output this grid as a single newline-separated string, as an array of rows, or as a 2D array of individual characters. This choice shall be the same for the input and output. If your language allows this, you may output by modifying the input in place instead of returning the modified string or array.

Possible inputs:

```
P#    P##   #P#   #####      #####P# #######   #####P#########   #####P#########
##    # #   # #   #   #      #     # #     #   #             #   #             #
      ###   ###   ## ##      # ### # # ### #   # ### ### ### #   #             #
###                # # ###   # # # # # # # #   # # # # # # # #   #             #
# P#    ### ###    # ### #   # # ### ### # #   # # ### ### # #   #             #
## #    # ### #    #     #   # #         # #   # #         # #   #             #
 # #    P     #    ##### P   # ########### #   # ##### ##### #   #             #
 ###    #######        ###   #             #   #     # #     #   #             #
                             ###############   ####### #######   ###############

```

Corresponding outputs:

```
P#    P##   #P#   #A###      #####P# #A#####   #####P#########   #####P#########
#A    # #   # #   #   #      #     # #     #   #             #   #             #
      ##A   #A#   ## ##      # ### # # ### #   # ### ### ### #   #             #
###                # # ###   # # # # # # # #   # # # # A # # #   #             #
# P#    ### ##A    # ### #   # # ### ### # #   # # ### ### # #   #             #
## #    # ### #    #     #   # #         # #   # #         # #   #             #
 A #    P     #    ##### P   # ########### #   # ##### ##### #   #             #
 ###    #######        ###   #             #   #     # #     #   #             #
                             ###############   ####### #######   #########A#####

```

Vertex distances from the podes (modulo 10) (do not output these):

```
P1    P12   1P1   5A543      54321P1 9A98765   54321P123456789   54321P123456789
1A    1 3   2 2   4   2      6     2 8     4   6             0   6             0
      23A   3A3   32 01      7 109 3 7 109 3   7 901 789 543 1   7             1
321                1 9 543   8 2 8 4 6 2 8 2   8 8 2 6 A 6 2 2   8             2
4 P1    234 89A    0 876 2   9 3 765 543 7 1   9 7 345 987 1 3   9             3
56 2    1 567 9    9     1   0 4         6 0   0 6         0 4   0             4
 A 3    P     8    87654 P   1 56789012345 9   1 54321 56789 5   1             5
 654    1234567        321   2             8   2     0 4     6   2             6
                             345678901234567   3456789 3210987   345678901A10987

```

# Answer
> 5 votes
# Python 2, ~~333~~ ~~221~~ 215 bytes

*-17 bytes thanks to @JanDvorak*

```
g=input()
y=map(max,g).index('P')
x=g[y].index('P')
m=[k[:]for k in g]
v=x;w=y
while'#'in sum(m,[]):x,y,(v,w)=v,w,[(x+a,y+b)for a,b in((1,0),(-1,0),(0,1),(0,-1))if'#'==m[y+b][x+a]][0];m[w][v]='_'
g[w][v]='A'
print g

```

Try it online!

---

# Python 3, ~~402~~ ~~288~~ 282 bytes, String IO

```
g=[[*k]for k in open(0).read().split('\n')]
y=[max(k)for k in g].index('P')
x=g[y].index('P')
m=[k[:]for k in g]
v=x;w=y
while'#'in sum(m,[]):x,y,(v,w)=v,w,[(x+a,y+b)for a,b in((1,0),(-1,0),(0,1),(0,-1))if'#'==m[y+b][x+a]][0];m[w][v]='_'
g[w][v]='A'
print('\n'.join(map(''.join,g)))

```

Try it online!

---

Animation of the code running:

# Answer
> 4 votes
## JavaScript (ES6), ~~193~~ 181 bytes

```
f=s=>s==(`P#1P#21#12#221A`[r=`replace`](/.../g,([n,f,t])=>s=s[r](eval(`/([${n+=f}])([^]{${s.search`\n`}})?(?!\\1)[${n}]/`),m=>m[r](eval(`/^${f}|${f}$/`),t))),s)?s[r](/\d/g,`#`):f(s)

```

Version that provides a looping animation:

```
f=s=>s==(`#A#1#12#221AP#1P#2`[r=`replace`](/.../g,([n,f,t])=>s=s[r](eval(`/([${n+=f}])([^]{${s.search`\n`}})?(?!\\1)[${n}]/`),m=>m[r](eval(`/^${f}|${f}$/`),t))),s)?s[r](/\d/g,`#`):s
;setInterval(_=>i.value=f(i.value),1e3)
```

```
<textarea rows=10 cols=20 id=i style="font-family:monospace"></textarea>
```

# Answer
> 4 votes
# MATL, ~~43~~ 42 bytes

```
32-I#fbbJ*+!w3>y"&)yy-|&X<]vJQ2/)G65b&Zj&(

```

The code accepts an arbitrary amount of space padding in the first and last rows and columns. Input is a rectangular array of chars, using `;` as row separator. For example, the input

```
#####
#   #
## ##
 # # ###
 # ### #
 #     #
 ##### P
     ###

```

is represented as

```
['#####   ';
 '#   #   ';
 '## ##   ';
 ' # # ###';
 ' # ### #';
 ' #     #';
 ' ##### P';
 '     ###']

```

or, in one line (so it can be entered through STDIN),

```
['#####   '; '#   #   '; '## ##   '; ' # # ###'; ' # ### #'; ' #     #'; ' ##### P'; '     ###']

```

**Try it online!** Or verify the last four cases: **1**, **2**, **3**, **4** (these have been chosen because they have the most complicated curves; the last one has some space padding).

### Explanation

TL;WR: Complex numbers, lots of indexing, no convolution.

```
32-     % Implicitly input char matrix. Subtract 32. Space becomes zero
I#f     % 3-output find: pushes nonzero values, their row indices,
        % and their column indices, as column vectors
bb      % Bubble up twice, so row and column indices are on top
J*+     % Times 1j, add. This transforms row and column indices into
        % complex numbers, where real is row and imaginary is column
!       % Transpose into a row vector
w       % Swap, so vector of nonzero values is on top
3>      % Logical index of elements exceeding 3. ASCII codes of space,
        % '#' and 'P0 are 32, 35 and 80 respectively. Since 32 was
        % subtracted these became 0, 3 and 48. So the only entry with
        % value exceeding 3 is that corresponding to the original 'P'.
y"      % Do this as many times as the number of complex positions
        %   The stack now contains the vector of complex positions and an
        %   index into that vector. The index points to the complex position
        %   to be processed next.
  &)    %   Two-output reference indexing: pushes the indexed entry and
        %   a vector with the remaining entries. This pulls off the
        %   current complex position, which is initially that of 'P'
  yy    %   Duplicate top two elements, i.e. current position and vector
        %   of remaining positions
  -|    %   Absolute differences
  &X<   %   Index of minimum. Gives the index of the complex position
        %   that is closest to the current one. In case of tie (which
        %   only happens in the first iteration) it picks the first. The
        %   result is the index of the complex position to be processed in
        %   the next iteration. This index will be empty if this is the last
        %   iteration.
]       % End
        % The stack now contains the complex positions as individual
        % values, starting from 'P' and sorted as per the curve; plus two
        % empty arrays. These empty arrays have been produced by the last
        % iteration as the index for the "next" iteration and the array of
        % "remaining" complex positions
v       % Concatenate into a column vector. The empty arrays have no effect.
        % The resulting vector contains the sorted complex positions
JQ      % Push 1j and add 1
2/      % Divide by 2. This gives (1+1j)/2. When used as an index this is
        % interpreted as (1+end)/2. Since the length of the curve is even
        % this gives a non-integer number, which will be implicitly
        % rounded up (because of .5 fracctional part). As an example, for
        % length 32 this gives 16.5, which rounded becomes 17. Position 17
        % along the curve is the antipode of position 1
)       % Reference indexing. Gives the complex position of the antipode
G       % Push input char matrix again
65      % Push 65 (ASCII for 'A')
b       % Bubble up, so complex position is on top
&Zj     % Separate into real and imagimary parts, corresponding to row and
        % column indices
&(      % 4-input assignment indexing. This writes 'A' at the specified row
        % and column of the char matrix. Implicitly display

```

# Answer
> 0 votes
# Python 3, 421 bytes

```
l,e=len,enumerate
r=open(0).read()
n=lambda x:[(x[0]-1,x[1]),(x[0]+1,x[1]),(x[0],x[1]-1),(x[0],x[1]+1)]
p=a={(i,j):y for i,x in e(r.split('\n'))for j,y in e(x)}
t=l(r.split('\n'));s=l(r.split('\n')[0])
for i in a:p=[p,i][a[i]=='P']
w=[p]
while l(w)!=r.count('#')+1:
 for x in a:
  if x in n(w[-1])and a[x]!=' 'and x not in w:w+=[x]
a[w[(l(w)+1)//2]]='A';print('\n'.join(''.join(a[j,i]for i in range(s))for j in range(t)))

```

Try it online!

# Answer
> 0 votes
# Mathematica, ~~234~~ 223 bytes

```
(p=Position;v=p[#,"#"|"P"];n=Length@v;q=v[[#]]&;h=FindCycle[Graph[v,Join@@Table[If[Norm[q@i-q@j]==1,q@i<->q@j,Nothing],{i,n},{j,i-1}]]][[1,#,1]]&;ReplacePart[#,h@Mod[p[Table[h@x,{x,n}],p[#,"P"][[1]]][[1,1]]+n/2,n,1]->"A"])&

```

This code makes `v` be the vertex list for the graph: the indices of the `"#"` and `"P"`s. Then `n` is the length (necessarily even) and `q` extracts the input-th vertex (so ignoring the shape of the loop).

Then `h` is a function that builds the graph with vertices in `v` and undirected edges between vertices when the length of the difference of their index pairs is exactly 1 (so their difference is something like `{-1,0}` or `{0,1}`) and then finds a list of all cycles and provides the first (only) cycle (as a list of edges) and then takes the input-th edge and takes the first vertex making up that edge.

Using `h`, we can find the index of the `"P"` in the cycle, and go halfway around (using Mod to wrap around if we go past the bounds of the cycle list) to find the antipode, and then we can replace the corresponding entry of the original input `m` with `"A"`

You can **try it online** with by pasting the following at the Wolfram Cloud Sandbox and clicking "evaluate cell" or hitting Shift+Enter or Numpad Enter:

```
(p=Position;v=p[#,"#"|"P"];n=Length@v;q=v[[#]]&;h=FindCycle[Graph[v,Join@@Table[If[Norm[q@i-q@j]==1,q@i<->q@j,Nothing],{i,n},{j,i-1}]]][[1,#,1]]&;ReplacePart[#,h@Mod[p[Table[h@x,{x,n}],p[#,"P"][[1]]][[1,1]]+n/2,n,1]->"A"])&@{{"#","#","#","#","#"," "," "," "},{"#"," "," "," ","#"," "," "," "},{"#","#"," ","#","#"," "," "," "},{" ","#"," ","#"," ","#","#","#"},{" ","#"," ","#","#","#"," ","#"},{" ","#"," "," "," "," "," ","#"},{" ","#","#","#","#","#"," ","P"},{" "," "," "," "," ","#","#","#"}}//MatrixForm

```

## Alternative idea, 258 bytes

Slightly inspired by ovs's Python solutions, I tried to write code that would not use any graph theory features of Mathematica and just blindly calculate the distances. I couldn't get it as short, but suspect someone could improve it:

```
f[m_]:=(x="#";t=ReplacePart;p=Position;l=t[m,p[m,"P"][[1]]->0];v=p[l,x|0];n=Length[v];q=v[[#]]&;r=l[[q[#][[1]],q[#][[2]]]]&;y=t[l,q@#->(r@#2+1)]&;Do[If[Norm[q@i-q@j]==1&&Xor[r@i==x,r@j==x],If[r@i==x,l=y[i,j],l=y[j,i]]],n,{i,n},{j,n}];t[m,p[l,n/2][[1]]->"A"])`

```

This code is very inefficient. Basically, it replaces `"P"` with `0` and then looks for a `"#"` next to something that's not a `"#"` by looping through the entire thing twice and replaces them with numbers representing the distance from `"P"`, and to make sure it finishes, it does that process `n` times. This actually doesn't even calculate distances correctly since one branch could go past the antipode, but only one location will be numbered with `n/2` no matter what.

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


title: Divisibility of numbers

text:
# Question
Title: Divisibility of numbers
# Challenge

HP is doing research in mathematics . After doing lots of research, she struck in a problem . She found four numbers n,a, b and c .Now, She wants to know how many number exists which are less than or equal to n and are divisible by a ,b or c .

# Input :

4 integers denoting `n,a,b and c` separated by space

# Output :

intger which denotes the count of the numbers which are divisible `a,b,c`

## Scoring:

This is , shortest code in bytes wins.

# Answer
> 0 votes
# Python 2, ~~72~~ 65 bytes

*Note:* This solution works for *positive* integers:

```
lambda a,b,c,n:len([x for x in range(1,n+1)if x%a*(x%b)*(x%c)<1])

```

Try it online!

# Answer
> 0 votes
# Python 2, 52 bytes

```
lambda n,a,b,c:n/a+n/b+n/c-n/a/b-n/a/c-n/b/c+n/a/b/c

```

Try it online!

By the inclusion–exclusion principle.

---
Tags: code-golf
---


title: Raindrops are falling on my... glasses?

text:
# Question
Title: Raindrops are falling on my... glasses?
I live in the UK, where it rains. A lot. I also have the unfortunate necessity to need to wear glasses to see, which means that when it rains (as it is now), I can barely see out of them. This challenge is so that you can all experience the same!

## Task

Output ASCII art glasses with a drop of water added each second.

## Input

None

## Output

A pair of glasses with drops of water on them.

### Glasses

```
 ________________________
|          /__\          |
|         /    \         |
|        /      \        |
\_______/        \_______/

```

### Raindrops

A raindrop is denoted by a `.`. A raindrop is randomly placed on the glasses' lenses. So when a raindrop is placed, the glasses might look like this

```
 ________________________
|          /__\          |
|    .    /    \         |
|        /      \        |
\_______/        \_______/

```

If it is placed on a blank space (), an `.` is placed on the image. If it is placed on a square which already has a raindrop, the drop graduates.

The steps on drops are

* no drops placed:
* 1 drop placed: `.`
* 2 drops placed: `o`
* 3 drops placed: `O`
* 4+ drops placed: `@`

## Rules

* The image should **look** as though it stays in place. This means that you can either clear the screen or print enough newlines to "clear" the screen. You cannot return a list of steps. Sorry about this, but you should be able to work around that.
* When outputting newlines to "clear" the screen, you must have at least 3 newlines between the glasses.
* The code runs until the glasses are full of fully graduated drops i.e. until the output looks like this:

```
     ________________________
    |@@@@@@@@@@/__\@@@@@@@@@@|
    |@@@@@@@@@/    \@@@@@@@@@|
    |@@@@@@@@/      \@@@@@@@@|
    \_______/        \_______/

```
* Shortest code in *bytes* wins.

# Answer
> 11 votes
## JavaScript (ES6), ~~269~~ ~~267~~ 265 bytes

```
document.write('<pre id=o>')
a=[...` _8_8_8
| 9 /__\\  9|
| 9/ 4\\ 9|
| 8/ 6\\ 8|
\\_7/ 8\\_7/`.replace(/.\d/g,s=>s[0].repeat(s[1]))]
s=" .oO@@"
g=_=>o.innerHTML=a.join``
f=(i=s.indexOf(a[j=Math.random()*a.length|0])+1)=>i?g(a[j]=s[i]):f()
g()
setInterval(f,1e3)
```

Edit: Saved ~~2~~ 4 bytes thanks to @Shaggy.

# Answer
> 5 votes
# Java 8, ~~449~~ ~~421~~ 420 bytes

```
v->{String q="########",g=" ________________________\n|##"+q+"/__\\##"+q+"|\n|#"+q+"/    \\#"+q+"|\n|"+q+"/      \\"+q+"|\n\\_______/        \\_______/\n\n\n";for(int t=0,n,x;g.matches("(?s).*[#\\.oO].*");Thread.sleep(150)){for(;(x=g.charAt(n=(int)(Math.random()*g.length())))!=35&x!=46&x!=111&x!=79;);g=t++>0?g.substring(0,n)+(x<36?".":x<47?"o":x<80?"@":"O")+g.substring(n+1):g;System.out.println(g.replace('#',' '));}}

```

-1 byte thanks to *@ceilingcat*.

**Explanation:**

Try it here. (`Thread.sleep` is removed so you instantly see the result.)

```
v->(){                      // Method without empty unused parameter and no return-type
  String q="########",g=" ________________________\n|##"+q+"/__\\##"+q+"|\n|#"+q+"/    \\#"+q+"|\n|"+q+"/      \\"+q+"|\n\\_______/        \\_______/\n\n\n";
                            //  The glasses (with inner spaces replaced by '#')
  for(int t=0,n,x;          //  Index integers
      g.matches("(?s).*[#\\.oO].*");
                            //   Loop (1) as long as the glasses still contain "#.oO"
      Thread.sleep(150)){   //   And sleep 150ms after each iteration to give the animation
    for(;                   //   Inner loop (2)
         (x=g.charAt(n=(int)(Math.random()*g.length())))!=35&x!=46&x!=111&x!=79;
                            //    To find the next '#', '.', 'o' or 'O' randomly
    );                      //   End of inner loop (2)
    g=t++>0??               //   Flag so it prints the initial glasses without a raindrop
      g.substring(0,n)+(x<36?".":x<47?"o":x<80?"@":"O")+g.substring(n+1):g;
                            //    Add a raindrop on this random position
    System.out.println(g    //   And print the glasses
        .replace('#',' ')); //   After we've replaced '#' with spaces
  }                         //  End of loop (1)
}                           // End of method

```

**Output:**

NOTE: The dots are a bit weird in the gif, but that's a problem in my ScreenToGif.exe..

# Answer
> 3 votes
# F#, non-recursive ~~379~~ ~~414~~ 404 bytes

```
open System
let z=String.replicate
let mutable s,d=z 54" ",new Random()
while Seq.exists((<>)'@')s do printfn" %s\n|%s/__\\%s|\n|%s/    \\%s|\n|%s/%7s%s|\n\\_______/%9s_______/\n\n"(z 24"_")(s.[..9])(s.[10..19])(s.[20..28])(s.[29..37])(s.[38..45])"\\"(s.[46..53])"\\";Threading.Thread.Sleep(1000);d.Next54|>fun i->s<-(s.[i]|>function|' '->"."|'.'->"o"|'o'->"O"|_->"@")|>(fun c->s.Remove(i,1).Insert(i,c))

```

Try it online!

* -7 bytes thanks to @vzwick
    + by aliasing String.replicate
    + by opening System instead of referencing it every time
* -3 bytes by reducing the while loop to one line

I love the premise of this challenge :)

And thanks for the earworm.

# F#, ~~406~~ ~~441~~ ~~438~~ ~~437~~ 423 bytes

```
open System
let z=String.replicate
let s,d=z 54" ",new Random()
let rec(!)s=s="";printfn" %s\n|%s/__\\%s|\n|%s/    \\%s|\n|%s/%7s%s|\n\\_______/%9s_______/\n\n"(z 24"_")(s.[..9])(s.[10..19])(s.[20..28])(s.[29..37])(s.[38..45])"\\"(s.[46..53])"\\";Threading.Thread.Sleep(1000);if Seq.exists((<>)'@')s then d.Next 54|>fun i-> !((s.[i]|>function|' '->"."|'.'->"o"|'o'->"O"|_->"@")|>(fun c->s.Remove(i,1).Insert(i,c)))else()
!s

```

Try it online!

* -3 bytes by constraining s to string by comparing it with string
* -1 byte, function name is now "!" saving a single space when calling it
* -7 bytes thanks to @vzwick
    + by aliasing String.replicate
    + by opening System instead of referencing it every time
* -1 byte, no need for parenthesis when calling d.Next
* -6 bytes, function is now one line

# Explanation

```
open System
let z = String.replicate    // define alias
let s, d = z 54 " ", new Random() // s holds a flat representation of the glasses.. glasses
let rec(!) s =
    s=""; // type s to string
    printfn" %s\n|%s/__\\%s|\n|%s/    \\%s|\n|%s/%7s%s|\n\\_______/%9s_______/\n\n"
        (z 24 "_")     // top of the glasses
        (s.[..9])      // slice
        (s.[10..19])   // and
        (s.[20..28])   // dice
        (s.[29..37])   // the
        (s.[38..45])   // glasses
        "\\"           // \ gets prepended with 6 spaces thanks to %7s
        (s.[46..53])
        "\\";          // same deal, just 8 spaces this time
    Threading.Thread.Sleep(1000);
    if Seq.exists((<>)'@') s then // if not everything's totally covered
        d.Next 54                 // get new random int < 54 (string has indices 0-53)
        |> fun i->                // passing is shorter than a let binding, saves two spaces and a new line
            !(                    // call the function again with new drop on glasses
              (s.[i]              // get part of the glasses drop fell on
              |>function
              |' '->"."           // promote drop
              |'.'->"o"
              |'o'->"O"
              |_->"@")
              |>(fun c-> s.Remove(i,1).Insert(i,c))) // and insert this in the string
    else ()
!s

```

# Answer
> 3 votes
# Python 2, ~~365~~ 328 bytes

That's a bit better...

```
import time,random
g=' '+'_'*24+r"""
|xxX/__\Xxx|
|xX/    \Xx|
|X/      \X|
\_______/        \_______/""".replace('X','x'*8)
while 1:
 print'\n'*3+g.replace('x',' ')
 s='x.oO@@'
 if all(c not in g for c in s[:-2]):exit()
 i,c=random.choice([(i,s[s.index(j)+1])for i,j in enumerate(g)if j in s])
 g=g[:i]+c+g[i+1:]
 time.sleep(1)

```

**Try it online**

The above link uses 30 lines instead of 3, but you can see it with 3 if you resize your browser window to be small enough vertically. Change `time.sleep(1)` to `time.sleep(.1)` for 10x speed.

# Answer
> 2 votes
# Ruby, 237 224 228 218 206 198 197 bytes

```
g=" #{?_*24}
|x##/__ax##|
|x#/    ax#|
|x/      ax|
a#{u=?_*7}/xa#{u}/

".gsub ?x,?#*8;217.times{|t|puts g.tr('#a',' \\');()while t<216&&g[x=rand*106]!~/[#.oO]/;g[x]=g[x].tr '#.oO','.oO@';sleep 1}

```

Try it online!

Previous answer was wrong, it did not take into account a raindrop falling on a @. Apparently not a requirement. Some bytes saved.

This terminates with an error thrown, but this definitely terminates as soon as the full glasses are printed.

* Saved 13 bytes by putting the printing into a lambda, and changing the assignment to use tr (duh)
* 8 bytes loss with the 1 second requirement.
* 10 bytes gain by using the gsub trick instead of interpolation (seen & adapted from mbomb007's Python answer).
* 12 bytes gain by removing the lambda printing now that the print is written only once \>.\>
* 1 byte gain by making all the `\\` be `a`, then changing back inside the tr
* 7 byte gain by putting the changing the spaces on the last line with another `x` (duh). In case some of you guys are wondering why this doesn't affect the main loop : the main loop doesn't consider the last line to determine its `x`.
* 1 byte gain by removing the  at the end of the top of the glasses

Yay \< 200 bytes :D

Gif :

# Answer
> 2 votes
# C, ~~313~~ ~~309~~ ~~305~~ 304 bytes

Needs to be golfed down quite a bit;

```
c;f(r,q){for(char*m=" ________________________\n|**********/__\\**********|\n|*********/    \\*********|\n|********/      \\********|\n\\_______/        \\_______/\n";c<216;r=rand()%144,m-=135)for(system("clear");*m++;putchar(*m^42?*m:32))q=--r?*m:*m^42?*m^46?*m^111?*m^79?*m:64:79:111:46,c+=q!=*m,*m=q;}

```

I run it with the following test stub

```
main()
{
    srand(time(0));
    f();
}

```

# Answer
> 1 votes
## Mathematica, 438 bytes

```
f=Flatten;p=Print;z=32;q=95;l=124;t=Table;v=z~t~8;s={f@{z,q~t~24,z},f@{124,z~t~10,47,q,q,92,z~t~10,l},f@{l,z~t~9,47,z~t~4,92,z~t~9,l},f@{l,v,47,z~t~6,92,v,l},f@{92,q~t~7,47,v,92,q~t~7,47}};c=0;Monitor[While[c<54,a=s[[i=RandomInteger@{2,4},j=RandomChoice[Range[2,13-i]~Join~Range[14+i,25]]]];If[a==z,s[[i,j]]=46,If[a==46,s[[i,j]]=111,If[a==111,s[[i,j]]=48,If[a==48,s[[i,j]]=64]]]];c=Count[Flatten@s,64];Pause@1],Column@FromCharacterCode@s]

```

here is a 10x speed result gif

# Answer
> 1 votes
# Bash, ~~576~~ ~~510~~ ~~429~~ 416 Bytes

```
j()(IFS=
printf "$*")
for i in {53..0};{ a[$i]=
b[$i]=@;}
while(($i == 0));do clear
echo  " ________________________
|`j ${a[@]::10}`/__\\`j ${a[@]:10:10}`|
|`j ${a[@]:20:9}`/    \\`j ${a[@]:29:9}`|
|`j ${a[@]:38:8}`/      \\`j ${a[@]:46}`|
\_______/        \_______/"
[ `j ${a[@]}` = `j ${b[@]}` ]&&{
i=1
}
sleep 1
d=`shuf -i0-53 -n1`
c=${a[$d]}
case $c in  )a[$d]=.;;.)a[$d]=o;;o)a[$d]=0;;0)a[$d]=@;esac
done

```

Wow, golfed a lot. If anyone have any idea for further golfing, I'm open to suggestions

Try it yourself! It has the sleep commented because of the 60 seconds limit

Here is the gif:

# Answer
> 1 votes
## Perl, 167 bytes

**Note that `\x1b` is a literal escape character.**

```
$_="\x1bc 24_
|10X/__\\10X|
|9X/4 \\9X|
|8X/6 \\8X|
\\7_/8 \\7_/
";s/\d+(.)/$1x$&/ge;do{$a[rand 54]++,sleep print s/X/($",".",o,O)[$a[$-++%54]]||"@"/ger}while grep$_<4,@a

```

See it online!

# Answer
> 0 votes
# PHP, ~~262~~ 254 bytes

```
for($t=" 8_8_8_
|Y9Y/__\Y9Y|
|9Y/4 \9Y|
|8Y/6 \8Y|
\\7_/8 \\7_/";$c=$t[$i++];)$s.=$c<1?$c:str_repeat($t[$i++],$c);for(;$c=$s[++$k];)$c!=Y?:$s[$m[]=$k]=" ";for(;$u<216;print str_pad($s,999,"
",sleep(1)))$u+=($c=".oO@"[$a[$p=rand(0,53)]++])&&$s[$m[$p]]=$c;

```

Run with `-nR` or try it online.

**breakdown**

```
# prep 1: generate template from packed string
for($t=" 8_8_8_\n|Y9Y/__\Y9Y|\n|9Y/4 \9Y|\n|8Y/6 \8Y|\n\\7_/8 \\7_/";
    $c=$t[$i++];)$s.=$c<1?$c:str_repeat($t[$i++],$c);
# prep 2: map substituted spaces and replace with real spaces
for(;$c=$s[++$k];)$c!=Y?:$s[$m[]=$k]=" ";
# loop until glasses are fully wet:
for(;$u<216;
    # 4. print glasses prepended with 865 newlines
    print str_pad($s,999,"\n",
    # 3. wait 1 second
        sleep(1)))
    $u+=($c=".oO@"[
        $a[$p=rand(0,53)    # 1. pick random position
        ]++])               # 2. and increment
        &&$s[$m[$p]]=$c         # if not fully wet, graduate drop
    ;                           # and increment drop count ($u+=)

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity, random, animation
---


title: Grocery Store Micromanagement

text:
# Question
Title: Grocery Store Micromanagement
You are an employee at the hip new grocery store Half Foods, and it's the day before ~~Thanksgiving~~ ~~Christmas~~ Easter. Since the store will be packed with customers rushing to get their foodstuffs, the store needs a traffic manager to send everyone to the appropriate lines. Being lazy, you'd like to automate this so that you can go hit the deli before everyone takes all the ~~turkey~~ ~~ham~~ whatever. However, all you have with you is your phone, and coding long programs on it is a real pain -- so you need to bust out your ninja skills.

## Challenge

Let's visualize the grocery store on a two-dimensional grid. Here's a sample grid to dissect:

```
                             e
                             s
                             s
                             s
                               Y

#           #                #s           #
#s          #                #s           #
#s          #                #s           #
#s          #s               #s           #
#3          #1               #4           #
 x           x                x            x

```

The grid starts out with an `e`, which represents an "outlet" to the rest of the store. Every generation, all of the outlets in the grid spawn a shopper (`s`) directly below. The shoppers move downward each generation until they reach you (`Y`). When a shopper reaches the same row as you, you must teleport the shopper to the beginning of the line with the least amount of shoppers in it. A shopper immediately moves to the line when they would move into the row with the `Y`, there is no generation in between. The lines are represented by the `#`s -- the column after the `#`s is a line. The shoppers go down to the end of the line (represented by an exit `x`), and then turn into a random number between `1` and `5`. Each generation, you must decrement numbered shoppers by `1` -- when a shopper would reach `0`, they're done checking out and they leave the store.

Given an input of a grid like this, output the next generation of the grocery store (move all the shoppers down simultaneously, redirect shoppers, and have them leave if they are done).

## Samples

Input:

```
                e

                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
 x           x                x            x

```

Output:

```
                e
                s
                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
 x           x                x            x

```

Input:

```
                e
                s
                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
 x           x                x            x

```

Output

```
                e
                s
                     Y

#s          #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
 x           x                x            x

```

Input:

```
                e

                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#s          #                #            #
#           #                #            #
 x           x                x            x

```

(Possible) Output:

```
                e
                s
                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#3          #                #            #
 x           x                x            x

```

Input:

```
                e
                s
                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#3          #                #            #
 x           x                x            x

```

Output:

```
                e
                s
                     Y

#           #s               #            #
#           #                #            #
#           #                #            #
#           #                #            #
#2          #                #            #
 x           x                x            x

```

Input:

```
                e

                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#1          #                #            #
 x           x                x            x

```

Output:

```
                e
                s
                     Y

#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
#           #                #            #
 x           x                x            x

```

This is , so shortest code wins.

# Answer
# Python 2, ~~477~~ ~~463~~ ~~453~~ ~~449~~ ~~423~~ ~~402~~ ~~397~~ ~~396~~ 393 bytes

```
t=input()
e=enumerate
q,r=" s"
for i,L in list(e(t))[:0:-1]:
 for j,c in e(L):
	a=t[i-1][j]
	if"0"<c<"6":L[j]="0 1234"[int(c)]
	if(r==a)*q==L[j]:t[i-1][j],L[j]=q+r
	if"e"==a:L[j]=r
	if r==L[j]and"x"==t[i+1][j]:L[j]="5"
 if"Y"in L:x=L.count(r);t[i]=[p.replace(r,q)for p in L]
for i,l in list(e(t))[::-1]:
 for j,c in e(l):
	if"#"==c and(q==l[j+1])*x:x-=1;l[j+1]=r
print"\n".join(map("".join,t))

```

Try it online!

Still working on golfing this but it solves the problem for now
> 4 votes

# Answer
## C++, ~~898~~ ~~896~~ ~~885~~ 841 bytes

Very long to code... but it's there

-2 bytes thanks to Conor O'Brien
-45 byte thanks to Zacharý

```
#include<vector>
#include<string>
#include<algorithm>
#include<ctime>
#define B begin()
#define L length()
#define C(e)if(i[j].find(e)!=string::npos&&!
#define S's'
#define T size()
#define U i[x][a]
using namespace std;auto g=[](auto&i){int e=i[0].find('e'),n=0,y=0,h=0,o,j,c,x,t=0;for(auto&a:i)t=a.L>t?a.L:t;for_each(i.B,i.end(),[&i,t](string&s){s.resize(t);});srand(time(0));vector<int>s,l;for(j=0;j<i.T;++j){C(S)y)++n;C(89)0)y=j;C(35)h){h=j;for(int d=0;d<i[j].T;++d)if(i[j][d]==35)l.push_back(d+1);s.resize(l.T);}if(h)for(c=0;c<l.T;c++)if(i[j][l[c]]!=32)++s[c];C('x')0)x=j;}--x;for_each(l.B,l.end(),[&i,&x,h](int&a){if(U!=32)--U;if(U==10)U=32;for(int b=x;b>h;--b){if(i[b][a]==32&&i[b-1][a]==S){i[b][a]=S;i[b-1][a]=32;}}if(U==S)U=49+rand()%5;});if(i[y-1][e]==S)i[h][l[min_element(s.B,s.end())-s.B]]=S;for(j=1;j<n+2;++j)if(j<y)i[j][e]=S;};

```

So... some details :

* You have to pass a `std::vector<std::string>` ( they will be resized at the same length the longest string is )
* All lines of `#` starts at the same y ( vertical ) coordinates, are the same length, and end at the same y ( vertical ) coordinates
* Assume that the grid have at least 1 `#` line or more, have one letter `e` ( one outlet ) at the top, one letter `Y`
* Assume that the input is a valid output so the shoppers waiting to be redirected will always be one after another

Edit : Just saw in the comments of Wheat Wizard's answer that it should support multiple entrances, i will continue to work on that
> 4 votes

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


title: Octal Calculator with Primality check

text:
# Question
Title: Octal Calculator with Primality check
# Problem

Build an octal calculator that can do the following operations:

* Add (+)
* Subtract (-)
* Multiply (\*)
* Divide (/)
* Check is prime

Counting in octal is like this with decimal

```
(Octal)  (Decimal)
0        0
1        1
2        2
3        3
4        4
5        5
6        6
7        7
10       8
11       9

```

and so on...

So given input `a` `b` `c`

* `a` being a number in octal
* `b` being an operator (+, -, \*, /) not is prime
* `c` being a number in octal

Output the expression evaluated as `abc = Output (Is prime)`

Test cases:

`a=3, b='+', c=3 -> 6 (false)`

`a=5, b='+', c=5 -> 12 (false)`

`a=1, b='*', c=5 -> 5 (true)`

`a=7, b='+', c=6 -> 15 (true)`

`a=31, b='-', c=11 -> 20 (false)`

`a=25, b='/', c=3 -> 7 (true)`

# Rules:

* The output just needs to contain the answer and a truthy/falsey value of whether it is prime so `[4,0]` is fine.
* The inputs will always be a case that outputs an integer (integer division)
* This is code golf so shortest answer wins

When is an octal number a prime

# Answer
> 1 votes
# Mathematica, 38 bytes

```
{a=#@@(#~FromDigits~8&)/@#2,PrimeQ@a}&

```

Anonymous function. Takes input in the form `... &[Plus, {"7", "12"}]` (with both numbers as octal strings and the operator being `Plus`, `Subtract`, `Times`, or `Divide`) and returns output in the form `{17, True}` (with the number in decimal.) Did this based on my own, possibly incorrect, interpretation of the rules; please comment if I did something wrong.

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
‚8ö`³.VDps8B‚

```

Try it online!

Input format:

```
c
a
b

```

Output format:

```
[Is prime, 'Output']

```

Note that strings and numbers are equivalent datatypes in 05AB1E.

# Answer
> 0 votes
# JavaScript, 82 bytes

```
(a,b,c,k=m=eval((v=0)+a+b+v+c))=>{while(k-->3)m%k||(v=1);return[m.toString(8),!v]}

```

# JSFiddle

Input is in octal base, output is also in octal base.

# Answer
> 0 votes
# Python 2, ~~89~~ 67 bytes

*A whopping -22 bytes thanks to suggestions by Rod.*

```
n=eval(''.join(input()))
print[oct(n),all(n%i for i in range(2,n))]

```

Try it online!

Takes input as:

```
['01', '*', '05']

```

Prints a list like:

```
['05', True]

```

# Answer
> 0 votes
# Jelly, 12 bytes

```
Dḅ8jVµb8V,ÆP

```

Try it online!

Uses `×` for `*` and `÷` or `:` for `/` (approved by OP in chat).

Argument 1:

```
[a, c]

```

Argument 2:

```
b

```

Output:

```
[Output, Is prime]

```

# Answer
> 0 votes
# PHP, 104 bytes

```
for(eval("\$i=\$n=octdec($argv[1])$argv[2]octdec($argv[3])|0;");--$i>1&&$n%$i;);echo
decoct($n),_,$i==1;

```

Run with `-nr` or try it online.

Output format: `Result_1` for primes; `Result_` for non-primes.

Output for negative results is faulty; replace the `echo` part with `echo$n<0?-decoct(-$n):decoct($n),_,$i==1;` (+17 bytes) to fix.

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


title: Toggle the Box!

text:
# Question
Title: Toggle the Box!
Given a string that is potentially boxed in, toggle the box. This becomes clearer in the test cases and explanation.

# Input / Output

### Input Format

The input will be either a single string separated by CR, LF, or CRLF, or a list of strings. The input format is up to you to decide.

### Output Format

The output format must be in the same format as the input.

# Explanation + Example

Let's take a boxed string as an example:

```
+-------------+
|Hello, World!|
+-------------+

```

To toggle the box, we remove the first and last row and the first and last column. You may assume that there will be no trailing whitespace after the last line (with an optional trailing newline at the end of the last line), and no trailing whitespace on any line, not counting the newline of course.

This would become:

```
Hello, World!

```

# The Other Way

If the string is *not* in a box, add a box to it. This is fairly simple; prepend `+---...---+` on its own line with `k` dashes where `k` is the length of the longest line, and then for each line, pad it with trailing whitespace to match the length of the longest line and then prepend and append a pipe character (`"|"`). Finally, append a line containing the same `+---...---+` setup as the first line.

For example:

```
Hello, World!

```

becomes:

```
+-------------+
|Hello, World!|
+-------------+

```

You may assume that none of the lines in the input will have trailing whitespace.

Another example of a string that should have a box put around it:

```
Hello,
    World!

```

becomes

```
+----------+
|Hello,    |
|    World!|
+----------+

```

An example of something that should still be boxed:

```
+--------+
|        |
 --------+

```

becomes:

```
+----------+
|+--------+|
||        ||
| --------+|
+----------+

```

# Rules + Specifications

* Standard Loopholes Apply
* No line of input will have any leading or trailing whitespace both overall and in each line, regardless of whether or not it has been boxed in
* Boxes will only have `+` as their corners and `|` for the vertical edges and `-` for the horizontal sides.
* A box must have its pluses in place to be considered a box; if it has height or width 2 (that is, no content), it should still be unboxed, which would result in a bunch of newlines, depending on the height of the box.
* If the input has a box but text outside of the box, the whole thing should be boxed.
* Your program must check the entire perimeter of the string. If a single character along the outside is not correct (either missing or a different character than what it should be), then it should be boxed, not unboxed.
* The unboxed string itself may contain `+ | -`. If the unboxed string itself has a box around it, return the string with the box; it should only be unboxed once.

# Edge Cases

### 1: Small boxes

Input:

```
++
++

```

Output is a empty or a newline

Input:

```
+----+
+----+

```

Output is empty or a newline

Input:

```
++
||
||
++

```

Output is 2 newlines or 3 newlines

### 2: Partial Box

Input:

```
+-------+
| Hello |
+ ------+

```

Output:

```
+---------+
|+-------+|
|| Hello ||
|+ ------+|
+---------+

```

### 3: Text outside of box

Input:

```
 +-------+
a| Hello |
 +-------+

```

Output:

```
+----------+
| +-------+|
|a| Hello ||
| +-------+|
+----------+

```

# Answer
## JavaScript (ES2017), 199 bytes

```
s=>/^\+-*\+\n(\|.*\|\n)*\+-*\+$/.test(s,s=s.split`
`,s.map(z=>z[y]?y=z.length:0,y=0))?s.slice(1,-1).join`
`.replace(/.(.*)./g,"$1"):(x=`+${'-'.repeat(y)}+`)+`
|${s.map(z=>z.padEnd(y)).join`|
|`}|
`+x

```

The naive solution. May or not be the best, we'll see...
> 6 votes

# Answer
# SOGL V0.12, 72 bytes

```
2-┌* +1Ο;2-⁴┌@ŗΖ+|ŗ∙⁴++B
▓Aa1w⁄;lGB╬8a⁰I{_=}¹χ?ajk{jk}⁰←a1w⁄;l2+G2+B00╬5

```

Try it Here!

+7 bytes (`⁰I{_=}¹χ`) because elementwise equals isn't implemented
+1 byte ()because input isn't guaranteed to be square
+1 byte (`A`) for me being lazy and not implementing typed inputs (so this expects input on the stack. For ease-of-use, the online link includes → so the input box can be used)
> 3 votes

# Answer
# Jelly, 46 bytes

```
ẋ2jÐ€
z©⁶”|çZṖ”-çµḢ⁾-+yWWçWẎZ
ḊṖZḊṖÇ
Ỵ®2ĿÇ⁼$?Y

```

Try it online!
> 2 votes

# Answer
# Retina, ~~197~~ 195 bytes

```
+m`^((.)*)(¶(?<-2>.)*(?(2)$|(.)))
$1$#4$* $3$#2$*
%`^|$
|
^.(.*).
+$.1$*-+¶$&
.(.*).$
$&¶+$.1$*-+
^(\+-*\+)¶(\|\+-*\+\|)¶(\|\|.*\|\|¶)*\2¶\1$
¶$&¶
..(.*)..(?=(.|¶)*¶$)
$1
^¶-*¶-*¶|(\G|¶)-*¶-*¶$

```

Try it online! Explanation:

```
+m`^((.)*)(¶(?<-2>.)*(?(2)$|(.)))
$1$#4$* $3$#2$*

```

This stage is quite complicated in itself, so I'll break it down a bit. `+` means that the stage repeats until no more replacements can be found. `m`^` means that the stage matches at the start of any line. `((.)*)` then matches the whole line. Now `$1` is simply the matched line, but `$2` is a list of matches i.e. characters.  then matches the end of the line and therefore the start of the next line. `(?<-2>.)*` uses a .NET balancing group. The `<-2>` removes matches from `$2` as long as a character can be matched on the second line. At this point, one of three things can happen:

* There weren't enough characters on the second line. `$2` still has some matches left.
* The two lines were exactly the same length. `$2` has no matches left, and we are at the end of the line.
* The second line is longer, so there is at least one character left over.

`(?(2)$|(.)))` helps distinguish these using a condition. If `$2` still has some matches left, then we need this to be because the second line is too short, so we match the end of the line, but if `$2` has no matches left, then we want the second line to be longer, so we match a character (which goes into `$4` so that we know that the match happened). Otherwise the two lines are the same length and the match fails at this point (it might match again at a later line of course).

The replacement string is `$1$#4$* $3$#2$*`. The `$#4` evaluates to `1` if we matched an additional character on the second line, `0` if not. This means that `$#4$*` adds a space to the first line if the second line was longer. Similarly `$#2$*` adds spaces to the second line if the first line was longer. (In fact, it ends up adding exactly the right number of spaces. If we were only balancing two lines, a `+` could have been added to the fourth capture group to achieve this directly for the case of the longer second line too.)

The upshot of all this is that this stage pads out the input into a rectangle. We can now draw a box around it.

```
%`^|$
|

```

Place `|`s on each side.

```
^.(.*).
+$.1$*-+¶$&

```

Place `+-...-+` on the top.

```
.(.*).$
$&¶+$.1$*-+

```

And again on the bottom.

```
^(\+-*\+)¶(\|\+-*\+\|)¶(\|\|.*\|\|¶)*\2¶\1$
¶$&¶

```

See if we've created a double box. If so, extra blank lines are added at the top and bottom for the remaining stages to match to delete both boxes.

```
..(.*)..(?=(.|¶)*¶$)
$1

```

If there's a trailing blank line, remove two characters from the start and end of every line.

```
^¶-*¶-*¶|(\G|¶)-*¶-*¶$

```

If there's a leading blank line, delete it and the next two lines (which will be the `-`s remaining at the top of the box). If there's a trailing blank line, delete it and the previous two lines. The `(\G|¶)` deals with the case where there's only six lines (and therefore 5 s) because the box had no content.
> 2 votes

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


title: Work out change

text:
# Question
Title: Work out change
You are writing a program for an automatic cash register. The user needs change with the least number of coins used. Write a program which takes an amount (say $1.53) and gives change in US denominations - in this instance: 1 x one dollar note, 1 x fifty cents and 3 x one cent. The shortest program shall be the winner. Bonus points for supporting other currencies (i.e. UK denominations) and unusual currencies (1, 2, 3 cents?)

You have these US denominations: 1 cent, 5 cents, 10 cents, 25 cents, 50 cents, 1 dollar (note or coin), 2 dollars, 5 dollars, 10 dollars.

You have these UK denominations: 1 pence, 2 pence, 5 pence, 10 pence, 20 pence, 50 pence, £1, £2, £5 (note or coin), £10.

# Answer
### Windows PowerShell, 108 ~~111~~ ~~117~~

Very first attempt, ungolfed so far:

```
$i=+("$input"-replace'[^\d.]')
$args|%{0d+$_}|sort -des|%{$a=[math]::floor($i/$_)
if($a){$i-=$a*$_
"$a×$_"}}

```

Implementation notes:

1. Accepts the quantity to return via the pipeline
2. Accepts the list of currency denominations via the command-line
3. The quantity can be given with a currency sign; that will be stripped (in fact, anything non-numeric).
4. The list of denominations does not need to be sorted.
5. The program will output the largest change smaller than the requested quantity achievable with the given denominations, i.e. 1.5 for 1.53 if the 1-cent coin is missing.

If 3 and 4 do not need to be satisfied (i.e. *I* control the input format ;-)), then the following program suffices (71):

```
$i=+"$input"
$args|%{$a=[math]::floor($i/$_)
if($a){$i-=$a*$_
"$a×$_"}}

```
> 2 votes

# Answer
## Mathematica: 110 chars

```
Sort[IntegerPartitions[Rationalize@#,Infinity,{10,5,2,1,1/2,1/4,1/10,5/100,1/100}],
    Length@#1<Length@#2&][[1]]&

```

Usage

```
%[0.98]
{1/100, 1/100, 1/100, 1/10, 1/10, 1/4, 1/2}

```

Or

```
Tally@Sort[IntegerPartitions[Rationalize@#,Infinity,
                             {10,5,2,1,1/2,1/4,1/10,5/100,1/100}],
     Length@#1<Length@#2&][[1]]&

```

(6 chars more) gives

```
{{1/100, 3}, {1/10, 2}, {1/4, 1}, {1/2, 1}}

```

For other denominations, just change the rationals table {10,....,5/100,1/100}
> 2 votes

# Answer
# D: 225 Characters

```
import std.algorithm,std.conv,std.stdio;void main(string[]args){auto m=args[1].findSplit(".");void p(T,S)(T t,T u,S s){foreach(v;[u,10,5,1]){writefln("%s %s%s",t/v,v,s);t-=(t/v)*v;}}p(to!int(m[0]),20,"");p(to!int(m[2]),25,"/100");}

```

More Legibly:

```
import std.algorithm,std.conv,std.stdio;

void main(string[] a)
{
    auto m = a[1].findSplit(".");

    void p(T, S)(T t, T u, S s)
    {
        foreach(v; [u, 10, 5, 1])
        {
            writefln("%s %s%s", t / v, v, s);
            t -= (t / v) * v;
        }
    }

    p(to!int(m[0]), 20, "");
    p(to!int(m[2]), 25, "/100");
}

```

Only handles US currency. Takes the value as a floating point value on the command line (must have the leading 0 for values under 1 dollar). Does not accept $ as part of value. Outputs the number of each type of bill/coin on a separate line. E.g. an input of 1.53 results in:

0 20
0 10
0 5
1 1
2 25/100
0 10/100
0 5/100
3 1/100
> 2 votes

# Answer
# Mathematica, 51 bytes

```
#~NumberDecompose~{10,5,2,1,.5,.25,.1,.05,.01}&

```

input

> \[1.53\]

output

> {0, 0, 0, 1, 1, 0, 0, 0, 3.}

# Mathematica, 82 bytes --WITH BONUS--

```
(s=#~NumberDecompose~#2;Row@Flatten@Table[Table[#2[[i]]"+",s[[i]]],{i,Length@s}])&

```

**Input**

> \[37.6, {15, 7, 2.5, 1, 0.88, 0.2, 0.01}\]

**output**

> 15 +15 +7 +0.2 +0.2 +0.2 +
> 1 votes

# Answer
# Javascript, ~~84~~ 83 bytes

~~```
(n,v=[10,5,2,1,.5,.25,.1,.05,.01],l=[])=>{for(i in v)l[i]=n/v[i]|0,n%=v[i];return l}

```~~
```
(n,v=[10,5,2,1,.5,.25,.1,.05,.01],l=[])=>eval("for(i in v)l[i]=n/v[i]|0,n%=v[i];l")

```

Uses a greedy algorithm.
> 1 votes

# Answer
# APL (Dyalog), 19 bytes

Prompts for desired amount and then for denominations expressed in smallest unit (pennies/cents).

```
⎕CY'dfns'
⎕ stamps⎕

```

Try it online!

`⎕CY'dfns'`**C**o**p**y the `dfns` workspace

`⎕ stamps⎕` ask for inputs and use as arguments to the `stamps` function
> 0 votes

---
Tags: code-golf
---


title: Count to 20 with Words!

text:
# Question
Title: Count to 20 with Words!
Using the following length-separated lists of words:

https://github.com/Magic Octopus Urn/wordListsByLength

Print 1 word from each list of length `n` from 1 all the way up to 20, here's a valid example:

```
a
an
and
hand
hands
handle
handles
abandons
abandoned
understand
outstanding
newfoundland
understanding
characteristic
characteristics
characterization
characterizations
characteristically
characterologically
chemotherapeutically

```

Alternatively (array):

```
['a', 'an', 'and', 'hand', 'hands', 'handle', 'handles', 'abandons', 'abandoned', 'understand', 'outstanding', 'newfoundland', 'understanding', 'characteristic', 'characteristics', 'characterization', 'characterizations', 'characteristically', 'characterologically', 'chemotherapeutically']

```

Alternatively (any printable non-alphabetic separator other than `\n`):

```
a:an:and:hand:hands:handle:handles:abandons:abandoned:understand:outstanding:newfoundland:understanding:characteristic:characteristics:characterization:characterizations:characteristically:characterologically:chemotherapeutically

```

---

# Rules

* You may choose your own 20 words.
* The words must be from the github page provided, more specifically:
    + 1 from 1.txt, 1 from 2.txt, etc...
    + Note, files above 20.txt exist, but you do not need any words above 20 characters.
* Valid separators are ASCII-printable non-alphabetical characters (even numbers, don't care).
* Lowercase or uppercase only, pick one, stick with it; no title-case allowed.
* Please don't use a 100% copy of my example 20 words...
    + You can, but that's no fun.
    + *They are likely suboptimal anyways...*
* If you DON'T want to use the separated files, and need a full list:
    + Use unsorted.txt, this is all `n`.txt files in one, sorted alphabetically.
* Note, you CANNOT directly read from the URL, it is a common loophole.
* This is , lowest byte-count will be the winner.

---

*For reference, the output is 229 bytes, so anything that gets under that beats hardcoding.*

---

Possible meta-tag-discussion:

where the user gets to customize their outputs from a list of possibilities?

# Answer
> 19 votes
# Jelly,  ~~49 35 31~~  30 bytes

```
ṫ3,⁸Ṗ,$€ẎK
“¤ƈȮⱮ⁴⁷ọḤƁŒ|⁾Ė»ḲÇ€K

```

A niladic link returning a list of characters, or a full program printing that list as a string (the words delimited by spaces).

**Try it online!**

### How?

```
ṫ3,⁸Ṗ,$€ẎK - Helper link: list of characters, word    e.g. "abreacts"
ṫ3         - tail word from index 3                          "reacts"
   ⁸       - chain's left argument, word
  ,        - pair                               ["reacts","abreacts"]
      $€   - last two links as a monad for €ach of the two words:
    Ṗ      -   pop (all but last character)      "react" / "abreact"
     ,     -   pair       ["react","reacts"] / ["abreact","abreacts"]
        Ẏ  - tighten          ["react","reacts","abreact","abreacts"]
         K - join with spaces         "react reacts abreact abreacts"

“¤ƈȮⱮ⁴⁷ọḤƁŒ|⁾Ė»ḲÇ€K - Link: no arguments
“¤ƈȮⱮ⁴⁷ọḤƁŒ|⁾Ė»     - a compressed string using dictionary indexes:
                    -   "agar abreacts acknowledges codeterminations deindustrializations"
               Ḳ    - split at spaces
                Ç€  - call the last link (Helper) as a monad for €ach
                  K - join with spaces

```

...which yields:

```
a ar aga agar react reacts abreact abreacts knowledge knowledges acknowledge acknowledges determination determinations codetermination codeterminations industrialization industrializations deindustrialization deindustrializations

```

---

Previous:

@35:

```
“¡Ụıƭz Xj]"Ɱ*AJƤʂạ5ƬṚṪð^ƥỤ»ḲṖ,$€K€K

```

Using 10 words and their length-1 prefixes.

@49

```
“ḊAḥTz¹ỴH¡ṛYẈDƤNŀt#ñ²ĿĊḤlṪnð⁻U+ɦỴĊypṆQ0⁴ṄẉṂi⁻d¤&»

```

Simply 20 compressed words.

# Answer
> 27 votes
# Python 2, 145 bytes

```
print'i am now tiny @ @s##s#ed#act#acts#@#@s#@ed#@ing#arguments#accusation#accusations#advertisings'.replace('#',' counter').replace('@','check')

```

Try it online!

Prints these words, separated by spaces:

```
i
am
now
tiny
check
checks
counter
counters
countered
counteract
counteracts
countercheck
counterchecks
counterchecked
counterchecking
counterarguments
counteraccusation
counteraccusations
counteradvertisings

```

# Answer
> 15 votes
# PowerShell, ~~166~~ 163 bytes

```
'a
an
and'
'','s','le','ler','lers'|%{"hand$_"}
($a="character")
($x=-split"s ed ful ized istic istics ization izations istically ologically"|%{"$a$_"})
"un"+$x[8]

```

Try it online!

Hand-optimized, no algorithms. The two loops `|%{ }` tack on the appropriate ending to the appropriate beginning. I'm searching for a way to get them down into one loop.

# Answer
> 10 votes
# Python, 169 bytes

```
z='odahs princesses acclimatizers cyanocobalamines aerothermodynamics underrepresentations'.split()
print([y[:i+1]for x,y in zip(['']+z,z)for i in range(len(x),len(y))])

```

Prints a list of the words.

Try it online!

Words gained by scanning sequences of matching words, by start or end of the word and starting from length 1 upwards or from length 20 downwords.

Here is the script I used to get it. (the upward-start-matching one)

# Answer
> 8 votes
# Python 2,  ~~126 120~~  112 bytes

-8 bytes thanks to Anders Kaseorg (I thought I'd migrated this from Python 3, but turns out I'd forgotten!)

A port of my Jelly answer works well in Python too...

```
for w in"agar abreacts acknowledges codeterminations deindustrializations".split():print w[2:-1],w[2:],w[:-1],w,

```

**Try it online!**

Prints:

```
a ar aga agar react reacts abreact abreacts knowledge knowledges acknowledge acknowledges determination determinations codetermination codeterminations industrialization industrializations deindustrialization deindustrializations

```

# Answer
> 6 votes
# JavaScript, 159 bytes

```
_='a1an1and}}swwrwrs~~s~ed~ful~ized{{s~|~|s{ally~ologically1misx|s~1x}1hand|ization{~isticxcharacterw}le';for(i of'wx{|}~')with(_.split(i))_=join(pop());f=f=>_

```

Try it online!

Thanks @HyperNeutrino for edit. But, I am reverting back to old post (removing "Node.js" flag) because it has nothing to do with Node.js. It perfectly works in browsers too.

# Answer
> 6 votes
# 05AB1E, 51 bytes

```
’¯Óa‚‡’D“€…€¤Þ¨íÊƒé¢Ã¥£žÜ¶ß´ç…àçî×Ü»‡Ûà³ŒçÓs²® ÿ ÿs

```

Try it online!

Separator:

List of words: `a, an, ana, anal, house, houses, amazing, criminal, seriously, apparently, accessories, disciplinary, distributions, discrimination, congratulations, responsibilities, characterizations, telecommunications, representationalist, representationalists`

# Answer
> 5 votes
# Ruby, 120 bytes

```
j=3
$><<?a
"  5  T &  }   <    ".bytes{|i|puts
8.times{|k|$><<%w{dehydro chlori ge n at ion e s}[k]*(j>>7-k&1)}
j+=i-31}

```

Prints the following. Each word is built from the 8 strings above, using the binary digits of `j` to select. On each iteration of the loop, `j` is incremented by the ASCII value of the characters in the string in quotes, minus 31.

```
a
es
ion
ions
nates
nation
nations
chlorine
chlorines
chlorinate
chlorinates
chlorination
dehydrogenate
dehydrogenates
dehydrogenation
dehydrogenations
dehydrochlorinate
dehydrochlorinates
dehydrochlorination
dehydrochlorinations

```

# Answer
> 4 votes
# Pyth, 74 bytes

*Psychopathologically adventuresomenesses*

```
.e:"psychopathologicallyadventuresomenesses"b+bhkiR36"GGGGBKMMKKM6K6M0K0K0

```

Try it online! It outputs:

```
['a', 'al', 'all', 'ally', 'logic', 'advent', 'venture', 'ventures', 'adventure', 'adventures', 'venturesome', 'pathological', 'adventuresome', 'pathologically', 'venturesomeness', 'psychopathologic', 'adventuresomeness', 'psychopathological', 'adventuresomenesses', 'psychopathologically']

```

Which, once formatted yields:

```
a
al
all
ally
logic
advent
venture
ventures
adventure
adventures
venturesome
pathological
adventuresome
pathologically
venturesomeness
psychopathologic
adventuresomeness
psychopathological
adventuresomenesses
psychopathologically

```

**Explanation**

The key was to choose two words that complement each other. I chose "*psychopathologically*" and "*adventuresomenesses*" thanks to a little tool I wrote. Using these two words, for any length we can find substrings which are actual words of the provided list. All the possible decompositions are demonstrated by:

```
a al all ally logic psycho logical          logically pathologic             pathological               pathologically                 psychopathologic                   psychopathological                     psychopathologically
a ad ess ness esses advent venture ventures adventure adventures venturesome              adventuresome                venturesomeness                  adventuresomeness                    adventuresomenesses

```

The next step is just to get the list of the indexes for a given decomposition. For my decomposition, I chose: `16 16 16 16 11 20 22 22 20 20 22 6 20 6 22 0 20 0 20 0`, which are indexes in the concatenated strings: `psychopathologicallyadventuresomenesses`.

Finally, write a program which just loops over the indexes and display the substring at each given index with increasing length.

For saving bytes, I stored the indexes in a base 36 string. Indeed, `GGGGBKMMKKM6K6M0K0K0` is the list of my indexes in base 36 (because my highest index is 22, I could have used base 23).

**Program explanation**

```
.e:"psychopathologicallyadventuresomenesses"b+bhkiR36"GGGGBKMMKKM6K6M0K0K0

                                                 iR36"GGGGBKMMKKM6K6M0K0K0    # For each character in the string, convert from base 36 to base 10
.e                                                                            # Loop over indexes: b are the indexes, h their position
  :"psychopathologicallyadventuresomenesses"b+bhk                             # In "psy...ses", select the substring at index b and of length k + 1

```

# Answer
> 4 votes
# Bubblegum, 66 bytes

```
00000000: 6d8b 410a 0020 0804 bf6a 4407 a134 5aff  m.A.. ...jD..4Z.
00000010: 4fe6 29ac 93ce b0a3 543a ad06 3f6c e769  O.).....T:..?l.i
00000020: 46f3 3ae2 b218 abc4 2cab d389 a805 82aa  F.:.....,.......
00000030: fee1 6e43 2444 62df 0f46 4a1e f356 8cf1  ..nC$Db..FJ..V..
00000040: 73d8                                     s.

```

Output:

```
o`al`res`alit`reset`preset`present`rational`represent`rationales`annotations`connotations`connotational`representation`representations`representational`misrepresentation`misrepresentations`representationalism`representationalisms

```

Try it online!

The words and separator were selected by simulated annealing:

```
from __future__ import print_function
import math
import random
import zlib

wordlists = \
    [[chr(x).encode() for x in [9, 10] + list(range(32, 127)) if not chr(x).encode().isalpha()]] + \
    [open('wordListsByLength/{}.txt'.format(n), 'rb').read().splitlines() for n in range(1, 21)]

words = [random.choice(wordlist) for wordlist in wordlists]

temperature = 10.
score = 9999
best = score

while True:
    old_score = score
    n = random.randrange(len(wordlists))
    old_word = words[n]
    words[n] = random.choice(wordlists[n])
    z = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, 9)
    score = len(z.compress(words[0].join(words[1:])) + z.flush())
    if score > old_score and random.random() >= math.exp((old_score - score) / temperature):
        words[n] = old_word
        score = old_score
    else:
        temperature *= .99999
        if score < best:
            best = score
            print(best, repr(words[0].join(words[1:])))

```

# Answer
> 3 votes
# C#, 259 bytes

```
_=>{var a=new int[7].Select((n,i)=>"abasers".Substring(0,i+1)).ToList();a.Add("abacuses");a.AddRange(new int[12].Select((n,i)=>(i>10?"un":"")+"character"+"|s|ed|ful|ised|istic|istics|isation|isations|istically|ologically|istically|".Split('|')[i]));return a;}

```

Some obvious room for golfing still but I've run out of time now. I know it's longer than hard coding so will fix it when I get some time later on.

# Answer
> 3 votes
# 05AB1E, ~~130~~ 68 bytes

-62 bytes thanks to Erik the Outgolfer

```
743222’€Ü†š ƒ´aî³eros €‡a•¿f²Ñns …¿en®íizers ‚ÀÙŠs ‡åØŽ’#‚øε`ηRs£R}˜

```

Try it online!

Takes as many prefixes as needed from each of the following words:

```
amusers
carabinero
foraminiferans
photosensitizers
videoconferencings
radiopharmaceuticals

```

Prints these words in an array:

```
a
am
amu
amus
amuse
amuser
amusers
carabine
carabiner
carabinero
carabineros
foraminifera
foraminiferan
foraminiferans
photosensitizer
photosensitizers
videoconferencing
videoconferencings
radiopharmaceutical
radiopharmaceuticals

```

# Answer
> 2 votes
# Bubblegum, 78 bytes

```
00000000: 654b c301 4431 10bd a7cb d876 9a5f efe7  eK..D1.....v._..
00000010: 781e 2080 ee55 0488 ffc8 9f69 e86f a5ff  x. ..U.....i.o..
00000020: ce00 0b98 202e 34ed d701 a464 bf59 35fb  .... .4....d.Y5.
00000030: 23d7 9192 b948 7c79 f351 0c8b f4ee 06e4  #....H|y.Q......
00000040: 8b05 1a33 77c8 1bcf 7f58 7577 e113       ...3w....Xuw..

```

Try it online!

# Answer
> 2 votes
# Ruby, 107 bytes

```
p(z=%w{o or for form ultra})+[z[3],c="centrifug",z[4]+c].product(%w{ed ing ally ation ations}).map{|i|i*""}

```

Prints the following array.

```
["o", "or", "for", "form", "ultra", "formed", "forming", "formally", "formation", "formations", "centrifuged", "centrifuging", "centrifugally", "centrifugation", "centrifugations", "ultracentrifuged", "ultracentrifuging", "ultracentrifugally", "ultracentrifugation", "ultracentrifugations"

```

Changing the `p` for `puts` (with trailing space) gives the following at a cost of an additional 4 bytes.

```
o
or
for
form
ultra
formed
forming
formally
formation
formations
centrifuged
centrifuging
centrifugally
centrifugation
centrifugations
ultracentrifuged
ultracentrifuging
ultracentrifugally
ultracentrifugation
ultracentrifugations

```

# Answer
> 1 votes
# Japt, 119 bytes

```
`av„v„dvjvjsvj¤vj¤svfœejvqvqsvq‚vqˆgvqizƒvqÄKcvqÄKcsvqizÂ\nvqizÂ\nsvq‰tkvqologkv·sqizÂ\ns`d'j`Ê@`'k`Åœ§`'q`Ö‹a×` q'v ·

```

Try it online!

## Prints:

```
a
an
and
hand
hands
handle
handles
freehand
character
characters
charactered
charactering
characterizes
characteristic
characteristics
characterization
characterizations
characteristically
characterologically
mischaracterizations

```

---
Tags: code-golf, kolmogorov-complexity, natural-language
---


title: THIS ... IS ... FORTRESS!

text:
# Question
Title: THIS ... IS ... FORTRESS!
Fortress was a language being developed by the Sun Programming Language Research Group (R.I.P. Fortress) that had a unique property to it, it was possible to render ("Fortify") programs in different font-styles (i.e. blackboard bold, bold, italics, roman, etc. ). The goal is to represent a one-char Fortress variable in HTML markup.

Here's how the fortification of one-char variables worked (simplified/modified from documentation for code-golfing purposes):

* If the variable is a repeated capital (i.e. `ZZ`), it becomes formatted in blackboard bold (`ℂℍℕℙℚℝℤ`)
* If the variable is preceded by an underscore, the variable is rendered in roman font (left alone)
* If the variable is followed by an underscore, the variable is rendered in bold font (`<b>`v`</b>`)
* If the variable is neither preceded nor followed by an underscore, the variable is rendered in italic font (`<i>`v`</i>`)
* The codepoints of the blackboard bolds are: :1D538, :1D539, :2102, :1D53B, :1D53C, :1D53D, :1D53E, :210D, :1D540, :1D541, :1D542, :1D543, :1D544, :2115, :1D546, :2119, :211A, :211D, :1D54A, :1D54B, :1D54C, :1D54D, :1D54E, :1D54F, :1D550, :2124. These count as **one byte each** in your program (if your language of choice can handle these characters at all)

Input will be either a repeated ASCII capital, or a single ASCII letter with either no underscore, a leading underscore, or a trailing underscore (AKA `_a_` will not be an input). This is code-golf so lowest byte count wins!

Test cases:

```
a => <i>a</i>
BB =>
c_ => <b>c</b>
_d => d
E => <i>E</i>
G_ => <b>G</b>
_H => H
ZZ => ℤ

```

Links: Specification, Direct download of version 0.1 alpha.

Reference implementation (This would be in Fortress, but Fortress doesn't like most of the doublestruck characters, so this implementation is in D):

```
dstring fortify(string arg) {
    import std.string, std.conv;

    alias D = to!dstring; //Convert to a string that accepts the unicode needed
    dstring BB = "ℂℍℕℙℚℝℤ"d; //blackboard bold capitals
    string UC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //normal ASCII capitals

    if(arg.length == 1)
        return D("<i>" ~ arg ~ "</i>");
    if(arg[0] == a[1])
        return D(BB[UC.indexOf(arg[0])]);
    if(arg[0] == '_')
        return D(arg[1]);
    return D("<b>" ~ arg[0] ~ "</b>");
}

```

# Answer
> 1 votes
# Jelly, 73 bytes

Turns out that not being able to use the BBB letters in the code is quite expensive.

```
5ŀ”i
“Ðñṡ’Dẋ@€“¡ḞḄ’ż“¿¿Æ€¢¬µ‘+⁽ø³F⁸ṪO¤+ị¥Ọ
Ṫ
Ḣ5ŀ”b
;j“<>/”ṃ@“¢ʠf’
i”_+LµĿ

```

A full program taking one argument and printing the result.

**Try it online!** or see the test suite.

### How?

The main entry point is the last line of code ("Main link").

```
5ŀ”i - Link 1: list of characters, s (length 1 & no underscore)
  ”i - literal character 'i'
5ŀ   - call link 5 as a dyad with s on the left and 'i' on the right

“Ðñṡ’Dẋ@€“¡ḞḄ’ż“¿¿Æ€¢¬µ‘+⁽ø³F⁸ṪO¤+ị¥Ọ - Link 2: list of characters, s (length 2 & no underscore)
“Ðñṡ’                                 - base 250 literal              1007245
     D                                - to decimal list               [1,0,0,7,2,4,5]
         “¡ḞḄ’                        - base 250 literal              111673
      ẋ@€                             - repeat with reversed @rguments for €ach -> [[111673],[],[],[111673,111673,111673,111673,111673,111673,111673],[111673,111673],[111673,111673,111673,111673],[111673,111673,111673,111673,111673]]
               “¿¿Æ€¢¬µ‘              - code page index list          [11,11,13,12,1,7,9]
              ż                       - zip together                  [[111673,11],[11],[13],[[111673,111673,111673,111673,111673,111673,111673],12],[[111673,111673],1],[[111673,111673,111673,111673],7],[[111673,111673,111673,111673,111673],9]]
                         ⁽ø³          - base 250 literal              8382
                        +             - addition (vectorises)         [[120055,8393],[8393],[8395],[[120055,120055,120055,120055,120055,120055,120055],8394],[[120055,120055],8383],[[120055,120055,120055,120055],8389],[[120055,120055,120055,120055,120055],8391]]
                            F         - flatten                       [120055,8393,8393,8395,120055,120055,120055,120055,120055,120055,120055,8394,120055,120055,8383,120055,120055,120055,120055,8389,120055,120055,120055,120055,120055,8391]
                                ¤     - nilad followed by link(s) as a nilad:                                                                                ^
                             ⁸        -   chain's left argument, s  e.g.    "CC"                                                                                |
                              Ṫ       -   tail (last character)             'C'                                                                                |
                               O      -   cast to ordinal                   67                                                                                |
                                   ¥  - last two links as a dyad:                                                                                |
                                  ị   -   index into (1-indexed & modular)  8383 (this is at index 67%26=15 -----------------------------------------------------+ )
                                 +    -   add the ordinal                   8450
                                    Ọ - convert from ordinal to character   'ℂ'

Ṫ - Link 3: list of characters, s (length 2 & underscore at index 1)
Ṫ - tail (get the first character

Ḣ5ŀ”b - Link 4: list of characters, s (length 2 & underscore at index 2)
Ḣ     - head s (the non-_ character)
   ”b - literal character 'b'
 5ŀ   - call link 5 as a dyad with the non-_ character on the left and 'b' on the right

;j“<>/”ṃ@“¢ʠf’ - Link 5, wrap in a tag: element, tagName      e.g. 'a', 'i'
;              - concatenate the element with the tagName          "ai"
  “<>/”        - literal list of characters                        "<>/"
 j             - join                                              "a<>/i"
         “¢ʠf’ - base 250 literal                                  166603
       ṃ@      - base decompression with reversed @rguments
               -   "a<>/i" is 5 long, so 166603 is converted to
               -   base 5 [2,0,3,1,2,4,0,3] with digits "a<>/i"    "<i>a</i>"

i”_+LµĿ - Main link: list of characters, s (as specified only):
 ”_     - literal '_'
i       - index of '_' in s (1-indexed; 0 if not found)
    L   - length of s
   +    - addition
     µĿ - call link with that number as a monad with argument s
        - implicit print

```

# Answer
> 4 votes
# Python 3.6, ~~159~~ ~~131~~ 128 bytes

*1 byte saved thanks to @Zacharý*

*3 bytes saved thanks to @VаlueInk*

*28 bytes saved thanks to @Rod*

```
lambda s:len(s)<2and f"<i>{s}</i>"or s[0]==s[1]and"ℂℍℕℙℚℝℤ"[ord(s[0])-65]or[f"<b>{s[0]}</b>",s[1]][s[0]=='_']

```

Try it online!

# Answer
> 2 votes
# Ruby, ~~104~~ ~~106~~ 105+1 = ~~105~~ ~~107~~ 106 "bytes"

Probably works even better in Retina. Uses `-p` flag.

-1 byte from Zacharý.

```
gsub /^.$/,'<i>\0</i>'
gsub(/(.)\1/){$1.tr"A-Z","ℂ-ℍ-ℕℙℚℝ-ℤ"}
gsub /(.)_/,'<b>\1</b>'
gsub ?_,''

```

Try it online!

# Answer
> 1 votes
# JavaScript, 97 chars

```
([a,b])=>a==b?[...'ℂℍℕℙℚℝℤ'][a.charCodeAt()-65]:b?b=='_'?a.bold():b:a.italics()

```

Why a language have methods like `String.prototype.italics` and `String.prototype.bold`?

Thanks to Neil, save 9 bytes, use `[...s]` instead of `s.match(/./u)`.

---
Tags: code-golf
---


title: Invisible Writing

text:
# Question
Title: Invisible Writing
In the physical world, invisible ink usually becomes invisible when it dries, and is then is readable if it is exposed to heat or chemicals of some kind. The invisible ink in this challenge will be readable when exposed to highlighting.

Create a full program or function that takes in text from the console (using a prompt) and outputs it the console so it cannot be seen unless highlighted (selected, as you would with a mouse).

## Notes:

* Assume that the console is a solid color (black, white, green, etc.).

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

# Answer
# JavaScript (ES6), ~~44~~ 42 bytes

Tested in Chrome & Firefox.

```
s=>console.log("%c"+s,"color:transparent")

```

---

## Try it

Open your browser's console.

```
(
s=>console.log("%c"+s,"color:transparent")
)("Invisible Text!")
```

---

# Japt, ~~21~~ 20 bytes

Will post this separately when/if the challenge is reopened

```
Ol"%c"+U`¬l:ÉspÂÁt

```

Test it
> 5 votes

# Answer
## Magneson, 102 bytes

<sub>(source: googleapis.com)</sub>

(Note that the above is an enlarged version of the program, and the action source can be found here

This is my first submission in a long while, so while I think Magneson does classify as a language according to this, if it's not suitable let me know and I can take it down.

Onto the "code" itself; Magneson operates by parsing an image and evaluating commands from the colours of the pixels it reads. So stepping through the image for this challenge, we have:

* `R: 0, G: 0, B: 1` is a simple `println` statement; it prints a string out to the console
* `R: 255, G: 255, B: 0` is a string operative to concatenate the following values, until we receive a stop concatenate op.
* `R: 2, G: 0, B: 27` is a raw character. In strings, when the red component is `2` and the green component is `0`, we simply use the blue component as a raw character to add to the string. In this case, we add the escape character for ANSI control strings.
* `R: 2, G: 0, B: 91` is another raw character (`[`)
* `R: 2, G: 0, B: 51` is another raw character (`3`)
* `R: 2, G: 0, B: 48` is another raw character (`0`)
* `R: 2, G: 0, B: 59` is another raw character (`;`)
* `R: 2, G: 0, B: 52` is another raw character (`4`)
* `R: 2, G: 0, B: 48` is another raw character (`0`)
* `R: 2, G: 0, B: 109` is another raw character (`m`)
* `R: 3, G: 0, B: 0` is a string operative for input from STDIN. In this case, it just appends it to the concatenated string.
* `R: 255, G: 255, B: 1` is the end concatenation op.

All in all, this program builds a string of `ESC[30;40m`, followed by one line of input from the command line. This'll set both the foreground and background colours to black.
> 1 votes

# Answer
# C (gcc), 77 91 bytes

```
c;main(){printf("\x1b]11;2\a\x1b[42;32m");while((c=getchar())>0)putchar(c);puts("\x1b[m");}

```

Try it online! (will only show the raw output including the escape sequences)

Extra bytes were necessary to be independent from the original background color, see discussion in the comments.

This version uses ANSI escape codes to set the background and foreground colors to green as well as an Xterm escape code to change the background of the whole window to green. This way, if your selection color doesn't happen to be (dark) green (very unlikely), it **will** work on terminals supporting ANSI escape sequences and compatible with Xterm.

It works for example in `rxvt` as seen in these screenshots:
> 0 votes

---
Tags: code-golf
---


title: Solve a Matchstick puzzle

text:
# Question
Title: Solve a Matchstick puzzle
On puzzling SE there are what are called "matchstick problems" in which math is written in match sticks and you are allowed to move a certain number of them to get a certain property.

In this question we will be considering only integers represented in a 7-segment display format. Here are all 10 digits in that format:

```
 __          __   __          __    __    __    __    __
|  |     |   __|  __|  |__|  |__   |__      |  |__|  |__|
|__|     |  |__   __|     |   __|  |__|     |  |__|   __|

```

Each segment of the display is one "match-stick" which can be moved independently of the rest of the number. Matchsticks are indivisible and indestructible, the cannot be broken or removed by any means.

A common puzzle is to take a number given in base 10 and try to make the largest number possible in a given number of moves. A move is considered to be one movement of a matchstick from any occupied slot to any other unoccupied slot. You are perfectly permitted to make new digits on either side of the number, for example 0 can be made into 77 give 3 moves

```
 __      __  __      __   __      __   __
|  |    |  |        |  |    |       |    |
|__| ,   __|     ,     |      ,     |    |

```

However you may not make one slot into 2 or make new slots between existing ones, for example turning a 4 into an 11 in the middle of a number or inserting new digits in between existing ones. Each move need not make a proper number but the final result should be a proper number in the base 10 seven segment display. You need not use every move if you do not wish to. Unlike on puzzling this is a \[tag:close ended question\] you *may not* use any operators (multiplication, exponentiation, etc.) or mathematical constants (Pi, Graham's number, etc.) in your answers.

## Task

Write a program or function that takes a number and a number of moves as input and returns the largest number that can be made with that many moves on the original number.

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

## Test Cases

```
n, moves -> max
0, 1     -> 9
0, 3     -> 77
0, 4     -> 111
8, 3     -> 74
220, 1   -> 320
220, 2   -> 520
220, 3   -> 7227
220, 4   -> 22111
220, 5   -> 32111
747, 1   -> 747
747, 2   -> 7171
747, 3   -> 7711

```

Related

# Answer
> 7 votes
## JavaScript (ES6), ~~297~~ ~~286~~ ~~279~~ 267 bytes

Takes input in currying syntax `(s)(k)`, where ***s*** is an array of digit characters and ***k*** is the number of moves (integer).

```
s=>k=>(B=(n,b=0)=>n?B(n^n&-n,b+1):b,b=[...p='u"[k,iy#}m'].map(c=>c.charCodeAt()+2),r=[],g=(n,d='')=>n?n>0&&b.map((v,i)=>g(n-B(v),d+i)):r.push(d))(s.reduce((s,c)=>s+B(b[c]),M=0))&&b.map((_,j)=>r.map(n=>M=[...n+p].reduce((t,d,i)=>t+B(b[d]^b[s[i-j]]),0)>k*2|+n<M?M:n))|M

```

### Test cases

```
let f=

s=>k=>(B=(n,b=0)=>n?B(n^n&-n,b+1):b,b=[...p='u"[k,iy#}m'].map(c=>c.charCodeAt()+2),r=[],g=(n,d='')=>n?n>0&&b.map((v,i)=>g(n-B(v),d+i)):r.push(d))(s.reduce((s,c)=>s+B(b[c]),M=0))&&b.map((_,j)=>r.map(n=>M=[...n+p].reduce((t,d,i)=>t+B(b[d]^b[s[i-j]]),0)>k*2|+n<M?M:n))|M

console.log("0   / 1 -> " + f([..."0"  ])(1)) // -> 9
console.log("0   / 3 -> " + f([..."0"  ])(3)) // -> 77
console.log("0   / 4 -> " + f([..."0"  ])(4)) // -> 111
console.log("8   / 3 -> " + f([..."8"  ])(3)) // -> 74
console.log("220 / 1 -> " + f([..."220"])(1)) // -> 320
console.log("220 / 2 -> " + f([..."220"])(2)) // -> 520
console.log("220 / 3 -> " + f([..."220"])(3)) // -> 7227
console.log("220 / 4 -> " + f([..."220"])(4)) // -> 22111
console.log("220 / 5 -> " + f([..."220"])(5)) // -> 32111
console.log("747 / 1 -> " + f([..."747"])(1)) // -> 747
console.log("747 / 2 -> " + f([..."747"])(2)) // -> 7171
console.log("747 / 3 -> " + f([..."747"])(3)) // -> 7711
```

---

### How?

**Shape data and helper function**

* The array ***b*** describes the shapes of the digits as 7-bit integers, where each bit is a segment:

For instance, the shape of "7" is 0b0100101 = 37.
* The helper function ***B()*** returns the number of 1's in the binary representation of a given number:

```
B = (n, b = 0) => n ? B(n ^ n & -n, b + 1) : b

```

**Step #1**

We first count the number of matchsticks used in the input number:

```
s.reduce((s, c) => s + B(b[c]), 0)

```

**Step #2**

We pass this value to the recursive function ***g()***, which populates a list ***r*** with all numbers that can be built with exactly this number of matchsticks:

```
g = (n, d = '') =>
  n ?
    n > 0 &&
    b.map((v, i) => g(n - B(v), d + i))
  :
    r.push(d)

```

For instance, ***g(5)*** will load `[ '17', '2', '3', '5', '71' ]` into ***r***.

**Step #3**

We now have to select the highest number ***M*** in ***r*** which can actually be obtained from the input number, within the allowed number of moves ***k***.

Because each number ***n*** in ***r*** uses exactly as many matchsticks as the input number ***s***, the number of moves required to transform ***s*** into ***n*** equals *half* the number of segment differences between each of their digits.

The number of segment differences between two digits ***x*** and ***y*** is given by the number of 1's in the binary representation of ***b\[x\] XOR b\[y\]***.

Finally, it's important to note that we need to try several possible digit alignments, because the first digit of ***s*** is not necessarily mapped to the first digit of ***n***. The shift between the digits is given by the variable ***j*** in the code.

# Answer
> 1 votes
# Mathematica, 188 ~~197~~ ~~200~~ ~~203~~ ~~170~~ ~~174~~ bytes

*NOTE:* The code is still kind of buggy. I'm working on it.

+30 bytes for bug

```
(p=PadLeft;q=IntegerDigits;g=Join@@(#~q~2~p~7&/@ToCharacterCode["w$]m.k{% o"][[1+q@#]])&;h=(v=g@#2~#~96-g@i~#~96;Tr@v==0&&Tr@Abs@v<=2#3)&;For[i=10^Tr@g@#,!h[p,##]&&!h[PadRight,##],--i];i)&

```

The character between `%` and `o` should be `0x7F` but SE won't allow it. You could click pastebin link to copy the original code.

The code takes a lot of time when there're more than 6-7 sticks. (You could modify the starting value of `i` to a smaller number to test it)

## Explanation

`g` is a helper function converting digits into a list of stick representation (according to here), such as `{1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}` for `220`.

`h` is a helper function to deal with left-padding and right-padding between two numbers.

`f` iterates from `10^Tr@g@#` (upper limit) to `1` to look for a integer whose stick representation has a same quantity of `1 -> 0` and `0 -> 1` compared to the original number and the quantity is smaller or equal than second argument.

---
Tags: code-golf, game, puzzle-solver
---