title: Draw Translucent Boxes

text:
# Question
Title: Draw Translucent Boxes
note: the string art might look horrible here because of SE font weirdness :P :(

Given a list of four-tuples representing the corners of rectangles, draw translucent rectangles over each other in that order.

For this challenge, you are required to have the smallest coordinate in the top-left corner and the x-axis increasing to the right and the y-axis increasing downwards.

A four-tuple `(x0, y0, x1, y1)` or `(x0, x1, y0, y1)` represents the `(x, y)` coordinate pairs of the top-left and bottom-right corners of a rectangle (you may choose either of the two formats for rectangles but it must be consistent)

What do I mean by "translucent rectangle"? Well, for this challenge, you will be using the space character and most of the box-drawing characters; specifically, all of the ones used to draw rectangles, including "bold" characters. When a translucent rectangle is drawn, first all thin lines in the space being occupied disappear and all bold lines become thin, and then the rectangle itself is drawn over in bold lines.

For example, if you draw a rectangle in the top-left and then in the bottom-right, it might look something like this:

```
┏━━━━┓
┃    ┃
┃    ┃
┃ ┏━━╇━━┓
┃ ┃  │  ┃
┗━╉──┘  ┃
  ┃     ┃
  ┃     ┃
  ┗━━━━━┛

```

To be clear, lines are lightened (bold -\> thin -\> none) for all lines strictly within the rectangle (for example, downwards facing lines are affected for the top edge but not the bottom edge).

# Test Cases

Some number of lines of input will be given, followed by unicode-art, for each test case.

```
0 0 5 5
5 5 10 10
3 3 7 7
2 2 8 8

┏━━━━┓
┃    ┃
┃ ┏━━╇━━┓
┃ ┃┌─┴─┐┃
┃ ┃│   │┃
┗━╉┤   ├╊━┓
  ┃│   │┃ ┃
  ┃└─┬─┘┃ ┃
  ┗━━╈━━┛ ┃
     ┃    ┃
     ┗━━━━┛

14 5 15 9
13 2 15 16
6 4 15 11

             ┏━┓
             ┃ ┃
      ┏━━━━━━╇━┫
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┃      │ ┃
      ┗━━━━━━╈━┫
             ┃ ┃
             ┃ ┃
             ┃ ┃
             ┃ ┃
             ┗━┛

6 8 10 11
15 12 16 16
14 10 16 16
9 1 15 15

         ┏━━━━━┓
         ┃     ┃
         ┃     ┃
         ┃     ┃
         ┃     ┃
         ┃     ┃
         ┃     ┃
      ┏━━╉┐    ┃
      ┃  ┃│    ┃
      ┃  ┃│   ┌╊┓
      ┗━━╉┘   │┃┃
         ┃    │┠┨
         ┃    │┃┃
         ┃    │┃┃
         ┗━━━━╈┩┃
              ┗┷┛

```

Generate more test cases!

# Rules

* Input can be in any reasonable format for a list of four-tuples. Input can be one-indexed or zero-indexed along either axis (i.e. the top-left corner can be any of `(0, 0)`, `(0, 1)`, `(1, 0)`, `(1, 1)`.
* Output must be as unicode-art as described. Output may not have leading newlines and can have at most one trailing newline (after the last line). Trailing whitespace will be ignored for the purposes of this challenge.

# Code-points

The bold and light horizontal and vertical pipes are in the range `[U+2500, U+2503]`. The various corner pipes are in the range `[U+250C, U+251C)`. The three-armed pipes are in the range `[U+251C, U+253C)`. The four-armed pipes are in the range `[U+253C, U+254C)`. The remaining pipes that can be found in my program are never actually used.

# Answer
> 3 votes
# Python 3, ~~289~~ 286 bytes

```
l,u=eval(input())
*_,w,h=map(max,zip(*l))
r=[*map(list,[' '*-~w]*-~h)]
R=range
for x,y,X,Y in l:
 for i in R(x,X+1):
  for j in R(y,Y+1):Q=i<X,y<j,x<i,j<Y;r[j][i]=u[sum(3**o*max(Q[o]*[j in(y,Y),i in(x,X)][o%2]*2,u.index(r[j][i])//3**o%3-Q[o])for o in R(4))]
for l in r:print(''.join(l))

```

Try it online!

Takes input as a list of 4-tuples: `(x0, y0, x1, y1)`, along with the pipedrawing characters as follows: `" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"`

Supports boxes of zero width or height (uses all box drawing chars).

Based on my answer to this question, but modified to alter existing boxes when drawing.

**'Ungolfed':**

```
u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"

#Create array of spaces:
l=eval(input())
w,h=list(map(max,zip(*l)))[2:]
r=[[' ']*w for _ in' '*h]

for x,y,X,Y in l:
 n,m=X-1,Y-1
 for i in range(x,X):
  for j in range(y,Y):
   A,B=j in(y,m),i in(x,n)
   P=(i<n*A,y<j*B,x<i*A,j<m*B)   # Pipe sides of the new box
   Q=(i<n,y<j,x<i,j<m)           # Pipe sides that are inside the new box, and should be thinned.
   # Get new pipe (sides of new box, on top of thinned pipes of existing boxes. (u.index... is existing pipe))
   l=sum(3**o*max(P[o]*2,(u.index(r[j][i])//3**o%3)-Q[o])for o in range(4))
   #Add to 'canvas'
   r[j][i]=u[l]

print('\n'.join(''.join(l)for l in r))

```

# Answer
> 2 votes
## JavaScript (ES6), ~~298~~ 261 bytes

```
(a,u,m=n=>[...Array(1+Math.max(...a.map(t=>t[n])))])=>m(3).map((_,j)=>m(2).map((_,i)=>u[a.reduce((c,[x,y,v,w])=>i<x|j<y|i>v|j>w?c:(g=n=>c-=c/n%3|0&&n,h=n=>c+=n*(2-(c/n%3|0)),[i>x&&9,i<v].map(j>y&j<w?g:h),[j>y&&3,j<w&&27].map(i>x&i<v?g:h),c),0)]).join``).join`\n`

```

Where `\n` represents the literal newline character. Based on my answer to Unicode rectangles. Explanation: An array of strings of spaces is created to draw in. Each spaces is then processed by looping over all the boxes in the input. Characters that lie outside of the box are then ignored but those on the edge or inside are processed further. For each of the four line segments making up a character (each represented by a power of 3) there are then three possibilities; a) the segment lies just outside the box and should be ignored (achieved by passing a parameter of 0 instead of the power of 3) b) the segment lies on the edge of the box and should be bold (achieved by calling the `h` function) c) the segment lies inside the box and should be lightened (achieved be calling the `g` function). The character is then indexed into the Unicode string. Once all the boxes have been processed the array is then joined on newlines.

```
f=
(a,u,m=n=>[...Array(1+Math.max(...a.map(t=>t[n])))])=>m(3).map((_,j)=>m(2).map((_,i)=>u[a.reduce((c,[x,y,v,w])=>i<x|j<y|i>v|j>w?c:(g=n=>c-=c/n%3|0&&n,h=n=>c+=n*(2-(c/n%3|0)),[i>x&&9,i<v].map(j>y&j<w?g:h),[j>y&&3,j<w&&27].map(i>x&i<v?g:h),c),0)]).join``).join`
`
;u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋";
[[
[0, 0, 5, 5],
[5, 5, 10, 10],
[3, 3, 7, 7],
[2, 2, 8, 8],
],[
[14, 5, 15, 9],
[13, 2, 15, 16],
[6, 4, 15, 11],
],[
[6, 8, 10, 11],
[15, 12, 16, 16],
[14, 10, 16, 16],
[9, 1, 15, 15],
]].map(a=>document.write(`<pre style="font-family:Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,sans-serif">${f(a,u)}</pre>`));
```

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


# Question
Title: Arranging arbitrary shapes to fill a rectangular space
A while ago, I posted a challenge asking to determine whether or not it's possible to arrange arbitrary rectangles to fill a rectangular space, here. That got answers, so clearly it was too easy. (Just kidding, it was fairly challenging, congrats to the answerers :D)

# Challenge

Given a bunch of arbitrary shapes (consisting of 1x1 square tiles) (up to 100 with a combined area of at most 1000), can you arrange them to fill a rectangular space, without rotations or reflections?

A shape is valid as input if it has at least 1 tile and all tiles are connected to each other by edges. For example:

Valid:

```
XXX
X X
XXX

```

Invalid:

```
XXX
X
 XX

```

The shapes will be represented in input by using a non-whitespace character `X`, spaces, and newlines. Individual shapes will be separated by two newlines (i.e. split on `\n\n`). You can choose to use LF, CR, or CRLF as a newline. Alternatively, you can choose to use LF or CR as a single newline and CRLF as a double-newline for separating shapes. Please specify in your answer what you choose.

For example, this would be the input format for a 2x2 square and a 3x3 "donut":

```
XX
XX

XXX
X X
XXX
(Optional trailing newline or double-newline)

```

The output should be either any truthy value or a consistent falsy value (but not an error). For example, you may output the valid arrangement if one exists or false, but you cannot error if there is no valid arrangement, neither can you output different values for having no valid arrangement.

# Test Cases

## Test Case 1

```
XXXX
X  X
XX X

X
X

X

TRUE

```

Valid Arrangement:

```
XXXX
XYYX
XXYX

```

## Test Case 2

```
XXXX
XX

X

FALSE

```

## Test Case 3

```
XXXXXX
X X  X
X XXX

XX

X
X

X

TRUE

```

Valid Arrangement:

```
XXXXXX
XYXZZX
XYXXXA

```

## Test Case 4

```
XX
X

 X
XX

XXX

X
X
X

TRUE

```

Valid Arrangement:

```
XXYZ
XYYZ
AAAZ

```

# Notes

* Each shape must be used exactly once in the arrangement
* Shapes may not be rotated or reflected
* The input can contain multiple identical shapes; in this case, each of those still needs to be used exactly once; that is, if two 5x3 rectangles are given in the input, two 5x3 rectangles must appear in the arrangement

# Answer
# Python 2, 434 bytes

```
lambda s:F([[' ']*sum(map(lambda s:len(s[0]),s)) for _ in' '*sum(map(len,s))],s)
L=len
R=range
def F(a,s):
 if not s:return len(set(tuple(l)for l in a if'X'in l))==len(set(tuple(l)for l in zip(*a)if'X'in l))==1
 c=s[0];h,w=L(c),L(c[0])
 for i in R(L(a)-h):
	for j in R(L(a[0])-w):
	 T=1;A=[l[:]for l in a]
	 for y in R(h):
		for x in R(w):
		 C=c[y][x]
		 if C>' ':T&=A[y+i][x+j]<'!';A[y+i][x+j]=C
	 r=T and F(A,s[1:])
	 if r:return r

```

Try it online!

Takes input as a list of lists.

Returns `True` or `None`

Assumes that each line in a shape is padded to the length of that shape.

(based on my answer to Do the figures fit?)
> 1 votes

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


# Question
Title: Least integer as a product of given factors
*There have been a lot of prime-/prime factorization-related challenges recently, so I thought it might be interesting to go the other way.*

Given:

* a positive integer `n`, and
* a non-empty list of positive integers `f`

write a full program or a function to find the smallest integer `i` such that `i >= n` and `i` is a product of nonnegative, integer powers of elements in `f`.

## Examples:

* Suppose `n = 11, f = [2, 3, 5]`.

The first few products are:

```
1   = 2^0 * 3^0 * 5^0
2   = 2^1 * 3^0 * 5^0
3   = 2^0 * 3^1 * 5^0
5   = 2^0 * 3^0 * 5^1
4   = 2^2 * 3^0 * 5^0
6   = 2^1 * 3^1 * 5^0
10  = 2^1 * 3^0 * 5^1
9   = 2^0 * 3^2 * 5^0
15  = 2^0 * 3^1 * 5^1
25  = 2^0 * 3^0 * 5^2
8   = 2^3 * 3^0 * 5^0
12  = 2^2 * 3^1 * 5^0 => smallest greater than (or equal to) 11, so we output it.
20  = 2^2 * 3^0 * 5^1
18  = 2^1 * 3^2 * 5^0
30  = 2^1 * 3^1 * 5^1
50  = 2^1 * 3^0 * 5^2
27  = 2^0 * 3^3 * 5^0
45  = 2^0 * 3^2 * 5^1
75  = 2^0 * 3^1 * 5^2
125 = 2^0 * 3^0 * 5^3

```
* Suppose `n=14, f=[9, 10, 7]`.

Again, the first few products:

```
1 = 7^0 * 9^0 * 10^0
7 = 7^1 * 9^0 * 10^0
9 = 7^0 * 9^1 * 10^0
10 = 7^0 * 9^0 * 10^1
49 = 7^2 * 9^0 * 10^0  => smallest greater than (or equal to) 14, so we output it.
63 = 7^1 * 9^1 * 10^0
70 = 7^1 * 9^0 * 10^1
81 = 7^0 * 9^2 * 10^0
90 = 7^0 * 9^1 * 10^1
100 = 7^0 * 9^0 * 10^2

```

## Test cases:

```
n, f -> output
10, [2, 3, 5]              -> 10
17, [3, 7]                 -> 21
61, [3,5,2,7]              -> 63
23, [2]                    -> 32
23, [3]                    -> 27
23, [2, 3]                 -> 24
31, [3]                    -> 81
93, [2,2,3]                -> 96
91, [2,4,6]                -> 96
1,  [2,3,5,7,11,13,17,19]  -> 1
151, [20,9,11]             -> 180
11616, [23,32]             -> 12167
11616, [23,32,2,3]         -> 11664 = 2^4 * 3^6
5050, [3,6,10,15,21,28,36,45,55,66,78,91,105,120,136,153,171,190,210] -> 5103 = 3^6 * 7
12532159, [57, 34, 12, 21] -> 14183424 = 12^5 * 57

```

## Rules

* You may assume that `f` will contain at least one element, and that all elements of `f` will be greater than 1.
* You may optionally assume that `f` is sorted in decreasing/increasing order if you would like (but please specify).
* You may optionally take the number of elements of `f` if you would like.
* Output as a string is allowed.
* This is , so shortest answer in bytes in each language wins!
* Default I/O rules apply, and standard loopholes are forbidden.
* Explanations are encouraged.

# Answer
# Husk, 8 bytes

```
ḟṠ€ȯmΠṖṘ

```

Extremely slow. Try it online!

## Explanation

```
ḟṠ€ȯmΠṖṘ  Implicit inputs, say L=[3,4] and n=5.
ḟ         Find the lowest integer k≥n that satisfies:
       Ṙ   Replicate L by k: [3,3,3,3,3,4,4,4,4,4]
      Ṗ    Powerset: [[],[3],[4],..,[3,3,3,3,3,4,4,4,4,4]]
    mΠ     Product of each: [1,3,4,..,248832]
 Ṡ€ȯ       k is in this list.

```
> 10 votes

# Answer
# Wolfram Language (Mathematica), ~~68~~ ~~65~~ ~~62~~ 61 bytes

```
If[#^#2<=1,1~Max~-Log@#2,Min[#0[#,#2-1,##4],#0[#/#3,##2]#3]]&

```

Try it online!

## How it works

Takes input as `[n,k,f1,f2,f3,...,fk]` (e.g., `[11,3,2,3,5]`): the first value is the target `n`, the second is the number of factors, and all the frctors follow.

The other number-theory challenges recently all folded to fancy built-ins (at the very least, they used `FactorInteger`) so I thought I'd try something that used only basic tools. This solution basically says that to write `n` as a product of the factors, we either use the first factor `f1` (and recurse on `n/f1`, then multiply by `f1`) or don't (and recurse on a shorter list of factors), then take the min.

The recursion bottoms out when the target is less than 1 or when the number of factors is 0, which we check for with `#^#2<=1` at once, and then generate 1 in the first case and `Infinity` in the latter with `1~Max~-Log@#2`.

The function gives a whole bunch of warnings (but still works) unless you run it with `Quiet`, because it eventually recurses to cases where `#3` doesn't exist, making the unused second branch of `If` sad.

---

*-3 bytes: taking the number of factors as input.*

*-3 bytes thanks to @ngenisis: using .*

*-1 byte, and no  ambiguity: the `#^#2` check.*
> 7 votes

# Answer
# Python 2, ~~91~~ ~~88~~ 84 bytes

```
f=lambda n,l:n<2or any(n%x<1and f(n/x,l)for x in l)
g=lambda n,l:n*f(n,l)or g(n+1,l)

```

Try it online!

The function `f` checks recursively if `n` is a product of powers of elements in `l`, `g` is just a wrapper to control the iteration
> 6 votes

# Answer
# Python, 55 bytes

```
f=lambda n,l,x=1:min(f(n,l,x*e)for e in l)if x<n else x

```

Try it online!

Shamelessly copied Rod's footer script for testing
> 6 votes

# Answer
# Jelly, 13 bytes

```
L⁹ṗ’⁸*P€ḟ⁹Ḷ¤Ṃ

```

A dyadic link taking the list, `f`, on the left and the number, `n`, on the right which yields a number.

**Try it online!** Golfily inefficient - will time out for inputs with higher `n` and/or longer `f`.

### How?

We know that the powers of the individual (strictly positive) factors will never need to exceed `n-1`
...so let's just inspect all the possible ways!

```
L⁹ṗ’⁸*P€ḟ⁹Ḷ¤Ṃ - Link: list, f; number, n
 ⁹            - chain's right argument, n
L             - length of f
  ṗ           - Cartesian power  ...e.g.: len(f)=2; n=3 -> [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
   ’          - decrement (vectorises)
    ⁸         - chain's left argument, f
     *        - exponentiate (vectorises) - that is [f1^a, f2^b, ...] for each [a, b, ...] in the list formed from the Cartesian power
      P€      - product for €ach - that is f1^a * f2^b * ... for each [a, b, ...] in the list formed from the Cartesian power
           ¤  - nilad followed by link(s) as a nilad:
         ⁹    -   chain's right argument, n
          Ḷ   -   lowered range -> [0,1,2,3,...,n-1]
        ḟ     - filter discard - that is remove values less than n
            Ṃ - minimum

```
> 4 votes

# Answer
# Mathematica, 85 bytes

```
Min@Select[Flatten[1##&@@(s^#)&/@Tuples[0~Range~⌈Log[Min[s=#],d=#2]⌉,#3]],#>=d&]&

```

**Input**

> \[{list f},n,number of elements of f\]
> \[{57, 34, 12, 21}, 12532159, 4\]
> 2 votes

# Answer
# Retina, 76 bytes

```
\d+
$*
1+;
$&$&
{+`;(1+)(\1)*(?=;.*\b\1\b)
;1$#2$*1
}`(1+);11+;
1$1;1$1;
\G1

```

Try it online! Link excludes the slowest test cases, but it's still a little slow, so try not to hammer @Dennis's server.
> 2 votes

# Answer
# Pyth - 10 bytes

Runs out of memory very quickly.

```
f}T*My*QTE

```

Try it online here.

Reasonable answer for 16 bytes: `fsm.A}RQ*Md./PTE`
> 2 votes

# Answer
# Japt, 10 bytes

```
_k e!øV}aU

```

Test it online!

Doesn't work on the last test case due to an iteration limit designed to keep the interpreter from running forever (didn't help much here though, as it froze my browser for an hour...)

### Explanation

```
_k e!øV}aU    Implicit: U = input integer, V = array of factors
_      }aU    Starting at U, find the next integer Z where
 k              the factors of Z
   e            are such that every factor
    !øV         is contained in V (e!øV -> eX{VøX}, where VøX means "V contains X").
              Implicit: output result of last expression

```
> 2 votes

# Answer
# Jelly, 9 bytes

```
xŒPP€ḟḶ}Ṃ

```

**O(2n•length(f))** runtime and memory usage make this a theoretical solution.

Try it online!
> 2 votes

# Answer
# Haskell, 46 bytes

This is a port of KSab's excellent Python answer. Thanks to Laikoni for their help in debugging and golfing this answer in the PPCG Haskell chatroom, Of Monads and Men. Golfing suggestions welcome! Try it online!

```
(#1)
(l#x)n|x<n=minimum[(l#(x*e))n|e<-l]|1>0=x

```
> 2 votes

# Answer
## Mathematica, 73 bytes

```
1±_=1>0;n_±f_:=Or@@(#∣n&&n/#±f&/@f);n_·f_:=NestWhile[#+1&,n,!#±f&]

```

Essentially a port of Rod's Python answer. Defines two binary operators `±` and `·`. `n±f` returns `True` if `n` is a product of elements of `f` and `False` otherwise. `n·f` gives the smallest integer `i`. If someone can figure out a way to eliminate the divisibility test, I could save 10 bytes by using the ISO 8859-1 encoding.

# Explanation

```
1±_=1>0;                         (* If the first argument is 1, ± gives True. *)
n_±f_:=Or@@(#∣n&&n/#±f&/@f);     (* Recursively defines ±. *)
                                 (* For each element of f, check to see if it divides n. *)
                                 (* For each element # that does, check if n/# is a product of elements of f. *)
n_·f_:=NestWhile[#+1&,n,!#±f&]   (* Starting with n, keep incrementing until we find an i that satisfies i±f. *)

```
> 1 votes

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

*Saved 3 bytes thanks to @DanielIndie*

Takes input in currying syntax `(n)(a)`.

```
n=>m=a=>(g=k=>k<n?a.map(x=>g(k*x)):k>m?0:m=k)(1)|m

```

### Test cases

```
let f =

n=>m=a=>(g=k=>k<n?a.map(x=>g(k*x)):k>m?0:m=k)(1)|m

console.log(f(10)([2,3,5]))                // -> 10
console.log(f(17)([3,7]))                  // -> 21
console.log(f(61)([3,5,2,7]))              // -> 63
console.log(f(23)([2]))                    // -> 32
console.log(f(23)([3]))                    // -> 27
console.log(f(23)([2, 3]))                 // -> 24
console.log(f(31)([3]))                    // -> 81
console.log(f(93)([2,2,3]))                // -> 96
console.log(f(91)([2,4,6]))                // -> 96
console.log(f(1,)([2,3,5,7,11,13,17,19]))  // -> 1
console.log(f(151)([20,9,11]))             // -> 180
console.log(f(11616)([23,32]))             // -> 12167
console.log(f(11616)([23,32,2,3]))         // -> 11664 = 2^4 * 3^6
console.log(f(5050)([3,6,10,15,21,28,36,45,55,66,78,91,105,120,136,153,171,190,210])) // -> 5103 = 3^6 * 7
console.log(f(12532159)([57,34,12,21]))    // -> 14183424 = 12^5 * 57
```

### How?

```
n => a => (                 // given n and a
  g = k =>                  // g = recursive function taking k
    k < n ?                 // if k is less than n:
      a.map(x => g(k * x))  //   recursive calls to g with x * k for each x in a
    :                       // else:
      k > m ?               //   if k is greater than m and m is not set to NaN:
        0                   //     ignore this result
      :                     //   else:
        m = k               //     update m to k
  )(                        // initial call to g with:
    1,                      //   k = 1
    m = +a                  //   m = either NaN or the single integer contained in a
  ) | m                     // return m

```
> 1 votes

# Answer
# , 52 bytes

```
function(n,f)min((y=(x=outer(f,0:n,"^"))%o%x)[y>=n])

```

Try it online!

It's been 3 weeks, so I thought I'd finally post my own solution. This is a brute force approach.

There is, however, a builtin:

# , 5 bytes

```
nextn

```

Try it online!

From the R docs:

> `nextn` returns the smallest integer, greater than or equal to `n`, which can be obtained as a product of powers of the values contained in `factors`. `nextn` is intended to be used to find a suitable length to zero-pad the argument of `fft` to so that the transform is computed quickly. The default value for `factors` ensures this.

Some testing revealed a bug in the implementation, however, as the TIO link above shows.

`nextn(91,c(2,6))` should return 96, but returns 128 instead. This obviously only occurs when `factors` are not all relatively prime with one another. Indeed, the C code underlying it reveals that `nextn` greedily tries to divide each `factor` in turn until `1` is reached:

```
static Rboolean ok_n(int n, int *f, int nf)
{
    int i;
    for (i = 0; i < nf; i++) {
    while(n % f[i] == 0) {
        if ((n = n / f[i]) == 1)
        return TRUE;
    }
    }
    return n == 1;
}

static int nextn0(int n, int *f, int nf)
{
    while(!ok_n(n, f, nf))
    n++;
    return n;
}

```

This can be solved by taking input in decreasing order.
> 1 votes

---
Tags: code-golf, arithmetic, integer
---


title: Five Character ASCII Map

text:
# Question
Title: Five Character ASCII Map
*Note: In this post, the terms 'character' and 'color' mean essentially the same thing*

This image:

can be represented as

```
....'''333
.eeee'''3e
..dddd33ee
%%%dd####e

```

(mapping colors to ascii characters)

The four color theorem states that "given any separation of a plane into contiguous regions, producing a figure called a map, no more than four colors are required to color the regions of the map so that no two adjacent regions have the same color. Two regions are called adjacent if they share a common boundary that is not a corner, where corners are the points shared by three or more regions." - Wikipedia (link)

This means that it should be possible to color a map using four colors so that no two parts which share an edge share a color.

The algorithm to color a map using only four colors is complicated so in this challenge your program only needs to color the map using five or less colors.

The previous map recolored could look like this:

which could be represented as

```
....'''333
.eeee'''3e
..dddd33ee
333dd....e

```

or equivalently

```
@@@@$$$!!!
@^^^^$$$!^
@@<<<<!!^^
!!!<<@@@@^

```

**Challenge:**

Given a "map" made of ascii characters (where each character represents a different color), "recolor" the map (represent the map using different ascii characters) so that it only uses five or less colors.

**Example:**

Input:

```
%%%%%%%%%%%%##########$$$$$$$$%%
*****%%%####!!!!!!!%%%%%%%%%#^^^
(((((((***>>>>??????????%%%%%%%%
&&&&&&&&$$$$$$$^^^^^^^))@@@%%%%%
^^^^^^%%%%%%%%%%%%##############

```

Possible output:

```
11111111111122222222223333333311
44444111222255555551111111112444
22222224441111444444444411111111
55555555222222255555553355511111
22222211111111111122222222222222

```

**Clarifications:**

* The input map will always use six or more characters
* You may use any five different characters in the output
* You can use less than different five characters in the output
* You may take the input in any reasonable format (including an array of arrays, or an array of strings)
* This is code-golf so the shortest answer wins.

Sandbox link

# Answer
> 6 votes
# Python 2, ~~375~~ ~~361~~ ~~359~~ ~~357~~ ~~355~~ ~~353~~ ~~350~~ 347 bytes

```
e=enumerate
C=set('12345')
def f(s):
 s=[map(ord,l)for l in s]
 for i,v in e(s):
	for j,w in e(v):
	 if{w}-C:
		F,N=g([],s,i,j,w)
		for y,x in F:s[y][x]=min(C-N)
 return s
def g(m,s,i,j,c):
 n={s[i][j]}
 if(n^{c}or(i,j)in m)<1:
	m+=(i,j),
	for x,y in(0,1),(0,-1),(1,0),(-1,0):
	 if len(s)>i+x>-1<j+y<len(s[0]):m,N=g(m,s,i+x,j+y,c);n|=N
 return m,n

```

Try it online!

Takes input as a list of strings, and returns a list of lists

`f` takes the map input and colors it, `g` returns all connected characters and the set of their neighbors, to the area can be colored with a distinct color.

---
Tags: code-golf
---


# Question
Title: Solve the equation `a*x == b` with Int32 arithmetics
In this thread we use 32-bit signed integers (assuming the usual two's complement). For simplicity I shall call this type Int32. The range is from `-2147483648` through `2147483647`. Any two values can be successfully multiplied (the result is an Int32 as well) since we use multiplication without overflow checking (we only keep the 32 least significant bits of the product).

For example, we have:

```
2147483647 * 2 == -2

```

and so on.

If your language does not have native support for 32-bit signed integers (with two's complement), you must emulate it.

Your task is to solve the equation:

```
a * x == b

```

where `a` and `b` are given as input, and it is assumed that `a` is an odd number (i.e. least significant bit is `1`). You output an Int32 value.

* The input to your program shall be two Int32 values `a` and `b`, and `a` will be odd
* The output must be one Int32 value such that (if we call the output `x`) `a*x == b`
* You do not have to handle invalid input; in particular, if the argument `a` is an even number, it does not matter what your code does
* Code golf

**Test cases:**

```
Input                  Output

1,42                   42
3,126                  42
5,5                    1

-3,126                 -42
3,-126                 -42
-3,-126                42

2147483647,-2          2
2147483647,2           -2
2147483647,666         -666

3,0                    0
3,1                    -1431655765
3,2                    1431655766

-387907419,1342899768  1641848792
348444091,1076207126   -1334551070
10,14                  irrelevant (illegal input)

```

In the last case `[a,b]==[10,14]`, even if there is a solution `x = -1717986917` (not unique, `x = 429496731` also works), you do not have to handle that case (`10` is not odd).

# Answer
> 3 votes
# Python 3, 39 bytes

```
lambda a,b,h=2**31:(a**~-h*b+h)%(2*h)-h

```

This is a theoretical solution that will take a *long* time unless **a = 1**. It uses the Euler-Fermat theorem to determine the modular inverse of **a**.

### Alternate version, 47 bytes

```
lambda a,b,h=2**31:(pow(a,h-1,2*h)*b+h)%(2*h)-h

```

This does exactly the same, but in a more efficient manner.

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), 44 bytes

```
a->b->{for(int i=0;;i++)if(a*i==b)return i;}

```

Try it online!

-12 bytes by using a currying lambda thanks to Kevin Cruijssen

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

```
Mod[#2PowerMod[#,-1,m=2^32],m,-m/2]&

```

Try it online!

---
Tags: code-golf, arithmetic, integer, division
---


title: Triangles of Hexagons

text:
# Question
Title: Triangles of Hexagons
Suppose an infinite tiling of hexagons composed of `|/\` characters.

```
 / \ / \ / \ / \
|   |   |   |   |
 \ / \ / \ / \ /  etc.
  |   |   |   |
   \ / \ / \ /

```

Given input `n > 0`, output a triangular portion of that tiling as depicted in the below examples, anchored with a `_` in the middle of a hexagon:

```
n=1
\_/

n=2
\/ \/
 \_/

n=3
\  |  /
 \/ \/
  \_/

n=4
\/ \ / \/
 \  |  /
  \/ \/
   \_/

n=5
\  |   |  /
 \/ \ / \/
  \  |  /
   \/ \/
    \_/

n=6
\/ \ / \ / \/
 \  |   |  /
  \/ \ / \/
   \  |  /
    \/ \/
     \_/

n=7
\  |   |   |  /
 \/ \ / \ / \/
  \  |   |  /
   \/ \ / \/
    \  |  /
     \/ \/
      \_/

n=8
\/ \ / \ / \ / \/
 \  |   |   |  /
  \/ \ / \ / \/
   \  |   |  /
    \/ \ / \/
     \  |  /
      \/ \/
       \_/

and so on

```

### Rules

* Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, returned as a list of strings, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Python 2, 86 bytes

```
i=k=input()
while i:i-=1;print(" "*(k+~i)+"\\"+i*' /  |\  '[i%2::2])[:k-~i]+"_/"[i>0:]

```

Try it online!

One of Erik’s tricks allowed me to golf 3 bytes! Saved 3 bytes thanks to Jonathan Allan.

## How this works

First off, this gets input from STDIN and assigns it to two separate variables `i` and `k`. Then, while the variable `i` is truthy, we decrement it and generate the strings accordingly; this is a shorthand for looping from the input - 1 all the way down to 0.

### Generating the Strings

I'll split this into more parts:

* First off, getting the leading spacing is achieved with `" "*(k+~i)`. Since `i` is mapped through the range **(input, 0\]**, we must subtract it from `k` (our safely stored original input), decrement and repeat a space that many times.
* `+"\\"` \- Adds the character `"\"` to the spaces above.
* `' / |\ '[i%2::2]` \- Generates our two strings, namely `"/ \ "` and `" | "`, in the following manner:

+ If `i` is odd, **i % 2** is **1**, thus `[i%2::2]` returns each 2 characters of our larger string, starting at index **1** (0-indexed).
    + If `i` is even, **i % 2** is **1**, thus the mechanism above does the same except it starts at index **0**.
* `+~-i*` \- Repeats the string generated above, either `"/ \ "` or `" | "`, **i-1** times, and appends it to the other strings. The benefit of the bitwise operator (`~` \- Bitwise Complement, Equivalent to **i** subtracted from **-1**) is that it doesn't require parenthesis in this context.
* `[:k-~i]` \- Gets all the characters of the strings concatenated above until index **k-~i = k - (-1 - i) = k + 1 + i**.
* `+"_/"[i>0:]` \- This only adds `"/"` if **i ≥ 1**, else it appends `_/`.

## Full example / execution details

Let's grab an example of how things work for an input of **4**:

```
i=k=input()        # i and k are assigned to 4.
while i:           # Starts the loop. The initial value of i is 4.
i-=1;              # Decrement i. i is now 3.
" "*(k+~i)         # A space repeated k - 1 - i = 4 - 1 - 3 = 0 times.
+"\\"              # Plus the character "\". CS (Current string): "\".
' /  |\  '[i%2::2] # The string ' /  |\  '[3%2::2] = ' /  |\  '[1::2] = "/ \ ".
i*                 # ^ repeated i = 3 times: "/ \ / \ / \ ".
+                  # And concatenate. CS: "\/ \ / \ / \ "
[:k-~i]            # Get the characters of ^ up to index k + 1 + i = 4 + 1 + 3 = 8.
                   # CS: "\/ \ / \".
+"_/"[i>0:]        # Append "_/"[i>0:] = "_/"[3>0:] = "_/"[1:] = "/".
                   # CS: "\/ \ / \/".
print              # Output the result "\/ \ / \/".
while i:           # i is truthy (> 0), thus we loop again.
i-=1;              # Decrement i. i becomes 2.
" "*(k+~i)         # " " repeated 4 - 2 - 1 = 1 time.
+"\\"              # Plus "\". CS: " \".
' /  |\  '[i%2::2] # ' /  |\  '[2%2::2] = ' /  |\  '[::2] = "  | ".
+i*                # Repeat i = 2 times and append: "  | ". CS: " \  |  |".
[:k-~i]            # CS up until k + 1 + i = 4 + 2 + 1 = 7. CS: " \  |  ".
+"_/"[i>0:]        # Append "/". CS: " \  |  /".
print              # Outputs the CS: " \  |  /".
while i:           # i is truthy (> 0), thus we loop again.
i-=1;              # Decrement i. i is now 1.
" "*(k+~i)         # " " repeated 4 - 1 - 1 = 2 times.
+"\\"              # Plus "\". CS: "  \".
' /  |\  '[i%2::2] # ' /  |\  '[2%2::2] = ' /  |\  '[::2] = "/ \ ".
+i*                # Repeat i = 1 time and append: "/ \ ". CS: "  \/ \ ".
[:k-~i]            # CS up until k + i + 1 = 4 + 2 = 6. CS: "  \/ \".
+"_/"[i>0:]        # Append "/". CS: "  \/ \/".
print              # Outputs the CS: "  \/ \/".
while i:           # i is truthy (> 0), thus we loop again.
i-=1;              # Decrement i. i is now 0.
" "*(k+~i)         # " " repeated 4 - 1 - 0 = 3 times.
+"\\"              # Plus "\". CS: "   \".
' /  |\  '[i%2::2] # ' /  |\  '[1%2::2] = ' /  |\  '[1::2] = "  | ".
+i*                # Repeat i = 0 times and append: "   \". CS: "   \".
[:k-~i]            # CS up until k + i + 1 = 4 + 0 + 1 = 5. CS: "   \".
+"_/"[i>0:]        # Append "_/" (because i > 0 is False since i == 0). CS: "  \_/".
print              # Outputs the CS: "  \_/".
while i:           # i == 0, hence the condition is falsy and the loop ends.
                   # Program terminates.

```
> 8 votes

# Answer
# Python 2, 90 bytes

```
n=N=input()
while N:print' '*(n-N)+'\\'+(('/   \|  '[N%2::2]*n)[:N*2-1],'_')[N<2]+'/';N-=1

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~123~~ ~~112~~ ~~110~~ ~~109~~ ~~100~~ ~~98~~ 96 bytes

```
i=n=input()
while i:a=i%2;print' '*(n-i)+'\%s/'%['_',((-~i/2)*'/   \  |'[a::2])[a:~a]][i>1];i-=1

```

Try it online!

* Saved a bunch of bytes by using input and string formatting as in Rod's answer
* Saved 2 bytes thanks to Mr. Xcoder
> 2 votes

# Answer
# 05AB1E, 33 bytes

```
1ŸεÐi'_ë"/ \   | "4ôsès∍}'\ì.∞}.c

```

Try it online!
> 2 votes

# Answer
# Mathematica, 131 bytes

```
Join[Table[s=StringRiffle@Table[If[OddQ@i,"/ \\"," | "],⌈i/2⌉];""<>{"\\",If[!OddQ@i,{" ",s," "},s],"/"},{i,#-1,1,-1}],{"\_/"}]&

```

returns a list of strings

Try it online!
> 2 votes

# Answer
# Retina, ~~129~~ ~~119~~ 112 bytes

```
\d+
$*

¶$`a $'$'
m`$
/
  /$
_/
^.¶

a(    )*/
a$#1/
\d+
$*
1
/ a
 (    )*/
$#1/
\d+
$*
1
 |
a /¶
a/¶
a
\

```

Try it online!
> 2 votes

# Answer
# Charcoal, 26 bytes

```
ＮθＧ↖→↓θ“ ″✂=ＡＬ«Q"η\`”←_↖θ‖Ｂ

```

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

# Answer
# Python 2, 103 bytes

```
i=n=input()
while i:print' '*(n-i)+'\%s/'%' '.join(['/\\'*(-~i/2),['_',' '+'| '*(i/2)][i>1]][i%2]);i-=1

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog), ~~97~~ 93 bytes

```
{⍵=1:1 3⍴'\_/'⋄x←' ',' ',⍨∇⍵-1⋄y←1+2×⍵-1⋄2|⍵:x⍪⍨'\','/',⍨y⍴'  | '⋄x⍪⍨'\/','\/',⍨(y-2)⍴' \ /'}

```

Try it online!
> 1 votes

# Answer
# SOGL V0.12, ~~28~~ 27 bytes

```
╔.H∫"C↕‽«‘4nwιF«Im}¹⌡¾\/¹№╚

```

Try it Here!
> 1 votes

# Answer
# Haskell, ~~96~~ 95 bytes

```
f n=[([1..n-x]>>" ")++'\\':take(2*x+1)(cycle$("_":a)!!x)++"/"|x<-[n,n-1..0]]
a="/ \\ ":"  | ":a

```

Try it online!

0-indexed and returns a list of lines.
> 1 votes

# Answer
## Haskell, ~~101~~ 99 bytes

```
j 1=["\\_/"]
j n|r<-([1,3..n-1]>>)=('\\':cycle[init$r"/ \\ ",' ':r" |  "]!!n++"/"):map(' ':)(j$n-1)

```

Returns a list of lines.

Try it online!

How it works:

```
j 1=["\\_/"]               -- base case, n=1

j n                        -- for all other n
   |r<-([1,3..n-1]>>)      -- let r be the function that makes n/2 copies of
                           -- it's argument
   =                       -- the result is
      '\\':                --  a backslash, followed by
      cycle[  ]!!n         --  the inner part, which is
          init$r"/ \\ "    --    all but the last char of some copies of
                           --    "/ \ " for even line numbers, or
          ' ':r" |  "      --    some copies of " |  " prepended by a space
                           --    for odd line numbers
                           --    (chosen by indexing an infinite list of
                           --     both values alternating)
      ++"/"                --  followed by a slash
    :                      --  and append a
               j$n-1        --  recursive call with n-1
      map(' ':)            --  where each line is prepended by a space

```

Edit: @Laikoni saved two bytes. Thanks!
> 0 votes

# Answer
# Java (OpenJDK 8), ~~315~~ 306 bytes

```
i->{String r="";int j=0,k,u=i*2;char[][]c=new char[i][u+1];c[i-1][i]=95;for(;j<i;r+="".valueOf(c[j++]).replace('\0',' ')+"\n")for(k=0;k<u+1;k++){if(k==j)c[j][k]=92;if(k==u-j)c[j][k]=47;if(k>j&k<u-j)if((i-j)%2<1)c[j][k]=(k-j-1)%2<1?(char)(47+((k-j-1)/2)%2*45):32;else if((k-j-1)%4==2)c[j][k]='|';}return r;}

```

Try it online!
> 0 votes

# Answer
# Java (OpenJDK 8), 198 bytes

Finally got it below 200 bytes. Will probably post an explanation later.

```
i->{for(int k=i+1;i>0;System.out.println(("".format("%"+(k-i)+"s","")+"\\"+(i<2?"":"".format("%"+(i-1)+"s","")).replace(" ","/ \\ ,  | ".split(",")[i%2])).substring(0,i<2?k:k+i)+(--i<1?"_/":"/")));}

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), ~~89~~ 85 bytes

```
f=(y,s='\\')=>--y?s+(y&1?' / \\':' |  ').repeat(y).slice(~y-y)+`/
`+f(y,' '+s):s+'_/'

```

### Demo

```
f=(y,s='\\')=>--y?s+(y&1?' / \\':' |  ').repeat(y).slice(~y-y)+`/
`+f(y,' '+s):s+'_/'

console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
console.log(f(5))
console.log(f(6))
console.log(f(7))
```
> 0 votes

# Answer
# CJam, 43

```
ri_{S*'\@(:X"  | / \ "4/=X*X2*)<'_e|'/NX}/;

```

Try it online
> 0 votes

# Answer
# PHP, 89+1 bytes

```
while($k=$argn-$n)echo($p=str_pad)("",$n++),$p("\\",2*$k,$k>1?$k&1?"  | ":"/ \ ":_),"/
";

```

Run as pipe with `-nR` or try it online.
> 0 votes

# Answer
# Pyth,  ~~46~~  44 bytes

```
j_m+<++*;t-Qd\\*d%2>" /  |\  "%d2h+Qd>"_/"._

```

**Try it here!**
> 0 votes

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


# Question
Title: Magic email transformation! Or: help the NSA extract your metadata from your email address
Given an email address, the result of a transformation applied to that email address, and a second email address, return the output of the same transformation applied to the second email address.

The email addresses will all have the following structure:

A string of positive length containing alphanumeric characters and at most one `.` (the local part), followed by an `@` symbol, followed by a string of positive length containing alphanumeric sumbols (the domain), followed by a `.` symbol, and a final string of positive length containing alphanumeric characters (the TLD).

There are four allowed transformations:

* Identity (no change). (`a.b@c.d -> a.b@c.d`)
* Returning just the local part (everything before the `@`) unmodified (`a.b@c.d -> a.b`).
* Returning the local part split on the `.` if present, with the first symbol of each half capitalised. (`a.b@c.d -> A B`).
* Returning just the domain (everything between the `@` and the final `.`) unmodified. (`a.b@c.d -> c`).

When more than one transformation is possible, you can give the output of any of the possibilities. Whitespace at the start and end of output don't matter, but in the middle does (i.e. if you split `a.b` to `A B` there should be just one space in the middle \[and any number at the start and end of output\], but if you split `a.`, then `A` with any number of spaces on either side are all acceptable).

Examples (`input | output`):

```
john.doe@gmail.com, John Doe, phillip.maini@gmail.com         | Phillip Maini
John.Doe@gmail.com, John Doe, Phillip.Maini@gmail.com         | Phillip Maini
foo.bar@hotmail.com, foo.bar, gee.whizz@outlook.com           | gee.whizz
foo.bar@hotmail.com, foo.bar, gEe.Whizz@outlook.com           | gEe.Whizz
rodney.dangerfield@comedy.net, comedy, michael.scott@office.0 | office
.jones@x.1, Jones, a.@3.z                                     | A
.jones@x.1, .jones@x.1, a.@3.z                                | a.@3.z
.jones@x.1, .jones, a.@3.z                                    | a.
.jones@x.1, x, a.@3.z                                         | 3
.@b.c, .@b.c, 1@2.3                                           | 1@2.3
john.jones@f.f, John Jones, 1in.thehand@2inthe.bush           | 1in Thehand
chicken.soup@q.z, Chicken Soup, fab@ulou.s                    | Fab
lange@haare.0, lange, fat.so@fat.net                          | fat.so
Lange@haare.0, Lange, fat.so@fat.net                          | {fat.so, Fat So} # either acceptable
chicken@chicken.chicken, chicken, horse@pig.farm              | {horse, pig} # either acceptable

```

Usual rules and loopholes apply.

# Answer
# Java 8, ~~254~~ ~~240~~ 236 bytes

```
(a,b,c)->{String A[]=a.split("@"),C[]=c.split("@"),x="";for(String p:C[0].split("\\."))x+=(p.charAt(0)+"").toUpperCase()+p.substring(1)+" ";return a.equals(b)?c:A[0].equals(b)?C[0]:A[1].split("\\.")[0].equals(b)?C[1].split("\\.")[0]:x;}

```

-4 bytes thanks to *@LukeStevens*.

**Explanation:**

Try it here.

```
(a,b,c)->{                  // Method with three String parameters and String return-type
  String A[]=a.split("@"),  //  Split `a` by "@" into two parts
         C[]=c.split("@"),  //  Split `c` by "@" into two parts
         x="";              //  Temp-String
  for(String p:C[0].split("\\."))
                            //  Loop over the first part of `c`, split by dots
    x+=                     //   Append String `x` with:
       (p.charAt(0)+"").toUpperCase()
                            //    The first character as uppercase
       +p.substring(1)      //    + the rest of the String
       +" ";                //    + a space
                            //  End of loop (implicit / single-line body)
  return a.equals(b)?       //  If input `a` and `b` are exactly the same:
    c                       //   Return `c`
   :A[0].equals(b)?         //  Else-if the first part of `a` equals `b`:
    C[0]                    //   Return the first part of `c`
   :A[1].split("\\.)[0].equals(b)?
                            //  Else-if the domain of `a` equals `b`
    C[1].split("\\.)[0]     //   Return the domain of `c`
   :                        //  Else:
    x;                      //   Return String `x`
}                           // End of method

```
> 4 votes

# Answer
# Jelly, 40 bytes

<sup>Pre-emptive thanks to Erik the Outgolfer for noticing the failure of using `Œt` (title-case) and hence `Œu1¦€K` over `ŒtK`</sup>

-1 byte thanks to Erik the Outgolfer (rearrangement of `⁵⁸ç⁹¤Ŀ` to `çµ⁵⁸Ŀ`)

```

ÑṪṣ”.Ḣ
ṣ”@
ÇḢ
Çṣ”.Œu1¦€K
⁹ĿðÐ€5i
çµ⁵⁸Ŀ

```

A full program taking `exampleEmail`, `exampleOutput`, `realEmail` and printing the result.

**Try it online!**

### How?

Performs all four transforms (plus a precursor one), finds the first one that yields the example from the first email, then applies it to the second email:

```
            - Link 1, do nothing: email
            - do nothing but return the input

ÑṪṣ”.Ḣ      - Link 2, the domain: email
Ñ           - call the next link (3) as a monad (split at "@")
 Ṫ          - tail
  ṣ”.       - split at "."
     Ḣ      - head

ṣ”@         - Link 3, split at @: email
ṣ”@         - split at "@"

ÇḢ          - Link 4, local part: email
Ç           - call the last link (3) as a monad (split at "@")
 Ḣ          - head

Çṣ”.Œu1¦€K  - Link 5, name-ified: email
Ç           - call the last link (4) as a monad (get the local part)
 ṣ”.        - split at "."
       ¦€   - for €ach sparsley apply:
      1     - ...to index: 1
    Œu      - ...action: uppercase
         K  - join with space(s)

⁹ĿðÐ€5i     - Link 6, index of first correct link: exampleEmail; exampleOutput
   Ð€5      - map across (implicit range of) 5 (i.e. for each n in [1,2,3,4,5]):
  ð         -   dyadicly (i.e. with n on the right and exampleEmail on the left):
 Ŀ          -     call referenced link as a monad:
⁹           -     ...reference: chain's right argument, n
      i     - first index of exampleOutput in the resulting list

çµ⁵⁸Ŀ       - Main link: exampleEmail; exampleOutput
ç           -   call the last link (6) as a dyad (get the first "correct" link index)
 µ          - monadic chain separation (call that L)
   ⁸        - chain's left argument, L
    Ŀ       - call the link at that reference as a monad with input:
  ⁵         -   program's third input, realEmail

```

Notes:

1. Assumes the input exampleOutput is strictly the same as the output would be.
2. The "precursor" (the result of link 3) is tested for matching the `exampleOutput`, but it won't match unless the `exampleOutput` itself is a list of lists of characters. As such the inputs should probably be quoted (Python formatting may be used here) to avoid the possibility of interpreting it as such.
> 3 votes

# Answer
# Haskell, 208 bytes

```
import Data.Char
s c""=[]
s c a=w:f t where
 (w,t)=span(/=c)a
 f(_:y)=s c y
 f _=[]
h=head
u""=""
u(x:y)=toUpper x:y
l=h.s '@'
f x y=h[t|t<-[id,l,unwords.filter(/="").map u.s '.'.l,h.s '.'.last.s '@'],t x==y]

```

Try it online!

It is sad I had to spend 59 bytes on reinventing `split` (`s`).

The solution creates a list of transformations and returns the first one that leads to the expected result.
> 3 votes

# Answer
# Python 2, 135 bytes

```
s,r,x=input()
def f(x):S,D=x.split('@');return x,S,' '.join(map(str.capitalize,S.split('.'))),D.split('.')[0]
print f(x)[f(s).index(r)]

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 145 bytes

Invoke with currying syntax, e.g. `f('chicken.soup@q.z')('Chicken Soup')('fab@ulou.s')`

```
x=>y=>[x=>x,s=x=>x.split`@`[0],x=>s(x).split`.`.map(w=>w&&w[0].toUpperCase()+w.slice(1)).join` `.trim(),x=>/@(.+)\./.exec(x)[1]].find(f=>f(x)==y)

```

```
f=x=>y=>[x=>x,s=x=>x.split`@`[0],x=>s(x).split`.`.map(w=>w&&w[0].toUpperCase()+w.slice(1)).join` `.trim(),x=>/@(.+)\./.exec(x)[1]].find(f=>f(x)==y)

for(const [x, y, z] of [
['john.doe@gmail.com', 'John Doe', 'phillip.maini@gmail.com'], // Phillip Maini
['John.Doe@gmail.com', 'John Doe', 'Phillip.Maini@gmail.com'], // Phillip Maini
['foo.bar@hotmail.com', 'foo.bar', 'gee.whizz@outlook.com'], // gee.whizz
['foo.bar@hotmail.com', 'foo.bar', 'gEe.Whizz@outlook.com'], // gEe.Whizz
['rodney.dangerfield@comedy.net', 'comedy', 'michael.scott@office.0'], // office
['.jones@x.1', 'Jones', 'a.@3.z'], // A
['.jones@x.1', '.jones@x.1', 'a.@3.z'], // a.@3.z
['.jones@x.1', '.jones', 'a.@3.z'], // a.
['.jones@x.1', 'x', 'a.@3.z'], // 3
['.@b.c', '.@b.c', '1@2.3'], // 1@2.3
['john.jones@f.f', 'John Jones', '1in.thehand@2inthe.bush'], // 1in Thehand
['chicken.soup@q.z', 'Chicken Soup', 'fab@ulou.s'], // Fab
['lange@haare.0', 'lange', 'fat.so@fat.net'], // fat.so
['Lange@haare.0', 'Lange', 'fat.so@fat.net'], // {fat.so, Fat So} # either acceptable
['chicken@chicken.chicken', 'chicken', 'horse@pig.farm'], // {horse, pig} # either acceptable
]) console.log( f(x)(y)(z) )
```
> 2 votes

# Answer
# Mathematica, 217 bytes

```
(L=Capitalize;T@x_:=(M=StringSplit)[x,"@"];P@x_:=#&@@T[x];W@x_:=If[StringContainsQ[P@x,"."],StringRiffle@L@M[P@x,"."],L@P@x];Z@x_:=#&@@M[T[x][[2]],"."];If[#==#2,#3,If[#2==P@#,P@#3,If[#2==W@#,W@#3,If[#2==Z@#,Z@#3]]]])&

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~117~~ ~~106~~ 102 bytes

```
->a,b,c{r=[/.*/,/(?<=@)\w*/,/[^@]*/].find{|x|r=c[x];a[x]==b}?r:r.sub(?.," ").gsub(/\b(.)/){$1.upcase}}

```

Try it online!
> 1 votes

# Answer
# Jelly, 43 bytes

```
ḢŒlṣ”.Œu1¦€K
ṣ”@Wẋ4j”@$ḷ/ÇṪṣ”.Ḣ$$4ƭ€
Çiị⁵Ç¤

```

Try it online!
> 1 votes

# Answer
# CJam, 42

```
q~@{[_\'@/~'./0=\_'.%{(eu\+}%S*]}:T~@a#\T=

```

Try it online

**Explanation:**

```
q~        read and evaluate the input (given as 3 quoted strings)
@         bring the first string to the top of the stack
{…}:T     define a function T that calculates the 4 transformations of a string:
  [       begin array
  _\      duplicate the string, and swap with the other copy to bring it in the array
           (1st transformation)
  '@/~    split by '@' and put the 2 pieces on the stack
  './0=   split the 2nd piece by '.' and keep the first part
           (4th transformation)
  \_      swap with the piece before '@' and duplicate it
           (2nd transformation)
  '.%     split by '.', removing the empty pieces
  {…}%    transform the array of pieces
    (eu   take out the first character and capitalize it
    \+    prepend it back to the rest
  S*      join the pieces by space
           (3rd transformation)
  ]       end array
~         execute the function on the first string
@a        bring the 2nd string to the top of the stack, and wrap it in an array
#         find the position of this string in the array of transformations
\T        bring the 3rd string to the top and call function T
=         get the transformation from the array, at the position we found before

```
> 1 votes

# Answer
# PHP 7.1, 176 bytes

```
<?$e=explode;[,$p,$q,$r]=$argv;echo$p==$q?$r:($e('@',$p)[0]==$q?$e('@',$r)[0]:($e('.',$e('@',$p)[1])[0]==$q?$e('.',$e('@',$r)[1])[0]:ucwords(join(' ',$e('.',$e('@',$r)[0])))));

```

Try it online!

# PHP \< 7.1, 180 bytes

Versions under 7.1 would need to change the `[,$p,$q,$r]=$argv` to `list(,$p,$q,$r)=$argv`, adding 4 bytes.
> 1 votes

# Answer
## GNU sed, 105 + 1(r flag) = 106 bytes

The first three `s` commands check for the **identity**, **local part** and **domain** transformations respectively. If one transformation matches, then it is applied to the second email address and the following `s` commands will fail due to a lack of the input format.

```
s:^(.*),\1,::
s:(.*)@.*,\1,(.*)@.*:\2:
s:.*@(.*)\..*,\1,.*@(.*)\..*:\2:
s:.*,([^.]*)\.?(.*)@.*:\u\1 \u\2:

```

Try it online!

The **local part split** transformation (last `s` command) is the most expensive to check, in terms of bytes, therefore I placed it at the end and assumed it matches (since the other ones failed by that time), going directly to its application.
> 1 votes

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


title: Highest or Lowest Occurrences?

text:
# Question
Title: Highest or Lowest Occurrences?
## Challenge:

**Inputs:**

* A string containing printable ASCII (excluding spaces, tabs and new-lines)
* A boolean

**Output:**

The parts of the String are divided into four groups:

* Lowercase letters
* Uppercase letters
* Digits
* Other

Based on the boolean, we either output the highest occurrence of one (or multiple) of these four groups, or the lowest, replacing everything else with spaces.

**For example:**

Input: `"Just_A_Test!"`
It contains:
\- 3 uppercase letters: `JAT`
\- 6 lowercase letters: `ustest`
\- 0 digits
\- 3 other: `__!`

These would be the outputs for `true` or `false`:

```
true:   " ust    est "

// digits have the lowest occurrence (none), so everything is replaced with a space
false:  "            "

```

(Note: You are allowed to ignore trailing spaces, so the outputs can also be `" ust est"` and `""` respectively.)

## Challenge rules:

* The input will never be empty or contain spaces, and will only consist of printable ASCII in the range `33-126` or `'!'` through `'~'`.
* You are allowed to take the input and/or outputs as character-array or list if you want to.
* Any two consistent and distinct values for the boolean are allowed: `true`/`false`; `1`/`0`; `'H'`/`'L'`; `"highest"`/`"lowest"`; etc. Note that these distinct values should be used (somewhat) as a boolean! So it's not allowed to input two complete programs, one that gives the correct result for `true` and the other for `false`, and then having your actual code only be `<run input with parameter>`. *Relevant new default loophole I've added, although it can still use a lot of finetuning regarding the definitions..*
* If the occurrence of two or more groups is the same, we output all those occurrences.
* The necessary trailing spaces are optional, and a single trailing new-line is optional as well. Necessary leading spaces are mandatory. And any other leading spaces or new-lines aren't allowed.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases:

```
Inputs:                              Output:

"Just_A_Test!", true                 " ust    est "     (or " ust    est")
"Just_A_Test!", false                "            "     (or "")
"Aa1!Bb2@Cc3#Dd4$", either           "Aa1!Bb2@Cc3#Dd4$"
"H@$h!n9_!$_fun?", true              " @$ !  _!$_   ?"
"H@$h!n9_!$_fun?", false             "H     9        "  (or "H     9")
"A", true                            "A"
"A", false                           " "                (or "")
"H.ngm.n", true                      "  ngm n"
"H.ngm.n", false                     "       "          (or "")
"H.ngm4n", false                     "H.   4 "          (or "H.   4")

```

# Answer
> 4 votes
# Husk, ~~27~~ ~~26~~ ~~24~~ 22 bytes

-2 bytes thanks to Zgarb

-2 bytes thanks to Leo

Takes `' '` as `False` and `'a'` as `True` (In Husk, whitespace in Fasly and all other characters are Truthy)

```
Fż▲→ġ#¬Ö#≡⁰Ṫḟë½D±o¬□m;

```

Try it online!

### How does it work?

```
Fż▲→ġ#¬Ö#≡⁰Ṫḟë½D±o¬□m;   Function, takes a character c and a string S as arguments
                    m;   Wrap each character in S into it's own string
             ë           List of four functions returning booleans:
              ½D±o¬      Lower case?,Upper case?,Digit?,Not alphanumeric?
           Ṫḟ            Outer product with find†
       Ö#≡⁰              Sort on how many characters have the same Truthyness as c
    ġ#¬                  Group strings with equal numbers of spaces
   →                     Take the last group
Fż▲                      Squash it all into one list

```

is a function that takes a predicate `p` and a list `L` and returns the first element of `L` that satisfies `p`. If no element satisfies `p` a default argument is returned. In this case `' '`. By applying  to a one character string, we are essentially saying `if p c then c else ' '`.

Is function that takes a function `f` and two lists `L1`,`L2`. It returns a table of `f` applied over all pairs of `L1` and `L2`. In this case `f` is , `L1` is our list of 4 functions, and `L2` is the list of one character strings.

After `Ṫḟ` we have a list of strings where each string is the result of replacing characters which don't satisfy one of the rules with a `' '`.

**NB:** In newer versions of Husk, `ġ#¬Ö#≡⁰` can be replaced by `k#≡⁰` for a 3 byte saving!

# Answer
> 7 votes
# Jelly, 31 bytes

```
ØṖḟØBṭØBUs26¤f€³Lİ⁴¡$ÐṀFf
¹⁶Ç?€

```

**Try it online!**

The boolean values are `2` and `1` (or any other positive even/odd pair), which represent `True` and `False` respectively. I will try to add an explanation after further golfing.

Thanks to caird coinheringaahing for saving 2 bytes, and to Lynn for saving 4 bytes! Thanks to one of Erik's tricks, which inspired me to save 4 bytes!

## How it works

Note that this is the explanation for the 35-byte version. The new one does roughly the same (but tweaked a bit by Lynn), so I won't change it.

```
ØBUs26f€³µ³ḟØBW,µẎLİ⁴¡$ÐṀF - Niladic helper link.
ØB                         - String of base digits: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
                             abcdefghijklmnopqrstuvwxyz'.
  U                        - Reverse.
   s26                     - Chop into sublists of length 26, preserving shorter
                             trailing substrings.
      f€³                  - For each, keep the common characters with the input.
            ØB             - Base digits.
          ³ḟ               - Get the signs in the input. Filter the characters of the
                             input that aren't alphanumeric.
              W,µẎ         - Concatenate (wrap, two element list, tighten).
                       ÐṀ  - Keep the elements with maximal link value.
                  L        - Length.
                    ⁴¡     - Do N times, where N is the second input.
                   İ       - Inverse. Computes 1 ÷ Length. 2 maps to the length itself,
                             because 1 ÷ (1 ÷ Length) = length; 1 yields
                             (1 ÷ Length), swapping the maximal numbers with minimal ones.
                         F - Flatten.

¹⁶e¢$?€ - Main link.
      € - For each character.
   e¢?  - If it is contained by the last link (called niladically), then:
¹       - Identity, the character itself, else:
 ⁶      - A space.

```

# Answer
> 5 votes
# Python 2, ~~166~~ 158 bytes

```
t=lambda c:('@'<c<'[','`'<c<'{','/'<c<':',1-c.isalnum())
def f(s,b):x=map(sum,zip(*map(t,s)));print''.join([' ',c][x[t(c).index(1)]==sorted(x)[-b]]for c in s)

```

Try it online!

# Answer
> 5 votes
# , ~~193~~ ~~186~~ ~~179~~ 158 bytes

*-7 bytes thanks to NofP and his suggestion of `cbind`*

*-6 bytes using `outer`, -1 byte switching `[^a-zA-Z0-9]` with `[[:punct:]]`*

*-21 bytes thanks to MickyT for pointing out a list of characters is allowed*

```
function(S,B){y=outer(c("[a-z]","[A-Z]","\\d","[[:punct:]]"),S,Vectorize(grepl))
S[!colSums(y[(s=rowSums(y))=="if"(B,max,min)(s),,drop=F])]=" "
cat(S,sep='')}

```

Verify all test cases

Takes `1/T` as truthy (`max`) and `0/F` as falsey (`min`), and takes `S` as a list of single characters.

Try it online!

In my original version (with NofP's suggestions), the matrix `y` is constructed by evaluating `grepl(regex, S)` for each `regex`, then concatenating them together as columns of a matrix. This results in multiple calls to `grepl`, but as `S` is fixed, it seemed that something else needed to be done. As I noted:

> There are potentially shorter approaches; `mapply`, for example:
>
> `y=mapply(grepl,c("[a-z]","[A-Z]","\\d","[^a-zA-Z0-9]"),list(S))`
>
> unfortunately, this will not simplify as a matrix in the 1-character example of `"A"`.

I used `outer` rather than `mapply`, which *always* returns an array (a matrix in this case), and was forced to `Vectorize` `grepl`, which is really just an `mapply` wrapper around it.

I also discovered the predefined character group `[:punct:]` which matches punctuation (non-space, non-alphanumeric) characters.

# Answer
> 4 votes
# Husk, ~~31 29~~ 28 bytes

```
SMS?' `ṁ§foSM≠?▲▼⁰M#Kë½D±o¬□

```

Uses 0 for minimal and 1 for maximal character counts. Try it online!

## Explanation

Lists of functions are cool.

```
SMS?' `ṁ§foSM≠?▲▼⁰M#Kë½D±o¬□  Inputs are bit B and string S.
                     ë        Make a list L of the four functions
                      ½       is-lowercase-letter,
                       D      is-uppercase-letter,
                        ±     is-digit, and
                         o¬□  not is-alphanumeric.
                  M#          For each of them, take number of matches in S,
              ?▲▼⁰            take maximum or minimum depending on B,
          oSM≠                and mark those entries that are not equal to it.
        §f          K         Remove from L the functions that correspond to marked entries, call the result L2.
                              These functions test whether a character should be replaced by a space.
SM                            Do this for each character C in S:
      `ṁ                      Apply each function in L2 to C and sum the results.
  S?'                         If the result is positive, return space, otherwise return C.

```

# Answer
> 4 votes
# Python 2, 140 bytes

```
g=lambda x:x.isalnum()-~(x>'Z')*x.isalpha()
def f(s,m):k=map(g,s).count;print''.join([' ',c][k(g(c))==sorted(map(k,range(4)))[m]]for c in s)

```

Try it online!

Jonathan Frech saved a byte. Thanks!

Highest is `m=-1`, lowest is `m=0`.

# Answer
> 3 votes
# Java (OpenJDK 8), ~~448~~ ~~439~~ ~~432~~ ~~362~~ ~~361~~ ~~354~~ ~~352~~ ~~348~~ ~~343~~ 320 bytes

```
s->b->{int w[]=new int[4],m=0,n=-1>>>1,l;s.chars().forEach(c->{if(c>96&c<123)w[0]++;else if(c>64&c<91)w[1]++;else if(c>47&c<58)w[2]++;else++w[3];});for(int W:w){m=W>m?W:m;n=W<n?W:n;}l=m-n;m=b?m:n;return l<1?s:s.replaceAll("["+(w[0]!=m?"a-z":"")+(w[1]!=m?"A-Z":"")+(w[2]!=m?"\\d]":"]")+(w[3]!=m?"|[^a-zA-Z0-9]":"")," ");}

```

Try it online!

# Answer
> 3 votes
# Jelly, 35 bytes

```
ØWṖs26µẎØṖḟW⁸;
¢ċ@€S¥€N⁹¡Mị¢Ẏ⁸f€ȯ€⁶

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~118~~ 116 bytes

Takes `0` (lowest) or `-1` (highest) for its second argument.

-2 bytes thanks to Lynn.

```
->s,t{s.gsub(/./){|c|[/\d/,/[a-z]/,/[A-Z]/,/[^\da-z]/i].group_by{|x|s.scan(x).size}.sort[t][1].any?{|x|x=~c}?c:" "}}

```

Try it online!

## Ungolfed

```
->s,t{
  s.gsub(/./) {|c|
    [ /\d/,
      /[a-z]/,
      /[A-Z]/,
      /[^\da-z]/i
    ]
    .group_by {|x| s.scan(x).size }
    .sort[t][1]
    .any? {|x| x =~ c } ? c : " "
  }
}

```

# Answer
> 3 votes
# Python 2, ~~190~~ ~~183~~ ~~174~~ 173 bytes

Thanks to Jonathan Frech for shortening it

```
from re import*
def f(i,c):
 q='[a-z]','[A-Z]','\d','[\W_]';l=[len(set(finditer(p,i)))for p in q]
 for j,k in enumerate(l):
	if k-eval(c):i=compile(q[j]).sub(' ',i)
 print i

```

This takes the strings `'max(l)'` and `'min(l)'` as true and false. (I don't think this breaks the rules...?) This is longer than the other two python answers but different so I thought I'd post it. I'm not a great golfer so I'm guessing this could be improved further but all the things I tried didn't work.

Try it online!

# Answer
> 2 votes
# PHP, ~~161~~ 158 bytes

```
for([,$s,$z]=$argv;~$c=$s[$i++];)foreach([punct,upper,lower,digit]as$f)(ctype_.$f)($c)?$$i=$f:$g[$f]++;while(~$c=$s[$k++])echo$g[$$k]-($z?min:max)($g)?" ":$c;

```

Run with `-nr` or try it online.

* first loop: for each position, remember the group of the character
and count the occurences of groups that the current character is *not* in.
(that negation saved 3 bytes)
* depending on second parameter, pick min non-count for truthy, max non-count for falsy.
* second loop: if (group of current character) non-count differs
from min/max non-count then print space, else print character.

# Answer
> 2 votes
## JavaScript (ES6), ~~151~~ 149 bytes

```
g=
(s,f,a=[/\d/,/[A-Z]/,/[a-z]/,/[_\W]/],b=a.map(r=>s.split(r).length))=>s.replace(/./g,c=>b[a.findIndex(r=>r.test(c))]-Math[f?"max":"min"](...b)?' ':c)
```

```
<input id=s oninput=o.textContent=g(s.value,f.checked)><input id=f type=checkbox onclick=o.textContent=g(s.value,f.checked)><pre id=o>
```

Sadly the rules probably don't allow me to pass `Math.max` or `Math.min` as the flag. Edit: Saved 2 bytes thanks to @JustinMariner.

# Answer
> 1 votes
# Jelly, 37 bytes

```
ØWṖs26µẎØṖḟW⁸;
¢f@³L$ÐṂFe@Ð€³¬¹⁴?a³o⁶

```

Try it online!

-6 bytes "borrowing" from Erik's post :D

# Answer
> 1 votes
# Bash, ~~229~~ ~~227~~ 212 bytes

```
LANG=C;g="A-Z a-z 0-9 !A-Za-z0-9";declare -A H
f()(((i=$2?99:-1));r=$1;for h in $g;{ t=${r//[$h]};t=${#t};(($2?t<i:t>i))&&i=$t&&H=([$h]=1);((t-i))||H[$h]=1;};for h in $g;{((${H[$h]}))||r=${r//[$h]/ };};echo "$r")

```

Try it Online

# Answer
> 1 votes
# Java (OpenJDK 8), ~~307 + 34~~ ~~306 + 27~~ 295 bytes

My "interesting" take on the challenge.

Thanks to *Kevin Cruijssen* for ~~cutting down the import bytes~~ removing the import entirely!

```
s->b->{String t=s.replaceAll("\\d","2").replaceAll("[a-z]","0").replaceAll("[A-Z]","1").replaceAll("\\D","3"),v="";int a[]={0,0,0,0},i=0,z=0,y=-1>>>1;t.chars().forEach(j->{a[j%4]++;});for(int x:a){z=x>z?x:z;y=x<y?x:y;}for(;i<s.length();i++)v+=a[t.charAt(i)%4]!=(b?z:y)?" ":s.charAt(i);return v;}

```

Try it online!

**Explanation:**

```
String t=s.replaceAll("\\d","2")
          .replaceAll("[a-z]","0")
          .replaceAll("[A-Z]","1")
          .replaceAll("\\D","3")

```

First replaces each group with an integer between 0 and 3 using some simple regex and stores this in a new String.

`int a[]={0,0,0,0},m,i=0,z=0,y=-1>>>1;`

Initialises an array of integers as well as a couple of other integers to use later. Sets the `y` variable to the max int size using unsigned right bit shift.

`t.chars().forEach(j->{a[j%4]++;});`

For each character in the modified string, this uses its ASCII value modulo 4 to calculate the index of the aforementioned array to increment.

```
for(int x:a){
    z=x>z?x:z;
    y=x<y?x:y;
}

```

This then loops through the counts of each group stored in the array and calculates the minimum (`y`) and the maximum (`z`).

```
for(;i<s.length();i++)
    v+=a[t.charAt(i)%4]!=(b?z:y)?" ":s.charAt(i);

```

Loops through every character in the String again, checking if the group of that characters group is equal to the min/max (using the modulo trick mentioned earlier). If it isn't equal, then a space is added to the new String in the characters place, otherwise the original character is added.

`return v;`

Finally return the new String!

# Answer
> 1 votes
# JavaScript (ES6), 139 bytes

```
s=>b=>s.map(c=>++a[g(c)]&&c,a=[0,0,0,0],g=c=>c>-1?0:/[a-z]/i.test(c)?c<"a"?2:1:3).map(c=>a.map(v=>v-Math[b?"max":"min"](...a))[g(c)]?" ":c)

```

Input and output is an array of characters. Takes actual boolean values for input.

A different approach from @Neil's answer; almost avoiding regular expressions. Instead, I used a series of checks to determine the category of each character:

* Digits return `true` for `c>-1` because non-digits fail mathematical comparisons
* Uppercase letters match the regex `/[a-z]/i` and have codepoints less than `"a"`
* Lowercase letters match that regex but have codepoints not less than `"a"`
* Symbols pass none of those tests

## Test Cases

```
f=
s=>b=>s.map(c=>++a[g(c)]&&c,a=[0,0,0,0],g=c=>c>-1?0:/[a-z]/i.test(c)?c<"a"?2:1:3).map(c=>a.map(v=>v-Math[b?"max":"min"](...a))[g(c)]?" ":c)

;[["Just_A_Test!", true],["Just_A_Test!", false],["Aa1!Bb2@Cc3#Dd4$", true],["Aa1!Bb2@Cc3#Dd4$", false],["H@$h!n9_!$_fun?", true],["H@$h!n9_!$_fun?", false],["A", true],["A", false],["H.ngm.n", true],["H.ngm.n", false],["H.ngm4n", false]]
.forEach(([S,B])=>console.log(`"${S}", ${B} -> "${f(S.split``)(B).join``}"`))
```

```
.as-console-wrapper{max-height:100%!important}
```

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


title: Export The $PATH Variable, Line-By-Line

text:
# Question
Title: Export The $PATH Variable, Line-By-Line
Inspired by this question on AskUbuntu.

Your job is extremely simple. Take the PATH environment variable (`echo $PATH`) and export it such that each entry (separated by the `:` character) is on its own line.

For example, if the PATH is `/bin:/usr/bin:/usr/local/bin`, your program should output:

```
/bin
/usr/bin
/usr/local/bin

```

Your program may not return a leading newline, but it may return a single trailing newline. You do not need to check if the PATH is right, or that the directory exists. Your program should take no input, meaning that your program is responsible for getting the PATH itself. You may safely assume that objects in the PATH do not contain `:` or newlines. However, spaces are fair game.

Reference implementations are present in the answers to the question above.

### Rules

* This is (obviously) code-golf, so the shortest answer will win the prized green checkmark.
* The accepted answer will be tested to make sure it's actually legit.
* Both Windows and \*nix entries are accepted.
    + However, if you don't explicitly specify Windows, I will try running it in Linux and fail. (If it's obvious (hi, Batch!), you don't need to specify explicitly.)
* Only have one solution per answer. If you have both a Windows and \*nix version, I will count the shorter one.
* If two answers have the same length, I will give priority to the one with the higher vote total. If they have the same vote total, I will count the older one. If the time posted is the same, I will choose the one that executes faster. If they execute in the same amount of time, I don't know.

### Leaderboard

```
var QUESTION_ID=96334,OVERRIDE_USER=15422;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 14 votes
# Z shell (zsh), 13 bytes

```
<<<${(F)path}

```

Uses the `$path` parameter, which is a special array parameter used by the shell that is tied to the `$PATH` parameter, and a parameter expansion flag to join an array with newlines.

# Answer
> 14 votes
## Bash/Coreutils, ~~17~~ 16 bytes

```
tr : '
'<<<$PATH

```

# Answer
> 10 votes
## Batch, 41 bytes

```
@for %%a in ("%PATH:;=";"%")do @echo %%~a

```

`PATH` is semicolon-delimited on Windows of course. Conveniently, `for` splits on semicolons by default, but inconveniently, also on spaces, so I have to use string replace trickery to quote each path element before splitting. It then remains to remove the quotes afterwards.

# Answer
> 10 votes
# Z shell (zsh), 15 bytes

```
<<<${PATH//:/
}

```

You can test the code on Anarchy Golf: click *use form*, select *zsh*, paste the code and submit.

## Bash (pure), 19 bytes

```
echo "${PATH//:/
}"

```

Same idea, but with Bash's less golfy syntax. Test it on Ideone.

# Answer
> 7 votes
# Powershell, 20 bytes

```
$env:PATH-split':'

```

Edit:

* ***-2** bytes off. Thanks to @TimmyD*

Old:

```
$env:PATH.split(":")

```

# Answer
> 5 votes
# Ruby, 25 bytes

```
puts ENV["PATH"].split":"

```

# Answer
> 4 votes
## Perl, 22 bytes

```
say$ENV{PATH}=~y/:/
/r

```

Needs `-E` or `-M5.010` to run :

```
perl -E 'say$ENV{PATH}=~y/:/
/r'

```

# Answer
> 3 votes
### Bash+Python, 43 bytes

Let's use shell's variable expansion. It eliminates calling `os.environ` , thus less code and less imports. That gives us 46 bytes, and with `xnor`'s trick and removing space before `-c` we've got 43 bytes.

```
python -c"print('$PATH'.replace(*':\n'))"

```

# Answer
> 3 votes
## GNU `sed` \+ `bash`, 25 bytes:

```
sed 's/:/\n/g' <<<"$PATH"

```

If the `PATH` contains no directory name with whitespace, no quoting needed, 23 bytes:

```
sed 's/:/\n/g' <<<$PATH

```

Even shorter, transliterating `:` to newline, thanks to @Dennis:

```
sed y/:/\\n/<<<"$PATH"

```

# Answer
> 3 votes
## Java, 58 bytes

```
System.out.print(System.getenv("Path").replace(';','\n'));

```

Full program: 106 bytes

```
class E {
    public static void main (String[] args) {
        System.out.print(System.getenv("Path").replace(';', '\n'));
    }
}

```

# Answer
> 3 votes
# Vim, 19 bytes

`"=$PATH<CR>p:s/:/\r/g<CR>`

Grab `$PATH` from the expression register and paste it. Turn the `:`s into newlines. Nothing tricky.

# Answer
> 2 votes
## PHP, ~~36~~ ~~35~~ ~~33~~ 32 bytes

*Saved 1 byte, thanks to Blackhole*
*Saved 2 bytes, thanks to user59178*
*saved 1 byte, thanks to Martijn*

### \*nix version

```
<?=strtr(getenv(PATH),":","
")?>

```

### Windows version

```
<?=strtr(getenv(PATH),";","
")?>

```

# Answer
> 2 votes
# Python 2, 49 bytes

Saving 2 bytes thanks to @xnor and 1 byte by replacing `environ` with `getenv` thanks to @Serg and @Oliver

```
import os
print os.getenv('PATH').replace(*':\n')

```

For Python 3, just add `(` and `)` around the `print` argument and add 1 to the byte count.

# Answer
> 2 votes
# C, ~~85~~ 84 bytes

-1 byte for using `#import`

```
#import<stdlib.h>
main(){char*a=getenv("PATH");while(*a)putchar(*a++==58?10:a[-1]);}

```

# Answer
> 2 votes
# C (x86), 60 bytes

```
f(){char*p=getenv("PATH");for(;*p;p++)putchar(*p-58?*p:10);}

```

This won't work on 64-bit platforms without including *stdlib.h*, since *getenv* returns an *int* (32 bits) while *char* pointers are 64 bits wide.

I have yet to find an online 32-bit C compiler.

# C (x86-64), 70 bytes

```
f(){char*getenv(),*p=getenv("PATH");for(;*p;p++)putchar(*p-58?*p:10);}

```

Instead of including *stdlib.h*, we declare *getenv* ourselves as a function returning a *char* pointer.

I've tested this with gcc and clang on Linux; other setups may cry blood. Try it on Ideone.

# Answer
> 2 votes
# jq, 18 characters

(16 characters code + 2 characters command line option)

```
env.PATH/":"|.[]

```

Sample run:

```
bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

bash-4.3$ jq -nr 'env.PATH/":"|.[]'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin

```

# Answer
> 1 votes
# C#, 64 bytes

```
x=>Environment.GetEnvironmentVariable("PATH").Replace(";","\n");

```

Anonymous function which returns the path variable, each directory on a separate line. Note that `x` is just a dummy object to save 1 byte instead of using `()`.

Full program:

```
using System;

namespace ExportPathVariable
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<object,string>f= x=>Environment.GetEnvironmentVariable("PATH").Replace(";","\n");

            Console.WriteLine(f(0));
        }
    }
}

```

Also works on UNIX systems if you replace `;` with `:`, presuming Mono libraries are available. **Try it online on ideone, .NET Fiddle returns a security exception.**

Alternatively, a full C# program, which is rather verbose:

---

# C#, 118 bytes

```
using System;class P{static void Main(){Console.Write(Environment.GetEnvironmentVariable("PATH").Replace(";","\n"));}}

```

# Answer
> 1 votes
## Racket 39 bytes

Using sed command of @heemayl :

```
(system "sed 's/:/\\n/g' <<<\"$PATH\"")

```

Ungolfed:

```
(define (f)
  (system "sed 's/:/\\n/g' <<<\"$PATH\"")
)

```

Testing:
(f)

Output:

```
/usr/local/bin
/usr/bin
/bin
/usr/games
/usr/lib/java/bin
/usr/lib/java/jre/bin
#t

```

# Answer
> 1 votes
# Scala, 31 bytes

```
sys env "PATH"replace(':','\n')

```

In scala, `a b c` is syntactic sugar for `a.b(c)`, so this compiles to `sys.env("PATH").replace(':','\n')`

# Answer
> 1 votes
# Perl 6,  ~~28 25~~  24 bytes

```
%*ENV<PATH>.split(':')».put

```

```
put %*ENV<PATH>~~tr/:/\n/

```

```
put %*ENV<PATH>~~tr/:/
/

```

# Answer
> 1 votes
# Factor, 28 bytes

for unix-likes. I dunno how to do it on Windows since I'm not at a Windows box.

```
"PATH"getenv ":" "\n"replace

```

# Answer
> 1 votes
## Haskell, 72 bytes

```
import System.Environment
m ':'='\n'
m x=x
map m<$>getEnv"PATH">>=putStr

```

An expensive import and no `replace` within the standard library make it quite long.

# Answer
> 1 votes
# Awk, ~~51~~ 44 characters

```
BEGIN{$0=ENVIRON["PATH"];gsub(":",RS);print}

```

Thanks to:

* ninjalj for suggesting to use `gsub()` instead of manipulating built-in variables (-7 characters)

The typical `awk` way would be to set up the built-in variables which influences how `awk` manipulates the data automatically:

```
BEGIN{FS=":";OFS=RS;$0=ENVIRON["PATH"];$1=$1;print}

```

Sample run:

```
bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

bash-4.3$ awk 'BEGIN{FS=":";OFS=RS;$0=ENVIRON["PATH"];$1=$1;print}'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin

```

# Answer
> 0 votes
# Node.js, 36 bytes

```
_=>process.env.PATH.split`:`.join`
`

```

Pretty straight forward.

# Answer
> 0 votes
# MATLAB, 34 bytes

```
disp(strrep(getenv('PATH'),58,10))

```

Here is an online demo in Octave with a slight modification since `strrep` in octave requires the second and third inputs to be `char` variables rather than numeric values.

# Answer
> 0 votes
# R, 38 bytes

```
cat(gsub(":","\n",Sys.getenv('PATH')))

```

Grab the $PATH, replace `:` with newlines and prints to stdout. You can try it online here.

# Answer
> 0 votes
# Groovy, 43 Bytes

```
System.env['PATH'].replaceAll(":","\n")

```

# Answer
> 0 votes
# Gema, 36 characters

```
\A=@subst{\\:=\\n;@getenv{PATH}}@end

```

Sample run:

```
bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

bash-4.3$ gema '\A=@subst{\\:=\\n;@getenv{PATH}}@end'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin

```

# Answer
> 0 votes
# Befunge-98 + EVAR fingerprint, 34 bytes

```
"RAVE"4("HTAP"Gv
:!k@:':-!'0*-, >

```

Loads the EVAR fingerprint (`"RAVE"4(`) to easily access environment variables, gets the PATH envvar (`"HTAP"G`), and for each character, exits the program if the character is "\0" (`:!k@`), substracts ASCII 48 "0" if the char is ASCII 58 ":" (`:':-!'0*-`), and outputs the character (`,`).

# Answer
> 0 votes
# ELF/x86, 78 bytes

```
00000000  7f 45 4c 46 01 00 00 00  43 0f 00 00 43 5f eb 10  |.ELF....C...C_..|
00000010  02 00 03 00 0c 50 eb 10  0c 50 eb 10 04 00 00 00  |.....P...P......|
00000020  5f 5f b1 05 be 49 50 eb  10 3d 20 00 01 00 5f f3  |__...IP..= ..._.|
00000030  a6 75 ef 89 f9 80 3f 3a  75 03 80 2f 30 42 ae 75  |.u....?:u../0B.u|
00000040  f4 4a 04 04 cd 80 93 cd  80 50 41 54 48 3d        |.J.......PATH=|
0000004e

```

NASM source:

```
BITS 32                                         ;
ORG 0x10eb5000                                  ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class   32b | -- | type: PT_LOAD      |
                                                ; |*data   none |    |                    |
                                                ; |*version   0 |    |                    |
                                                ; |*ABI    SysV |    |                    |
DD 0xf43        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  inc     ebx     ; STDOUT_FILENO         ; |*PADx7       | -- | vaddr = 0x10eb5f43 |
        pop     edi     ; discard argc          ; |             |    |                    |
        jmp     short skip                      ; |             |    |                    |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x10eb500c                                   ; |*version     | -- | filesz             |
DD 0x10eb500c                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
skip:   pop     edi     ; discard argv[0]       ; |*sh offset   | -- |*align              |
        pop     edi     ; discard argv[1]=NULL  ; |             |    |                    |
env:    mov     cl,5    ; \ strlen("PATH=")     ; |             |    |                    |
        mov     esi,PATH; > "PATH="             ; |*flags    /--|    |                    |
DB 0x3d         ; cmp eax,0x10020               ; |*ehsize      |    +--------------------+
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
                                                ; |             |
        pop     edi     ; > envp                ; |*shentsize   |
        repe    cmpsb   ; > strcmp(envp,"PATH="); |*shnum       |
        jne     env     ; /                     ; |*shstrndx    |
        mov     ecx,edi                         ; +-------------+

nlcolon:cmp     byte[edi],58  ; \ if (char == ':')
        jne     nosub         ; >
        sub     byte[edi],48  ; >   char -= '0'
nosub:  inc     edx           ; > wlen++
        scasb                 ; >
        jne     nlcolon       ; / while(char != 0)

        dec     edx           ; wlen--
        add     al,4
        int     0x80          ; write(1, ecx, wlen)
        xchg    eax,ebx
        int     0x80          ; exit(...)

PATH: db "PATH="

```

# Answer
> 0 votes
# DOS .COM File, 52 bytes

```
00000000  31 f6 8b 16 2c 00 8e da  bf 2f 01 b9 05 00 f3 a6  |1...,..../......|
00000010  74 06 f7 d9 f2 ae eb f0  b4 02 ac 3c 3b 75 06 b2  |t..........<;u..|
00000020  0d cd 21 b0 0a 92 08 c0  74 04 cd 21 eb ea c3 50  |..!.....t..!...P|
00000030  41 54 48 3d                                       |ATH=|
00000034

```

NASM Source:

```
BITS 16
ORG 0x100

                                ; we assume ax is zeroed on start
        xor     si,si
        mov     dx, [0x2c]
        mov     ds, dx          ; PSP:002C points to the environment segment

searchpath:
        mov     di, PATH
        mov     cx, 5
        repe    cmpsb           ; search for PATH= in environment
        je      loop            ; jump if found
        neg     cx
        repne   scasb           ; scan for '\0': skip to the next env var
        jmp     searchpath

loop:   mov     ah, 2           ; WRITE TO STDOUT; AH=02 DL=char
        lodsb                   ; load the next character from PATH
        cmp     al,59
        jne     nosemi
        mov     dl, 0x0d        ; \ if it is a semicolon,
        int     0x21            ; > output '\r',
        mov     al,0x0a         ; / and change it to '\n'
nosemi: xchg    dx,ax           ; 1 byte shorter than mov dl,al
        or      al,al
        je      end             ; if it is '\0', end
        int     0x21
        jmp     loop

end:    ret

PATH: db "PATH="

```

On some older DOS versions (e.g: 3.3) SI is apparently zeroed at start, so 2 bytes can be saved. Newer DOS versions apparently set SI to 100h.

# Answer
> 0 votes
# Q 20 Characters

If no double quotes in the output the length is 17 chars

```
q)-1":"vs getenv`PATH;
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
q)

```

# Answer
> 0 votes
# Tcl, 34 bytes

```
puts [regsub -all : $env(PATH) \n]

```

Try it online!

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


title: Reverse user input

text:
# Question
Title: Reverse user input
This is a pretty simple one. if the user enters "Hello World" your code should output "dlroW olleH"

I was inspired by the multiplication question recently posted. I know this is probably easy in bash.

As this is code-golf, least bytes wins.

# Answer
> 0 votes
# Mathematica, 13 bytes

```
StringReverse

```

Try it online!

---
Tags: hello-world
---


title: Do the figures fit?

text:
# Question
Title: Do the figures fit?
## Challenge

Make the shortest program to determine if the figures in the input will fit into the space in the input.

## Requirements

The input will be in the format of this example: Input:

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

```

Output:

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

```

First, starting in the upper left corner, is the space that the program will try to fit the figures into. Then there is a space. Then there is a figure, in this case two dashes. Then there is a space, then a second figure. The output is the figures fitted inside of the space.

## Rules about figures and input:

* The upper left corner of a shape will always be on the first row.
* After a figure, there is one space, as shown in the example.
* There is no limit on the size of the figures.
* The first figure will always be the space that the program will determine if the figures fit into.
* There is no limit on the number of figures, but there will only be one space to fit them into.
* All figures will be made of `|` and `-` for the sides and `+` for the corners. These are the only characters used besides spaces and newlines.
* Figures cannot be rotated.
* Borders cannot overlap.
* You may fit one figure inside of another.
* The figures do not have to be closed.
* The space will always be closed.
* The space does not have to be completely filled.
* You may not split up shapes.

## Rules about output:

* If the figures fit into the space, the program should output the figures inside of the space, as shown above. It does not matter how they are arranged, as long as no borders overlap, all figures are correct, and no shapes are split up.
* If the figures do not fit, output "no".

## Examples

Input:

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

```

Output:

```
no

```

Input:

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

```

Output:

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

```

This is also valid:

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

```

Input:

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

```

Output:

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

```

This is a code golf, so the shortest answer wins.

# Answer
> 5 votes
# Python 2, ~~529~~ ~~692~~ ~~683~~ 681 bytes

```
L=len
R=range
def g(s):S=s.split('\n');S=[l.ljust(L(S[0]))for l in S];Z=zip(*S);I=[-1]+[i for i in R(L(Z))if{' '}==set(Z[i])]+[None];return[[list(x)for x in zip(*Z[I[i]+1:I[i+1]])if set(x)!={' '}]for i in R(L(I)-1)]
def f(s):
 S=g(s);G(S[0],1,1)
 for l in F(*S)or['no']:print''.join(l).replace('~',' ')
def G(a,i,j):
 if len(a)>i>-1<j<len(a[0])and'!'>a[i][j]:
	for x,y in(0,1),(0,-1),(1,0),(-1,0):G(a,i+x,j+y);a[i][j]='~'
def F(a,*s):
 if not s:return a
 c=s[0];h,w=L(c),L(c[0])
 for i in R(1,L(a)-h):
	for j in R(1,L(a[0])-w):
	 T=1;A=[l[:]for l in a]
	 for y in R(h):
		for x in R(w):
		 C=c[y][x]
		 if' '<C:T&=A[y+i][x+j]>'}';A[y+i][x+j]=C
	 r=T and F(A,*s[1:])
	 if r:return r

```

Try it online!

Gained a lot of bytes by adding a flood fill to the first shape.

This is to fix fix cases where a figure can be outside the shape, but inside its bounding box.

eg. The shape fits inside the bounding box, but outside the shape:

```
Input:        Wrong:      Correct:
+-+    --     +-+         +-+
| |           | |--       | |
| +--+        | +--+      | +--+
|    |        |    |      |--  |
+----+        +----+      +----+

```

---

**Explanation**

`f` takes input as a single string with newlines.

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

```

The shapes are split up with `g(s)` and mapped to lists of lists

```
[[['+', '-', '-', '-', '-', '+', ' ', ' ', ' ', ' ', ' '], ['|', ' ', ' ', ' ', ' ', '+', '-', '-', '-', '-', '+'], ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|'], ['|', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '|'], ['+', '-', '-', '-', '-', '-', '-', '-', '-', '-', '+']],
[['-', '-']],
[['+', '-', '-', '+'], ['|', ' ', ' ', '|'], ['+', '-', '-', '+']]]

```

The first shape is flood filled with `~` (`G(S[0])`), so we know the allowed area:

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

```

For each other shape we recursively fit them into the first `F(a,*s)`, returning when all of them fit, or at the end, if no configuration does.

```
+----+        +----+        +----+        +----+        +----+
|--~~+----+   |~--~+----+   |~~--+----+   |~~~~+----+   |~~~~+----+
|~~~~~~~~~|   |~~~~~~~~~|   |~~~~~~~~~|   |--~~~~~~~|   |~--~~~~~~|
|~~~~~~~~~|   |~~~~~~~~~|   |~~~~~~~~~|   |~~~~~~~~~|   |~~~~~~~~~|
+---------+   +---------+   +---------+   +---------+   +---------+
     |             |             |             |             |
     V             V             V             V             V
  No room        No room      No room       No room     +----+
  for next       for next     for next      for next    |+--++----+
  shape          shape        shape         shape       ||--|~~~~~|
                                                        |+--+~~~~~|
                                                        +---------+

                                                           Done!

```

Lastly we print the combined shapes, without `~`.

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

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 811 bytes

```
(M=MorphologicalComponents;L=Length;A=Thread;T=Last;B=Table;P=Position;W=Prepend;g=AnyTrue[#,#!=" "&]&;h[n_]:=If[DuplicateFreeQ[Join@@B[(#-{1,1}+W[n,{1,1}][[i]]&)/@P[t[[i]],1],{i,L[y]}]],n,Nothing];R[z_]:=PadRight[#,Max[L/@z]," "]&/@z;s=Characters/@StringSplit[#,"\n"];s=R@s;r=Map[#/.{Longest[" "...],n___," "...}->{n}&,DeleteCases[A/@Split[A@s,g],_?(!g@#&),2],2];r[[1]]=R@#&@@r;t=r/.{"|"|"+"|"-"->1," "->0};y=M[#,Method->"ConvexHull"]&/@t;o=y-M/@t;u=T[h/@T@T@Reap[Outer@@Append[W[B[{NoneTrue[Flatten@B[#[[q+1,w+1]]==1&&o[[1]][[i+q,j+w]]==0,{w,0,L@#&@@#-1},{q,0,L@#-1}],TrueQ],i,j},{i,1,1+L@#&@@y-L@#},{j,1,1+L@y[[1,1]]-L@#&@@#}]&/@y[[2;;]],If[And@@(First/@{##}),Sow[#[[2;;]]&/@{##}]]&],2]]];If[u=={},"no",Grid@ReplacePart[r[[1]],Join@@B[(#-{1,1}+u[[i-1]])->Part[r[[i]],Sequence@@#]&/@P[t[[i]],1],{i,2,L@y}]]])&

```

It needs a frontend to display grid (which is not supported on tio.run).

The code does the following things:

1. Get inside points of 1st shape
2. Iterate over all starting point combinations
3. Pick a combination where all other (2, 3, ...) shapes' points lie in waht we get in Step 1, and without any overlapped points
4. Output (by `ReplacePart`)

If the input format can be more flexible, the code can be shortened to ~680 bytes. Besides that, there is still a lot of golfing space, though.

Try it online!

Expanded:

```
(M = MorphologicalComponents; L = Length; A = Thread; T = Last;
  B = Table; P = Position; W = Prepend; g = AnyTrue[#, # != " " &] &;
  h[n_] := If[
    DuplicateFreeQ[
     Join @@ B[(# - {1, 1} + W[n, {1, 1}][[i]] &) /@ P[t[[i]], 1], {i,
         L[y]}]], n, Nothing];
  R[z_] := PadRight[#, Max[L /@ z], " "] & /@ z;
  s = Characters /@ StringSplit[#, "\n"]; s = R@s;
  r = Map[# /. {Longest[" " ...], n___, " " ...} -> {n} &,
    DeleteCases[A /@ Split[A@s, g], _?(! g@# &), 2], 2];
  r[[1]] = R@# & @@ r; t = r /. {"|" | "+" | "-" -> 1, " " -> 0};
  y = M[#, Method -> "ConvexHull"] & /@ t; o = y - M /@ t;
  u = T[h /@
     T@T@Reap[
        Outer @@
         Append[W[
           B[{NoneTrue[
                Flatten@
                 B[#[[q + 1, w + 1]] == 1 &&
                   o[[1]][[i + q, j + w]] == 0, {w, 0,
                   L@# & @@ # - 1}, {q, 0, L@# - 1}], TrueQ], i,
               j}, {i, 1, 1 + L@# & @@ y - L@#}, {j, 1,
               1 + L@y[[1, 1]] - L@# & @@ #}] & /@ y[[2 ;;]],
           If[And @@ (First /@ {##}), Sow[#[[2 ;;]] & /@ {##}]] &],
          2]]]; If[u == {}, "no",
   Grid@ReplacePart[r[[1]],
     Join @@ B[(# - {1, 1} + u[[i - 1]]) ->
          Part[r[[i]], Sequence @@ #] & /@ P[t[[i]], 1], {i, 2,
        L@y}]]]) &

```

---
Tags: code-golf, grid, packing
---


title: How many Latin Squares?

text:
# Question
Title: How many Latin Squares?
A Latin Square is a square of size **n × n** containing numbers **1** to **n** inclusive. Each number occurs once in each row and column.

An example of a 3 × 3 Latin Square is:

```
[[1, 2, 3],
 [3, 1, 2],
 [2, 3, 1]]

```

Another is:

```
[[3, 1, 2],
 [2, 3, 1],
 [1, 2, 3]]

```

Given an integer input **n** where **n \> 0**, determine how many Latin Squares there are with a size **n × n**, where the possible values are anything from **1** to **n** inclusive.

## Examples:

```
1 -> 1
2 -> 2
3 -> 12
4 -> 576
5 -> 161280
6 -> 812851200
7 -> 61479419904000
11 -> 776966836171770144107444346734230682311065600000

```

This is OEIS sequence A002860. It has a Wikipedia article here.

Answers are only required to support inputs up to 6, due to anything above that being greater than 232. However, while this is not strictly enforceable, your *algorithm* must work for all inputs.

# Answer
# Wolfram Language (Mathematica), ~~67~~ ~~56~~ ~~50~~ 48 bytes

```
D[Permanent@a^n,##]&@@Join@@(a=x~Array~{n=#,#})&

```

Try it online!

Uses Theorem 5.1 in this article: if X is an *n* by *n* matrix whose entries are distinct variables, then the number of *n* by *n* Latin squares is equal to the coefficient of the product of all these variables in per(X)*n*, where per(X) is the permanent of X. Here, we obtain that coefficient by differentiating with respect to all of the variables, once each (which leaves a constant).

Regarding running time: TIO was happy to deal with inputs 1 through 6, and my laptop can handle 7 in a bit over 6 minutes. I didn't try 8.

Choice quotations included in the article about this formula's practicality:

> The use of MacMahon's result by mere mortals seems doomed. – Riordan
>
> One should not wish to actually perform, even in a computer algebra package like Maple, MacMahon's counting method. – Van Leijenhorst

# Another Mathematica solution, 52 bytes

```
LineGraph@CompleteGraph@{#,#}~ChromaticPolynomial~#&

```

Much less efficient (only inputs 1 through 4 are viable) but somewhat more readable.

Uses the fact that Latin squares of size *n* are precisely the *n*-colorings of the *n* by *n* rook's graph, which is the line graph of the complete bipartite graph K*n*,*n*, and is an excellent example of Mathematica's occasional tendency to look like a natural-language explanation of the algorithm with prepositions replaced by random symbols.

In practice, `GraphData@{"Rook",{#,#}}~ChromaticPolynomial~#&` is only 47 bytes and works for all feasible inputs, but it fails to satisfy the criterion of being a general algorithm (since `GraphData` hardcodes small rook graphs, but does not generate arbitrarily large ones).
> 6 votes

# Answer
# Jelly, 8 bytes

```
Œ!ṗµfZ€L

```

Brute force solution. Inputs **5** and higher will time out on TIO.

Try it online!

### How it works

```
Œ!ṗµfZ€L  Main link. Argument: n

Œ!        Generate all permutations of R := [1, ..., n].
  ṗ       Take the n-th Cartesian power, yielding the array A of all n×n matrices
          whose rows are permutations of R.
   µ      New chain. Argument: A
     Z€   Zip each; transpose each matrix in A, yielding the array B of all n×n
          matrices whose columns are permutations of R.
    f     Filter; keep only matrices that appear in A and B.
       L  Compute the length, counting the kept matrices.

```
> 5 votes

# Answer
# Pyth, 11 bytes

```
l@K^.pQQCMK

```

**Try it here!**

## How it works

```
l@K^.pQQCMK   - Full program.

    .pQ       - All permutations of the range [0, input).
   ^   Q      - To the Cartesian power of the input.
  K           - Assign to a variable K.
 @            - The intersection of K.
        CMK   - With the list of all elements in K transposed.
l             - Length.

```

As this is brute force, anything higher than **4** will Memory Error on Herokuapp or time out on TiO.
> 2 votes

# Answer
# Python 2, 91 bytes

```
f=lambda n,k=0,s={''},x=0:k<n*n>x and f(n,k+1,s|{x+k/n,~x-k%n})+f(n,k,s,x+n)or len(s)>n*n*2

```

Try it online!

---

**Python 2, 102 bytes**

```
lambda n:sum(all(len({(k/r%n,i/n**k%n)for k in range(n*n)})/n/n for r in(1,n))for i in range(n**n**2))

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~138~~ ~~134~~ 124 bytes

```
from itertools import*
def f(n):r=range(n);print sum(map(set,zip(*m))==n*[set(r)]for m in product(permutations(r),repeat=n))

```

Try it online!

Brute forces, very slow. Works for `n=1..4` on tio
> 1 votes

# Answer
# Mathematica, 102 bytes

```
Length@Select[Subsets[Permutations@Range@#,{s=#}],Union[Sort/@Table[#[[i]]&/@#,{i,s}]]=={Range@s}&]s!&

```

Try it online!
> 1 votes

# Answer
# Ruby, 90 bytes

Brute force!

```
->n{x=[*1..n]
y=*x.permutation
y.product(*[y]*~-n).count{|a|a.transpose.all?{|b|x-b==[]}}}

```

Try it online!
> 0 votes

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