title: Count the reviews!

text:
# Question
Title: Count the reviews!
## Introduction and Credit

Imagine you're Amazon. Imagine you have a large number of products for which a lot of people have written reviews scoring 1-5 stars. Now you need to give your customers a summary for each product based on the simple product-scoring association. Because you're Amazon, time is money and as such you need to fit this into the smallest code possible because that's the code you can write the fastest.
Credit: This task appeared in 2014 in a programming mid-term exam in the functional programming course at my university and since then an example solution has been provided. I have the lecturer's and author's (same person) permission to post this question publicly.

---

## Input

Your input will be a list of pairs of natural numbers, where the second value of each pair is always either 1, 2, 3, 4 or 5. Take the input using your preferred, generally accepted way.

## Output

Your output will be a list of pairs of a number and a list of 5 numbers. Give the output using your preferred, generally accepted way.

## What to do?

Given the (unsorted) list of product-id and scoring pairs, count for each product how often each score appears and return the amounts in the second list of the output pair at the appropriate position.
So for product #5 with 10x 1-star, 15x 2-star, 25x 3-star, 50x 4-star and 150x 5-star would result in the entry `[5 [10 15 25 50 150]]`.

## Potential Corner Cases

The input list may be empty in which case your output should be as well.
You don't need to consider the case where the input violates the above constraints.
You can safely assume all numbers to be representable by a signed 32-bit integer.
If you have no review(s) for a product (ie it doesn't appear in the output) it must not appear in the output either, i.e. 5x zeroes doesn't happen and can always be dropped.

## Who wins?

This is so the shortest answer in bytes wins. Built-ins are allowed and standard rules apply.

---

## Examples

Example input:

```
[(1,4),(2,5),(1,5),(1,1),(1,5),(1,4)]

```

Example corresponding output:

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

```

Other test vectors:

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

```

# Answer
> 3 votes
# MATL, 8 bytes

```
5B#uilZ?

```

Input format is a column array of products followed by a column array of scores:

```
[1; 2; 1; 1; 1; 1]
[4; 5; 5; 1; 5; 4]

```

Output format is a vertical array of products followed by a matrix of score occurrences:

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

```

Try it online!

### Explanation

```
5B#u   % Implicitly input array of products. Push unique values and integer labels
       % of the input entries. So input [1; 3; 1; 1; 1] would give outputs [1; 3]
       % and [1; 2; 1; 1; 1]. The latter is lik the input but without "holes", i.e.
       % uses consecutive integers. This is required to avoid rows of zeros in the
       % result for non-existing intermediate products
i      % Input array of scores
l      % Push 1
Z?     % Build sparse matrix with those row indices, column indices, and value 1.
       % Implicitly display

```

# Answer
> 3 votes
## R, 64 bytes

```
function(m)`if`(length(m)>1,by(m[,2],m[,1],tabulate,n=5),list())

```

This solution works if the I/O is somewhat flexible. It's an unnamed function that works by taking an R-matrix as input and tabulates the frequency of each type of review. The only problem is dealing with the empty list. We need to introduce a control whether this is actually the case and because an empty matrix `matrix()` is not actually empty, we return an empty `list()` instead.

Try it on R-fiddle

**Example output for the last test case:**

```
m[, 1]: 1
[1] 1 0 0 0 0
---------------------------------------------------------------------------------------------
m[, 1]: 2
[1] 0 1 0 0 0
---------------------------------------------------------------------------------------------
m[, 1]: 3
[1] 0 0 1 0 0
---------------------------------------------------------------------------------------------
m[, 1]: 4
[1] 0 0 0 1 0
---------------------------------------------------------------------------------------------
m[, 1]: 5
[1] 0 0 0 0 1

```

# Answer
> 2 votes
# Python 2 - ~~88~~ ~~72~~ ~~71~~ ~~69~~ 67 bytes

```
def s(l,d={}):
 for p,s in l:d.setdefault(p,[0]*5)[s-1]+=1
 print d

```

```
Input to the function:
[(1,4),(2,5),(1,5),(1,1),(1,5),(1,4)]

Output:
{1: [1, 0, 0, 2, 2], 2: [0, 0, 0, 0, 1]}

```

**Edits:**

* Thanks to nedla2004 for saving 16 bytes!
* Changed to Python 2 to save 1 byte :D
* Saved 3 bytes by taking newline byte count as 1 byte.
* Thanks flp-tkc for saving 2 bytes. (There was an unnecessary extra space too :D)

Golfing suggestions are welcome :)

# Answer
> 1 votes
# Mathematica, 68 bytes

```
{#[[1,1]],Last/@Tally@Join[Range@5,#2&@@@#]-1}&/@GatherBy[#,#&@@#&]&

```

Unnamed function taking as input a list of ordered pairs of integers such as `{{1, 4}, {2, 5}, {1, 5}, {1, 1}, {1, 5}, {1, 4}}`. To start, `GatherBy[#,#&@@#&]` groups together all the pairs with the same first element (which can be any identifier, actually, not just an integer).

Each of those groups is then operated on by the function `{#[[1,1]],Last/@Tally@Join[Range@5,#2&@@@#]-1}`, which produces a two-element list as output, the first element of which is just the common identifier. `Join[Range@5,#2&@@@#]` generates a list of integers starting with `1,2,3,4,5` and ending with all of the scores corresponding to the given identifier. `Last/@Tally` then computes how many time each score was found, returning the appropriate 5-tuple; then `-1` makes up for the fact that we introduced each score one extra time, leaving zeros for any missing score (which otherwise would be skipped completely).

# Answer
> 1 votes
# Jelly, ~~18~~ 17 bytes

```
Fm2QṢµ5,@þċ@€€³ż@

```

**TryItOnline!**

### How?

```
Fm2QṢµ5,@þċ@€€³ż@ - Main link: List of (id, score) pairs
F                 - flatten
 m2               - mod 2 of list (gets the IDs)
   Q              - unique items by first appearance (one of each ID)
    Ṣ             - sorted (IDs in order)
     µ            - monadic chain separation (call the above z)
         þ        - table the result of
       ,@         -    pair z (with reversed @rguments) with
      5           -    5 (implicit range, so [1,2,3,4,5]) ...we now have:
                  -        [[id,1],[id,2],[id,3],[id,4],[id,5]] for every id, in order.
          ċ@€€    - count occurrences of (with reversed @rguments) for €ach for €ach in
              ³   - the first input (the list of (id, score) pairs)
               ż@ - zip (with reversed @rguments) with z

```

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

Returns an object whose keys are the product IDs, associated to a list of review scores.

```
a=>a.map(([i,n])=>(o[i]=o[i]||[0,0,0,0,0])[n-1]++,o={})&&o

```

### Test cases

```
let f =

a=>a.map(([i,n])=>(o[i]=o[i]||[0,0,0,0,0])[n-1]++,o={})&&o

console.log(JSON.stringify(f([])));
console.log(JSON.stringify(f([[1,4],[2,5],[1,5],[1,1],[1,5],[1,4]])));
console.log(JSON.stringify(f([[1,1],[2,2],[3,3],[4,4],[5,5]])));
```

# Answer
> 1 votes
# Lua, 114 112 103 bytes

```
function(t,o)for i=1,#t do v=t[i]n,r=v[1],v[2]o[n]=o[n]or{n,{0,0,0,0,0}}o[n][2][r]=o[n][2][r]+1 end end

```

Try it online!

### Explanation

```
function(t,o) -- Anonymous function taking a table and the output table
    for i=1,#t do -- For every number from 1 to the length of t
        v = t[i] -- Get the current entree
        n, r = v[1], v[2] -- Item Number and Rating
        o[n] = o[n] or {n,{0,0,0,0,0}} -- Make sure the item exists in the output
        o[n][2][r] = o[n][2][r] + 1 -- Add 1 to that rating
    end
-- Tables are always passed by reference, so no need to return
end

```

# Answer
> 0 votes
**Clojure, 79 bytes**

```
(fn[c](reduce(fn[r[i v]](update r i #(update(or %[0 0 0 0 0])(dec v)inc))){}c))

```

Must called with a sequence of vectors so that item id and ratinv value are correctly mapped to function arguments. Returns a hash-map of vectors.

```
(def f (fn[c]( ... )))
(f [[1 4] [2 5] [1 5] [1 1] [1 5] [1 4]])
{1 [1 0 0 2 2], 2 [0 0 0 0 1]}

```

# Answer
> 0 votes
# Husk, 18 bytes

```
m§,o←←oλm#⁰ḣ5)m→k←

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), ~~37~~ 35 bytes

```
Merge[Rule@@@#,#~BinCounts~{1,6}&]&

```

Try it online!

---
Tags: code-golf, array
---


title: Build a Primitive Root Diffuser

text:
# Question
Title: Build a Primitive Root Diffuser
### Introduction

When a room has bare, parallel walls, it can create unpleasant repeating acoustic reflections (echoes). A diffuser is a device mounted on a wall which creates a blocky surface of many different heights. This has the effect of breaking up the reflected sound into many smaller reflections (each with a different time delay). The acoustic quality of the room is thought to be greatly enhanced.

### Primitive Root Diffuser

The primitive root diffuser uses a grid of (typically wooden) posts, each with a different height (to obtain a different reflection delay time). The heights of the posts are chosen according to successive powers of a primitive root G, modulo N (a prime number).

Here are some pictures of a primitive root diffuser.

### Task

You must write a program or function which takes a prime number N \> 2 as its only input. It must then select a primitive root of N. G is a primitive root of N if the successive powers of G modulo N generate all the integers from 1 to N-1. A more formal definition of primitive roots can be found in the Wikipedia article.

Your code must then place these successive powers into an X-by-Y array (or matrix). Because we want to hang this on the wall, the diffuser should be a convenient shape - as close to square as possible. The number of entries in the array will be N-1, so its dimensions X and Y should be chosen such that X\*Y = N-1, and X is near but not equal to Y (specifically, X and Y are coprime). For convenience of display, the horizontal dimension should be greater than the vertical dimension.

The order of placement of successive powers of G (modulo N) should start at one corner of the array, then traverse diagonally through the array, wrapping around in both directions until all array positions are filled. Then the function should return that array, or print it to stdout, whichever you prefer.

We won't concern ourselves with the measurement units used to actually cut the posts to length; we'll assume the units are appropriate for the range of audio frequencies we want to diffuse, and stick to integers.

There's an online calculator, in case you want to check your work. However, the site appears to be down currently.

### Example

Suppose we choose N = 41. Our program should select one of the primitive roots of N, which are \[6, 7, 11, 12, 13, 15, 17, 19, 22, 24, 26, 28, 29, 30, 34, 35\]. Suppose our program selects the smallest primitive root, G = 6.

Our program then chooses the squarest dimensions X,Y for the array such that X\*Y = N-1. The clear choice is X=8 and Y=5.

Then our program populates the array with successive powers of G modulo N (starting with G^0), traversing diagonally. The program then returns/prints the array:

```
1   14  32  38  40  27  9   3
18  6   2   28  23  35  39  13
37  26  36  12  4   15  5   29
10  17  33  11  31  24  8   30
16  19  20  34  25  22  21  7

```

Note how it begins with 6^0 mod 41 = 1, then 6^1 mod 41 = 6, then 6^2 mod 41 = 36, then 6^3 mod 41 = 11, etc.

To clarify, the sequence of powers of 6 modulo 41 is:

```
[1, 6, 36, 11, 25, 27, 39, 29, 10, 19, 32, 28, 4, 24, 21, 3, 18, 26, 33, 34, 40, 35, 5, 30, 16, 14, 2, 12, 31, 22, 9, 13, 37, 17, 20, 38, 23, 15, 8, 7]

```

### Another Example

N = 31

Assuming the program selects G = 11, X = 6, Y = 5, the output is:

```
1   26  25  30  5   6
4   11  7   27  20  24
16  13  28  15  18  3
2   21  19  29  10  12
8   22  14  23  9   17

```

### A Third Example

N = 37

Assuming the program selects G = 2, X = 9, Y = 4, the output is:

```
1   12  33  26  16  7   10  9   34
31  2   24  29  15  32  14  20  18
36  25  4   11  21  30  27  28  3
6   35  13  8   22  5   23  17  19

```

### Scoring

Standard code golf rules - the fewest bytes of code producing correct output wins!

# Answer
> 3 votes
# Mathematica 158

Spaces not needed:

```
f@n_ := (m = Mod;
        {p, q} = Sort[{y-x, x, y} /. Solve[x*y==n - 1 && x~GCD~y == 1 < x < y, Integers]][[1, 2 ;;]];
        (g[#~m~p + 1, #~m~q + 1] = m[PrimitiveRoot@n^#, n]) & /@ (Range@n - 1);
         g~ Array~{p, q})

```

The last one looks like this ...

# Answer
> 3 votes
# Haskell, ~~220~~ ~~213~~ ~~207~~ ~~201~~ ~~194~~ ~~182~~ 178

```
f n=[map(x%)[0..j-1]|x<-[0..i-1]]where j=[x|x<-l,x^2>n,(n-1)&x<1,gcd(n`div`x)x<2]!!0;i=n`div`j;0%0=1;a%b=([x|x<-l,all((>1).(&n).(x^))l]!!0*(a-1)&i%((b-1)&j))&n;l=[1..n-2]
(&)=mod

```

this is a function which returns a matrix (a list of lists of `Int`).

it works by calculating the smallest possible `g`, the closet coprime `j` and `k` and defines a recursive function that given the indices of a slot in the grid returns the Integer in it, and maps this function over all slots.

**example output:**

```
*Main> mapM_ print $ f 13 -- used for printing the matrix line-by-lie
[1,5,12,8]
[3,2,10,11]
[9,6,4,7]

*Main> mapM_ print $ f 43
[1,21,11,16,35,4,41]
[37,3,20,33,5,19,12]
[36,25,9,17,13,15,14]
[42,22,32,27,8,39,2]
[6,40,23,10,38,24,31]
[7,18,34,26,30,28,29]

*Main> mapM_ print $ f 37
[1,12,33,26,16,7,10,9,34]
[31,2,24,29,15,32,14,20,18]
[36,25,4,11,21,30,27,28,3]
[6,35,13,8,22,5,23,17,19]

```

# Answer
> 1 votes
# Python 2: 232 217 212 208 201 198 194 192 187 bytes

```
N=input()
w=n=G=N-1
Z=range(n)
while sorted(G**x%N-1for x in Z)!=Z:G-=1
while w*w/n|n%w|1-all(w%i|n/w%i for i in Z[2:]):w-=1
n/=w
a=[]
for x in Z:a+=[n*[0]];a[x%w][x%n]=G**x%N
print a[:w]

```

Now it selects the largest root instead of the smallest, so output is different. Example:

```
41
[[1, 27L, 32L, 3L, 40L, 14, 9L, 38L], [18L, 35, 2L, 13L, 23L, 6L, 39, 28L], [37L, 15L, 36, 29L, 4L, 26L, 5L, 12L], [10L, 24L, 33L, 30, 31L, 17L, 8L, 11L], [16L, 22L, 20L, 7L, 25, 19L, 21L, 34L]]

```

# Answer
> 1 votes
# MATLAB w/ Symbolic Toolbox - ~~199~~ 198 bytes

Minified:

```
function C=F(N),M=N-1;y=1:N;p=y-1;t=@(x)eval(mod(sym(x).^p,N));l=M./y;L=fix(l);k=y(l==L.*gcd(y,L)&y>M^.5);k=k(1);l=M/k;C=eye(l,k);g=y(arrayfun(@(x)sum(t(x)<2)<3,y));C(mod(p,k)*l+mod(p,l)+1)=t(g(1));

```

Expanded:

```
function C = primroot( N )

M = N-1;
y = 1:N;
p = y-1;
t = @(x) eval( mod( sym(x).^p, N ) );
l = M./y;
L = fix( l );
k = y( l == L.*gcd(y,L) & y > M^.5 );
k = k(1);
l = M/k;
C = eye( l, k );
g = y(arrayfun( @(x) sum( t(x) < 2 ) < 3, y ));
C(mod(p,k)*l+mod(p,l)+1) = t(g(1));

```

### Sample Outputs

```
primroot(37)

ans =

 1    12    33    26    16     7    10     9    34
31     2    24    29    15    32    14    20    18
36    25     4    11    21    30    27    28     3
 6    35    13     8    22     5    23    17    19

primroot(41)

ans =

 1    14    32    38    40    27     9     3
18     6     2    28    23    35    39    13
37    26    36    12     4    15     5    29
10    17    33    11    31    24     8    30
16    19    20    34    25    22    21     7

primroot(31)

ans =

 1     6     5    30    25    26
16     3    18    15    28    13
 8    17     9    23    14    22
 4    24    20    27     7    11
 2    12    10    29    19    21

primroot(113)

ans =

  1    48    44    78    15    42    95    40   112    65    69    35    98    71    18    73
106     3    31    19     8    45    13    59     7   110    82    94   105    68   100    54
 49    92     9    93    57    24    22    39    64    21   104    20    56    89    91    74
109    34    50    27    53    58    72    66     4    79    63    86    60    55    41    47
 28   101   102    37    81    46    61   103    85    12    11    76    32    67    52    10
 30    84    77    80   111    17    25    70    83    29    36    33     2    96    88    43
 16    90    26     5    14   107    51    75    97    23    87   108    99     6    62    38

```

A noble effort for MATLAB (even if I do say so myself), the language that requires `a1 = b(c); a = a1(d);` because it doesn't understand `a = b(c)(d)`. :P

A few notes:

* the routine exploits the fact that `mod( j^k, N )` for `k = 0..N-1` is strictly positive for positive `j`, and that `j` is only a primitive root of `N` if the number `1` appears exactly twice in the sequence
* the routine exploits the fact that a number `x >= 2` can only equal `floor(x)*gcd(floor(x),y)` for positive `y` if `floor(x) == x` and `gcd(floor(x),y) == 1`. Also, the fact that `x` and `y` are coprime iff `gcd(x,y) == 1`.

Other than that, I couldn't find any problem-specific optimizations.

MATLAB's `mod` function is particularly painful since I use it 3 times, and it takes a minimum of 8 characters per invocation, as opposed to 3 (i.e. `x%y`) for virtually every other programming language in existence. The `arrayfun` (which in every other language is either `map` or `->` is also painful.

In light of these handicaps, I also present the following solution:

### Fantasy MATLAB - far fewer bytes

```
C = @(N):
M = N-1;
y = 1:N;
p = y-1;
t = @(x) eval( sym(x).^p % N );
L = fix( l = M./y );
k = y( l == L.*gcd(y,L) & y > M^.5 )(1);
C = ones( l = M/k, k );
C( p%k*l + p%l + 1 ) = t(y( x -> sum( t(x) < 2 ) < 3 )(1));

```

# Answer
> 0 votes
# APL (dzaima/APL), 84 bytes

```
{{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}⊃(⍵∘{1=≢⍵~⍨⍳⍺}¨⌿⊢)↓⍵|∘.*⍨⍳⍵-1}

```

Try it on repl.it!

Uses `⎕IO←0` (0-indexing).

A dfn which takes input as a long integer, and returns a matrix of long ints for the first primitive root of .

Hosted on repl.it since tio is not updated with the latest version of dzaima/APL. The run button runs all testcases.

## Explanation

`{{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}⊃(⍵∘{1=≢⍵~⍨⍳⍺}¨⌿⊢)↓⍵|∘.*⍨⍳⍵-1}`

`∘.*⍨⍳⍵-1` create a power table for 0..n-1

`⍵|` modulo that by the input

convert to list of lists

`(⍵∘{...}¨⌿⊢)` tacit function, filter lists where:

`1=≢⍵~⍨⍳⍺` numbers from 1 to n-1 are present

take the first one

`{⍵@(b∘|¨2⌿¨⍳≢⍵)⊢(b←{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵)⍴0}` and do the following:

**Dimension finding function(courtesy of ngn):**

`{a⊃⍨⊃⍋+/↑a←(≠/¨⌿⊢)⍸⍵=∘.×⍨⍳⍵}≢⍵` do the following with the length of the first list:

`∘.×⍨⍳⍵` multiplication table of 1..length

`⍸⍵=` coordinates at which product = length

`(≠/¨⌿⊢)` remove the ones which create squares

`a←` assign the final coordinates to `a`

`⊃⍋+/↑` index of coordinate with highest sum

`a⊃⍨` take that coordinate from `a`

`b←` assign that to b

`(...)⍴0` create a grid of zeroes of that size

`⍵@(...)⊢` assign the first list at the following indices:

`⍳≢⍵` 1..length

`2⌿¨` each replicated twice

`b∘|¨` mod b(vectorizes)

This gives the final diagonally oriented matrix.

---
Tags: code-golf, number-theory, primes
---


title: A graph and its seven closures

text:
# Question
Title: A graph and its seven closures
## Background

A little while ago, someone posted an interesting puzzle on Math.SE:

> What is the smallest digraph (directed graph) G where the following eight graphs are all distinct:
>
> * G, the original graph
> * Reflexive closure of G
> * Symmetric closure of G
> * Transitive closure of G
> * Reflexive symmetric closure of G
> * Symmetric transitive closure of G
> * Reflexive transitive closure of G
> * Reflexive symmetric transitive closure of G

A quick refresher on the terminology:

* A reflexive graph satisfies: for every vertex X of G, the edge (X,X) is present in G.
* A symmetric graph satisfies: for every pair of vertices X and Y of G, if the edge (X,Y) is present in G, the edge (Y,X) is also present.
* A transitive graph satisfies: for every triple of vertices X, Y, and Z of G, if the edges (X,Y) and (Y,Z) are present in G, the edge (X,Z) is also present.
* A reflexive/symmetric/transitive closure of G is the smallest superset of G that satisfies the given property. Note that, for example, *symmetric transitive closure* is not equal to *symmetric closure of transitive closure* in general.

For example, the following (from the original Math.SE post) shows an example graph that satisfies the original question:

## Challenge

Given a digraph G, determine if it satisfies the above puzzle (G and its seven closures are all distinct).

The input digraph G can be represented in any reasonable way: adjacency matrix, adjacency list, flat lists of vertices and edges, etc. Since the answer is always false when isolated vertices are not allowed, the representation must include some representation of the list of vertices.

For output, you can choose to

1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

The shortest code in bytes wins.

## Test cases

### Truthy

```
# the example in the image
vertices: [1, 2, 3, 4, 5, 6]
edges: [[1, 2], [2, 3], [3, 4], [4, 2], [4, 5]]
adjacency matrix:
[[0, 1, 0, 0, 0, 0],
 [0, 0, 1, 0, 0, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 1, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]]

# the smallest answer in Math.SE
vertices: [1, 2, 3, 4]
edges: [[1, 2], [2, 3]]
adjacency matrix:
[[0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0]]

```

### Falsy

```
# the incorrect answer in Math.SE
vertices: [1, 2, 3]
edges: [[1, 2], [2, 3]]
adjacency matrix:
[[0, 1, 0],
 [0, 0, 1],
 [0, 0, 0]]

# a modification of 4-vertex correct answer, ST=RST
vertices: [1, 2, 3, 4]
edges: [[1, 2], [2, 3], [4, 4]]
adjacency matrix:
[[0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 1]]

```

# Answer
# , 71 58 bytes

Takes in the adjacency matrix.

```
*/@~:@(,([+./@,#)"#/~^:_"2)@(,s@r,(s=:+.|:),:r=:[+.=@i.@#)

```

Try it online!

### How it works

First the original, `s`, `r` and `r->s` variants are computed, then all their transitive closures. Albeit the operations are not commutative, I believe calculating the transitive closure last will work here (`r->t` is equal to `r->t->r` as `r` just adds the diagonal, which was already set. `s->t` is equal to `s->t->s` as every transition was already symmetric. `s->r` is equal to `r->s` as every reflexion is symmetric.) Though this might be wrong, and if it is, I'm happy to slap some `^:_` on there. :-)

* `r=:+.=@i.@#`: original matrix OR the diagonal `=@i.@#`.
* `s=:+.|:`: original matrix OR its transposition `|:`.
* `,s@r,s,:r`: original matrix and all its variants in a list.
* `([+./@,#)"#/~^:_"2`: until the result does not change `^:_`: for every node: take the neighboring rows `#`, append them to the current row `[ ,` and OR them together `+./`.
* `*/@~:`: `~:` returns whether each element of the list is unique, then AND `*/` those booleans.
> 8 votes

# Answer
# Jelly, ~~31~~ ~~29~~ ~~27~~ ~~26~~ ~~25~~ 24 bytes

```
,|Z$æ*ⱮLS,Ʋ€Ẏæ*0|,Ʋ€Ẏ¬QƑ

```

Try it online! (comes with a test harness that runs all test inputs)

Takes the adjacency matrix and returns `1` or `0`.

I'm very rusty in code golf (especially in Jelly) and this solution tries to stay very safe regarding the specification, so there is very likely room for improvement. (Edit 7 bytes later: yes, there was. For example, just found out about `Ƒ` when re-reading the docs.)

### Explanation

1. The main link gets the adjacency matrix.
2. `Z` transposes the matrix and `|` bitwise-ORs it with the original. This gives the symmetric closure. `,` makes the pair `[orig, SC]`.
3. does the following for each of the two matrices:
    1. `L` finds the edge length N of the matrix. `æ*Ɱ` raises the matrix to each power 1…N to find routes of length 1 to N. `S` sums the resulting matrices together to find all routes. This gives the transitive closure, but the matrix can have values greater than one. `,` makes the pair `[TC, orig]`.
4. flattens the outermost array, giving `[TC, orig, STC, SC]`.
5. does the following for each of the four matrices:
    1. `æ*0` gets the zeroth matrix power, i.e. the identity matrix. `|` bitwise-ORs it with the previous matrix, giving the reflexive closure. `,` makes the pair `[RC, orig]`.
6. flattens the outermost array, giving `[RTC, TC, RC, orig, RSTC, STC, RSC, SC]`.
7. `¬` logical-NOTs all values in the matrices to turn 0 into 1 and anything else into 0. This makes all nonzero values equal.
8. `Q` removes duplicates from that list and `Ƒ` sees if it stayed the same.

### Correctness

The order of operations here is important. The transitive closure must be performed after the symmetric closure, but the reflexive closure can be performed at any point. I'll try to give a (very hand-wavy) proof of my algorithm's correctness.

For any path A1→…→An in SC(G), An→…→A1 will also exist, and thus TC(SC(G)) will be symmetric. SC(G) must be a subset of STC(G) (all "new edges" of SC(G) must also be in STC(G)) and TC(SC(G)) is the minimal transitive superset of SC(G). Thus TC(SC(G)) = STC(G).

RC(STC(G)) is always symmetric and transitive, since the edges added by RC will never break transitivity or symmetricity. STC(G) must be a subset of RSTC(G) (all "new edges" of STC(G) must also be in RSTC(G)) and RC(STC(G)) is the minimal reflexive superset of STC(G), so RC(STC(G)) = RSTC(G).1
> 5 votes

# Answer
# Charcoal, 66 bytes

```
⊞υθ⊞υＥθＥι∨λ§§θμκＦ⮌υ⊞υＥιＥκ∨μ⁼νλＦＥυＥιλ«ＦθＵＭιＥλ∨ν⊙λ∧π§§ιρξ⊞υι»⬤υ⁼¹№υι

```

Try it online! Link is to verbose version of code. Takes input as an adjacency matrix. Explanation: Port of @xash's answer.

```
⊞υθ

```

Push the input to the predefined empty list.

```
⊞υＥθＥι∨λ§§θμκ

```

Logical Or the input with its transpose and push it to the list.

```
Ｆ⮌υ⊞υＥιＥκ∨μ⁼νλ

```

For each matrix in the (reversed) list, logical Or it with the identity matrix and push the result to the list. (The list is reversed because otherwise the For command will attempt to iterate over the new results.)

```
ＦＥυＥιλ«

```

For each shallow cloned matrix in the list...

```
Ｆθ

```

... for as many times as the size of the matrix...

```
ＵＭιＥλ∨ν⊙λ∧π§§ιρξ

```

... logical Or the matrix with its square, and...

```
⊞υι

```

... push the final result to the list.

```
»⬤υ⁼¹№υι

```

Check that all of the matrices are unique.
> 4 votes

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


# Question
Title: Make Korean Character Multi-style Ascii/Box Art
## About Hangul

As I'm Korean, I'm really proud of Korean character, Hangul(한글).

Hangul is a syllabary invented by King Sejong the great, 4th king of Joseon dynasty, in 1443.

Because today (October 9th) is Hangul day in Korea, I'll give you a challenge: Make some Hangul

## List of characters

So, To make ASCII art, you have to know every characters represent each syllables, right?

No. There are 11172 syllables in Korean character, so it's almost impossible to hardcode it. But, there are only 24 basic characters:

```
ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎㅏㅑㅓㅕㅗㅛㅜㅠㅡㅣ

```

And in Korean you compose these to make all those syllables.

## How to compose

24 basic characters can be separated into two part: a consonant and a vowel.

The first 14 characters `ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ` are consonants, and followingthe 10 characters `ㅏㅑㅓㅕㅗㅛㅜㅠㅡㅣ` are vowels.

There are roughly 3 parts to a Korean character: initial consonant, vowel, and a final consonant.

### Initial consonant

The initial consonant (초성 in Korean) is simplest part. It is just consonant, only with `ㄲㄸㅃㅆㅉ`(double consonant). It placed in the top-left.

### Vowel

The vowel (중성 or 모음 in Korean) is the hardest part. Here is list of the vowels: `ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ`

`ㅏㅐㅏㅒㅓㅔㅕㅖㅣ` go on the right side of initial consonant; `ㅗㅛㅜㅠㅡ` go at the bottom; `ㅘㅙㅚㅝㅞㅟㅢ` are both. For example: `가, 고, 과`.

### Final consonant

The final consonant (종성 in Korean) is at the bottom. Here is list of final consonants: `ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ`, or blank.

Example characters using final consonant : `각, 갌, 갏`

## How to decompose Unicode

See this webpage for help.

## Challenge

Input is in this format: `(number) Korean char (number) Korean char ...` Where (number) is optional. If a number is given, switch to a different style as specified below. `1` and `2` are ASCII only, and `3` is Unicode box-art.

Separate characters with 2 spaces. Note that not every character has the same width.

If the vowel is not `ㅗㅛㅜㅠㅡ`, the following final consonant must be indented with a space.

The default style is `1`, so if first character doesn't have a number, style 1 is used.

An example input could be: `1한2글3날` or `한3글날`.

Here is list of Korean ascii art(style 1 and 2).

Here is list of Korean unicode box-art(style 3).

## List of ASCII art

### Style 1

```
ㄱ
___
   |
   |

ㄴ
|
|
|__

ㄷ
 ___
|
|___

ㄹ
___
 __|
|___

ㅁ
 __
|  |
|__|

ㅂ
|  |
|__|
|__|

ㅅ
 /\
|  |
|  |

ㅇ
 __
/  \
\__/

ㅈ
____
 /\
/  \

ㅊ
 __
____
/  \

ㅋ
___
___|
   |

ㅌ
 ___
|___
|___

ㅍ
____
 ||
_;;_

ㅎ
 __
____
 ()

ㄲ
_ _
 | |
 | |

ㄸ
 _ _
| |
|_|_

ㅃ
||||
[][]
""""

ㅆ
/|/|
||||
||||

ㅉ
____
/|/|
||||

ㅏ
    |
    |_
    |
    |

ㅐ
    | |
    |_|
    | |
    | |

ㅑ
    |
    |_
    |_
    |

ㅒ
    | |
    |_|
    |_|
    | |

ㅓ
     |
    _|
     |
     |

ㅔ
     ||
    _||
     ||
     ||

ㅕ
     |
    _|
    _|
     |

ㅖ
     ||
    _||
    _||
     ||

ㅗ

 |
_|__

ㅘ
    |
    |
    |_
 |  |
_|__|

ㅙ
    | |
    | |
    |_|
 |  | |
_|__| |

ㅚ
    |
    |
    |
 |  |
_|__|

ㅛ

 ||
_][_

ㅜ

____
 |

ㅝ
    |
    |
    |
____|
 |--|

ㅞ
    ||
    ||
    ||
____||
 |--||

ㅟ
    |
    |
    |
____|
 |  |

ㅠ

____
 ||

ㅡ

____

ㅢ
    |
    |
    |
    |
____|

ㅣ
    |
    |
    |
    |

ㄳ
_ /|
 |||
 |||

ㄵ
| __
| /|
|_||

ㄶ
| __
| __
|_()

ㄺ
_ _
 ] |
[_ |

ㄻ
_ ++
 ]||
[_""

ㄼ
_ ||
 ][]
[_""

ㄽ
_ /|
 ]||
[_||

ㄾ
_  _
 ]|_
[_|_

ㄿ
_ __
 ]][
[_""

ㅀ
_ __
 ]__
[_()

```

### Style 2

```
ㄱ
---.
   :
   :

ㄴ
:
:
'---

ㄷ
.---
:
'---

ㄹ
---.
.--'
'---

ㅁ
.--.
:  :
'--'

ㅂ
:  :
:--:
'--'

ㅅ
 ,.
:  :
:  :

ㅇ
 ..
(  )
 ''

ㅈ
-.,-
 ;:
'  `

ㅊ
 --
-,.-
;  :

ㅋ
---.
---:
   :

ㅌ
.---
:---
'---

ㅍ
-..-
 ::
-''-

ㅎ
 --
----
 ()

ㄲ
-.-.
 : :
 : :

ㄸ
.-.-
: :
'-'-

ㅃ
::::
[][]
''''

ㅆ
,:,:
::::
::::

ㅉ
----
,:,:
::::

ㅏ
    :
    :-
    :
    :

ㅐ
    : :
    :-:
    : :
    : :

ㅑ
    :
    :-
    :-
    :

ㅒ
    : :
    :-:
    :-:
    : :

ㅓ
     :
    -:
     :
     :

ㅔ
     ::
    -::
     ::
     ::

ㅕ
     :
    -:
    -:
     :

ㅖ
     ::
    -::
    -::
     ::

ㅗ

 :
-^--

ㅘ
    :
    :
    :-
 :  :
-^--:

ㅙ
    : :
    : :
    :-:
 :  : :
-^--: :

ㅚ
    :
    :
    :
 :  :
-^--:

ㅛ

 ::
-^^-

ㅜ

-v--
 :

ㅝ
    :
    :
    :
-v--:
 :--:

ㅞ
    ::
    ::
    ::
-v--::
 :--::

ㅟ
    :
    :
    :
-v--:
 :  :

ㅠ

-vv-
 ::

ㅡ

----

ㅢ
    :
    :
    :
    :
----:

ㅣ
    :
    :
    :
    :

ㄳ
-.,:
 :::
 :::

ㄵ
: --
: ,:
'-::

ㄶ
: --
: --
'-()

ㄺ
-.-.
.' :
'- :

ㄻ
-...
.'::
'-''

ㄼ
-.::
.'][
'-''

ㄽ
-.,:
.'::
'-::

ㄾ
-..-
.':-
'-'-

ㄿ
-...
.'][
'-''

ㅀ
-.--
.'--
'-()

```

### Style 3

```
ㄱ
───┐
   │
   │

ㄴ
│
│
└──

ㄷ
┌───
│
└───

ㄹ
───┐
┌──┘
└───

ㅁ
┌──┐
│  │
└──┘

ㅂ
│  │
├──┤
└──┘

ㅅ
 ╱╲
│  │
│  │

ㅇ
╭──╮
│  │
╰──╯

ㅈ
────
 ╱╲
╱  ╲

ㅊ
 ──
────
╱  ╲

ㅋ
───┐
───┤
   │

ㅌ
┌───
├───
└───

ㅍ
─┬┬─
 ││
─┴┴─

ㅎ
 ──
────
 ()

ㄲ
─┐─┐
 │ │
 │ │

ㄸ
┌─┌─
│ │
└─└─

ㅃ
││││
├┤├┤
└┘└┘

ㅆ
╱│╱│
││││
││││

ㅉ
────
╱│╱│
││││

ㅏ
    │
    ├─
    │
    │

ㅐ
    │ │
    ├─┤
    │ │
    │ │

ㅑ
    │
    ├─
    ├─
    │

ㅒ
    │ │
    ├─┤
    ├─┤
    │ │

ㅓ
     │
    ─┤
     │
     │

ㅔ
     ││
    ─┤│
     ││
     ││

ㅕ
     │
    ─┤
    ─┤
     │

ㅖ
     ││
    ─┤│
    ─┤│
     ││

ㅗ

 ╷
─┴──

ㅘ
    │
    │
    ├─
 ╷  │
─┴──│

ㅙ
    │ │
    │ │
    ├─┤
 ╷  │ │
─┴──│ │

ㅚ
    │
    │
    │
 ╷  │
─┴──│

ㅛ

 ╷╷
─┴┴─

ㅜ

─┬──
 ╵

ㅝ
    │
    │
    │
─┬──│
 ╵──┤

ㅞ
    ││
    ││
    ││
─┬──││
 ╵──┤│

ㅟ
    │
    │
    │
─┬──│
 ╵  │

ㅠ

─┬┬─
 ╵╵

ㅡ

────

ㅢ
    │
    │
    │
    │
────│

ㅣ
    │
    │
    │
    │

ㄳ
─┐╭╮
 │││
 │││

ㄵ
╷ ──
│ ╱│
└─╵╵

ㄶ
│ ──
│ ──
└─()

ㄺ
─┐─┐
┌┘ │
└─ ╵

ㄻ
─┐┌┐
┌┘││
└─└┘

ㄼ
─┐╷╷
┌┘├┤
└─└┘

ㄽ
─┐╭╮
┌┘││
└─╵╵

ㄾ
─┐┌─
┌┘├─
└─└─

ㄿ
─┐┬┬
┌┘││
└─┴┴

ㅀ
─┐──
┌┘──
└─()

```

## Example input and output

`1한2글3날`

```
 __ |   ---.  │   │
____|_     :  │   ├─
 () |      :  └── │
    |   ----      │
 |      ---.   ───┐
 |      .--'   ┌──┘
 |__    '---   └───

```

`뛟쀒3쫽`

```
 _ _||  ||||||  ────│ │
| | ||  [][]||  ╱│╱││ │
|_|_||  """"||  ││││├─┤
____||  ____||   ╷  │ │
 |--||   |--||  ─┴──│ │
 _ __    _ __    ─┐─┐
  ]__     ]][    ┌┘ │
 [_()    [_""    └─ ╵

```

## Scoring

This is , so the shortest code in bytes wins.

# Answer
> 8 votes
# C, 1832 bytes

Well, this is the first time I've ever golfed anything, and this is easily the ugliest code I have ever written:

(compiled with gcc 7.5.0)

```
#define C(x,y)case 0x##x:y;break;
#define c(x)case x:r=r<<6|getchar()&63;
#define F(x,n)for(x=0;x<n;x++)
#define M(n)"\e["#n"D\e[B"
#define m M(1)
#define U(n)"\e["#n"A"
#define l U(4)
char p[]={0,1,3,6,27,7,15,16,28,18,19,20,21,29,22,23,24,25,26},*H="---.-.-.-.,::   : --: --.------.-.-.-...-.::-.,:-..--...-.--.--.:  :::,: ,. ,:,: .. -.,- -- ---..----..- -- .-.-::::----   : : : ::::   : ,:: --:   .--'.' :.'::.'][.'::.':-.'][.'--:  ::--:[]:::  :::::(  ) ;: -,.----::--- :: ----: : [][],:,:   : : : :::'---'-::'-()'---'---'- :'-'''-'''-::'-'-'-'''-()'--''--''':::  ::::: '' '  `;  :   :'----''- () '-'-''''::::",*B=M(4),
#define P "    "U(3)
#define Q " :"M(2)"-^--"l
*U[]={P,P,P,P,P,P,P,P,Q,Q,Q,Q," ::"M(3)"-^^-"l,"-v--"M(4)" :  "l,"-v--"M(4)" :--"l,"-v--"M(4)" :--"l,"-v--"M(4)" :  "l,"-vv-"M(4)" :: "l,"----","    "M(4)"----"U(4),P},
#define X(x,y)x y x
#define Y(x,y)x y y
#define Z(x,y)x x y x
#define R "\e[4B"M(4)
#define S Z(":"m,":"m)":"M(4)
*V[]={X(":"m,":-"M(2))":"M(4),X(": :"M(3),":-:"M(3))": :"M(6),Y(":"m,":-"M(2))":"M(4),Y(": :"M(3),":-:"M(3))": :"M(6),X(" :"M(2),"-:"M(2))" :"M(5),X(" ::"M(3),"-::"M(3))" ::"M(6),Y(" :"M(2),"-:"M(2))" :"M(5),Y(" ::"M(3),"-::"M(3))" ::"M(6),R,Z(":"m,":-"M(2))":"M(4),Z(": :"M(3),":-:"M(3))": :"M(6),S,R,R,S,Z("::"M(2),"::"M(2))"::"M(5),S,R,M(4),S,Z(":"m,":"m)"\e[3D"},
#define w(m,n)"\e["#m"C"U(n)
#define T w(7,7)
#define W w(8,7)
#define x w(6,8)
*A[]={T,W,T,W,T,W,T,W,x,w(7,8),w(7,8),x,x,x,x,w(7,8),x,x,x,x,x};
#define D(x) printf(x);
g(){int r=getchar(),n=~0;switch(r>>4){C(f,n=7)C(e,n=15)C(d,C(c,n=31))}r&=n;switch(n){c(7)c(15)c(31)}return r;}main(){D("\e[2J\e[H")int n,j,k,t,v,h;while(~(n=g())){if(n>>8){n-=44032;t=n%28;v=n/28%21;h=p[n/588];F(j,3){F(k,4)putchar(H[(j*30+h)*4+k]);D(B)}D(U[v])D(V[v])if(t--)F(j,3){F(k,4)putchar(H[(j*30+t)*4+k]);D(B)}else D("\e[3B")D(A[v])}}}

```

It only does style 2; the challenge was already difficult enough for me without needing to support all three styles! It's a shame though, because I'm really in love with the charming ASCII art the OP made (by the way, they forgot to provide art for the ㅃ jamo, so I made one myself).

You can see the project here: https://repl.it/@Mahkoe/hangul-ASCII-art

***Brief hints for understanding the code***

* This makes heavy use of ANSI escape sequences for moving the cursor. The `U(n)` macro moves the cursor up by `n` characters, and the `M(n)` macro moves the cursor left by `n` characters then down by one. (`U` stands for "up", and `M` stands for "mot", which is French for "word").
* Because `U(4)` appeared enough times, I defined `l` to `U(4)` (`l` doesn't stand for anything, it was just one of the few single-character identifiers left).
* The `g` function reads stdin and parses out a UTF-8 sequence. It correctly returns EOF when it sees one.
* The `C` and `c` macros are used to shorten the cases in the switch statements in the `g` function.
* The `H` string contains all the tail consonants (copy-paste the string to a text file and break it into three 30-character wide lines to see it better). They are ordered according to increasing UTF-8 codepage addresses. (I originally called this string `H` because early on it only had head consonants, but the name stuck around even after I changed my mind and put in the tail consonants).
* Some consonants are head-only consonants (ㄸ, ㅃ, and ㅉ), so I tacked these onto the "right-hand side" of `H`. The `p` array is a mapping from the head consonant number to the position in the `H` string. (I originally called this array `p` because I thought of it as a permutation, but the name stuck around after I realized it wasn't actually a permutation).
* The vowels had so many special cases that I ended up splitting a vowel into three actions: the "underneath" (anything that would end up between the head and tail consonants), the rest of the vowel, and any adjustments needed to the cursor after drawing the tail consonant. These three quantities are stored in the `U`, `V`, and `A` strings, respectively.
* If anything appeared often enough in the `U`, `V`, or `A` strings, I made a macro for it. This consists of the `P`, `Q`, `R`, `S`, `T`, `W`, `w`, and `x` macros (I started having name collisions, which is why the macro name pattern breaks after `T`).
* All together, the `main` function eats characters from stdin until it gets an EOF. If it sees a Hangul character, it prints the head consonant, then the underneath, then the rest of the vowel, then the tail consonant, then the adjustment.

This challenge was delightful, and I'm really excited about having learned Hangul. Thanks!

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


# Question
Title: Sub-string Extractor with Specific Keywords
**Challenge**

The goal of this challenge is to make a function that takes an input string, a start keyword and a end keyword. The output extracted result is from (but excluded) the given start keyword to (but excluded) end keyword. The output sub-string follows the rules as below.

* In all cases, the leading/trailing spaces in output sub-string should be removed.
* If the given start keyword is an empty string, it means that the anchor is at the start of the input string. Otherwise, the first occurrence of the given start keyword is an start anchor. If there is no any occurrence of the given start keyword, the output is an empty string.
* If the given end keyword is an empty string, it means that the anchor is at the end of the input string. Otherwise, the first occurrence of the given end keyword is an end anchor. If there is no any occurrence of the given end keyword, the output is an empty string.
* If the location of start anchor is after than the location of end anchor, or a part of the first occurrence of the given start keyword and a part of the first occurrence of the given end keyword are overlapped, the output is an empty string.

Similar but different from Extract a string from a given string, the given start and end anchors are multiple characters.

Here's an ungolfed reference implementation in C#

```
private static string GetTargetString(string stringInput, string startKeywordInput, string endKeywordInput)
{
    int startIndex;
    if (String.IsNullOrEmpty(startKeywordInput))
    {
        startIndex = 0;
    }
    else
    {
        if (stringInput.IndexOf(startKeywordInput) >= 0)
        {
            startIndex = stringInput.IndexOf(startKeywordInput) + startKeywordInput.Length;
        }
        else
        {
            return "";
        }

    }

    int endIndex;
    if (String.IsNullOrEmpty(endKeywordInput))
    {
        endIndex = stringInput.Length;
    }
    else
    {
        if (stringInput.IndexOf(endKeywordInput) > startIndex)
        {
            endIndex = stringInput.IndexOf(endKeywordInput);
        }
        else
        {
            return "";
        }
    }

    //    Check startIndex and endIndex
    if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex)
    {
        return "";
    }

    if (endIndex.Equals(0).Equals(true))
    {
        endIndex = stringInput.Length;
    }
    int TargetStringLength = endIndex - startIndex;
    return stringInput.Substring(startIndex, TargetStringLength).Trim();
}

```

**Example Input and Output**

The example input and output is listed as below.

| Input String | Start Keyword | End Keyword | Output |
| --- | --- | --- | --- |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ""(empty string) | ""(empty string) | "C# was developed around 2000 by Microsoft as part of its .NET initiative" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ""(empty string) | ".NET" | "C# was developed around 2000 by Microsoft as part of its" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "C#" | ""(empty string) | "was developed around 2000 by Microsoft as part of its .NET initiative" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "C#" | ".NET" | "was developed around 2000 by Microsoft as part of its" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ".NET" | ""(empty string) | "initiative" |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ""(empty string) | "C#" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ".NET" | "C#" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "ABC" | "C#" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | ".NET" | "XYZ" | ""(empty string) |
| "C# was developed around 2000 by Microsoft as part of its .NET initiative" | "ABC" | "XYZ" | ""(empty string) |

**Rules**

This is . The answer with the fewest bytes wins.

# Answer
# APL (Dyalog Extended), 24 bytes (SBCS)

Full program that prompts for array of `[EndKeyword,StartKeyword,InputString]`. Requires 0-based indexing.

```
⌂deb⊃(⌽⊢↓⍨1⍳⍨⊣,⍷)/⌽¨@0⊢⎕

```

Try it online!

prompt for input

on that…

`⌽¨@0` reverse all the elements that occur at offset 0

`(``)/` reduce from the right using the following tacit function:

indicate with a Boolean list all the places where the left argument begins in the right argument

`⊣,` prepend the left argument to that

`1⍳⍨` find the offset of the first 1

`⊢↓⍨` drop that many leading elements from the right argument

reverse (next time around, do this from the end, and after that, revert order)

disclose the enclosure caused by the reduction from a 1-dimensional array to a 0-dimensional array

`⌂deb`**d**elete **e**nding (leading and trailing) **b**lanks
> 2 votes

# Answer
# JavaScript (ES6),  ~~80~~  75 bytes

This contains some unprintable characters which are escaped below.

```
(s,a,b)=>s.replace(b||/$/,"").replace(a,"").match(/ *(.*?) *|$/)[1]||""

```

Try it online!

### Commented

```
(s, a, b) =>          // s = input string, a = start keyword, b = end keyword
  s.replace(          // replace in s:
    b || /$/,         //   look for the end keyword, or the regex /$/ if it's empty
    "\3"              //   and replace it with ETX (end of text)
  )                   //
  .replace(           // replace in the resulting string:
    a,                //   look for the start keyword
    "\2"              //   and replace it with STX (start of text)
  )                   //
  .match(             // attempt to match:
    /\2 *(.*?) *\3|$/ //   "\2"    STX
  )                   //   " *"    followed by optional whitespace
                      //   "(.*?)" followed by a non-greedy string (the payload)
                      //   " *"    followed by optional whitespace
                      //   "\3"    followed by ETX
                      //   "|$"    OR match an empty string to make sure that
                      //           match() doesn't return null
  [1] || ""           // return the payload string, or an empty string if undefined

```
> 5 votes

# Answer
# Python 3, <sup>~~86~~ ~~77~~</sup> 75 bytes

Saved 9 bytes thanks to movatica!!!
Saved 2 bytes thanks to ovs!!!

```
lambda s,a,b:s[s.find(a):(b in s)*s.find(b)if b else None][len(a):].strip()

```

Try it online!
> 3 votes

# Answer
# Ruby, 66 bytes

```
->w,s,e,r=Regexp{"#{w[/#{r.quote s}\K.+(?=#{r.quote e})/]}".strip}

```

Try it online!

Another method without the use of regex,

# Ruby, 72 bytes

```
->w,s,e{"#{w[((w+s).index(s)+s.size rescue 0)...w.rindex(e)||0]}".strip}

```

Try it online!
> 1 votes

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

```
(s,a,b)=>s.substr(p=(s+a).indexOf(a)+a.length,b?s.indexOf(b)-p:1/0).trim()

```

Try it online!

Quite straightforward...
> 1 votes

# Answer
# Wolfram Language (Mathematica), 93 bytes

```
sStringTrim@StringTake[s,i=1;If[i*=-1;#=="",0,StringPosition[s,#][[1,i]]]-i&/@#]/._@_:>""&

```

Try it online!
> 1 votes

# Answer
# Red, 90 bytes

```
func[t s e][p:""if""<> s[append s" "]if e =""[e:[end]]parse t[thru s copy p to[opt" "e]]p]

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~100~~ 85 bytes

Regex version, still cannot beat the slicing algorithm.

```
from re import*
r=escape
f=lambda s,b,e:(search(r(b)+'(.+)'+r(e),s)or'  ')[1].strip()

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 60 bytes

```
(.*)¶(.+)?¶.*?\1 *(.*?) *(?<!(?=\2).*)(?(2)\2.*|$)|(.|¶)+
$3

```

Try it online! Takes input as start, end, string on separate lines but link is to test suite with header that converts from comma separated string, end, start for convenience. Explanation:

```
(.*)¶

```

Match the start keyword.

```
(.+)?¶

```

Optionally match a non-empty end keyword.

```
.*?\1

```

Find the start keyword as early as possible in the string, plus optional spaces.

```
 *(.*?) *

```

Match as short a result as possible (so that the end keyword is found as early as possible in the string) but also trim spaces around it.

```
(?<!(?=\2).*)

```

Ensure that the end keyword hasn't already been passed at this point.

```
(?(2)\2.*|$)

```

If the end keyword was empty then only match at the end of the string otherwise match the end keyword and the rest of the string.

```
|(.|¶)+

```

If it wasn't possible to match anything, delete everything.

```
$3

```

Keep the desired result.
> 1 votes

# Answer
# C (gcc), ~~168~~ ~~152~~ ~~143~~ ~~132~~ 112 bytes

An enormous **-38** thanks to @ceilingcat

```
#define r strstr(c
*f(c,s,e)int*c,*s,*e;{return*e&&r,s)>r,e)|!r,s)|!r,e)||*e&&(*r,e)=0)?"":r,s)+strlen(s)+!!*s;}

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6) ~~95~~ 92 Bytes, No Regex!

```
(i,s,e,t=i.indexOf(s),r=i.lastIndexOf(e))=>t!=-1&r!=-1?(i.substring(t+s.length,r)).trim():''

```

### How to try it:

Open your browser's JavaScript Console and paste the following.

```
((i,s,e,t=i.indexOf(s),r=i.lastIndexOf(e))=>t!=-1&r!=-1?(i.substring(t+s.length,r)).trim():'')('C# was developed around 2000 by Microsoft as part of its .NET initiative', 'C#', '.NET')

```
> 0 votes

# Answer
# Charcoal, 41 bytes

```
≔⎇ζ…θ⌕θζθθ≔⎇η⪫Φ⪪θηκηθθ≔⌕ＡＥθ›ι ¹ε¿ε✂θ⌊ε⊕⌈ε

```

Try it online! Link is to verbose version of code. Take care to include sufficient newlines in the input even if one of the keywords is empty. Explanation:

```
≔⎇ζ…θ⌕θζθθ

```

If the end keyword is not empty then truncate the string at its first appearance. (Fortunately `CycleChop` truncates the string to empty if its input is negative.)

```
≔⎇η⪫Φ⪪θηκηθθ

```

If the start keyword is not empty then split the string on the keyword, discard the first element, and join the string again. This results in an empty string if the start keyword does not appear in the string.

```
≔⌕ＡＥθ›ι ¹ε

```

Check whether the string has any non-spaces.

```
¿ε✂θ⌊ε⊕⌈ε

```

If so then print from the first to the last non-space.
> 0 votes

# Answer
# , 111 bytes

```
function(s,a,b,c=?s,`?`=nchar,r=regexpr)trimws(substr(s,`if`((d=r(a,s,f=T))>0,d+?a,c),`if`(?b,r(b,s,f=T)-1,c)))

```

Try it online!

Straightforward approach: finds bounding words using `regexpr` (with argument `f`ixed=`T`rue to ensure that the text string is not interpreted as a regex), gets the `substr`ing between them, and then `trim`s the `w`hite`s`pace from both ends.

Since the functions `nchar` and `regexpr` are each used twice, it's shorter to define single-character aliases. In the case of `nchar`, we can even redefine the unary operator `?` as its alias, so that we avoid the need for parentheses. Unfortunately, this trick isn't possible here for `regexpr` because of the need to feed it the additional argument `f`ixed=`T`rue.
> 0 votes

# Answer
## C# 114 bytes

```
(i,s,e)=>{int p=(i+(s??="")).IndexOf(s)+s.Length,q=$"{e}"==""?i.Length:i.IndexOf(e);return p<q?i[p..q].Trim():"";}

```
> 0 votes

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


# Question
Title: Print a specific value in the infinite Walsh matrix
The Walsh matrix is an interesting fractal matrix with the property that every single value in a Walsh matrix has a value of either -1 or 1. Additionally, the size of a Walsh matrix is always a power of 2.

Because each Walsh matrix is identical to the top-left quarter of the immediately higher-order Walsh matrix, we can create a generalized "infinite Walsh matrix" by considering the limit of the sequence of Walsh matrices of order N, as N goes to infinity. From here on, we will call this infinite generalization *the Walsh matrix*.

Your task is to build a program that takes the coordinates of a location in the Walsh matrix and returns the value that occurs there.

Your program will accept two integers `x` and `y` as input (in any form you choose), and output the value that appears in the `x+1`th row of the `y+1`th column of the Walsh matrix. For example, the input

```
2 5

```

will return `1`, as the 3rd row in the 6th column of the Walsh matrix has a value of 1. The input

```
6 4

```

will return `-1`, as the 7th row in the 5th column of the Walsh matrix has a value of -1. The input

```
2834719 394802

```

will return `-1`, as the 2384720th row of the 394803rd column has a value of -1.

The shortest code to do this in any language wins.

# Answer
## GolfScript (18 15 14 bytes)

```
~&2base-1\0-,?

```

Takes input space-separated; outputs to stdout. Thanks to Howard for pointing out that the space in the 15-char solution was removable.

The way I reasoned to this solution is quite simple. Take the highest set bit of `x|y`: this tells you the size of the smallest Walsh matrix which contains the relevant index. Then clearing that bit in both `x` and `y` drops us down to the top-left quadrant, and we need to multiply by `-1` if we were previously in the bottom-right quadrant: i.e. if the bit was set in both `x` and `y`. By induction down the bit sequence, we just need to count the number of bits set in `x&y`.
> 4 votes

# Answer
# Forth (gforth), 44 bytes

```
: f and 1e 63 for s>d 2* 1+ s>f f* 2* next ;

```

Try it online!

The function takes two word-sized unsigned integers (64 bits on TIO). It returns -1 or 1 on the floating-point stack and leaves a garbage 0 on the main stack.

The algorithm follows Blckknght's submission, but the task made me explore LOTS of possibilities for writing Forth programs - from bit shift, divmod, single-to-double conversion to abusing floating-point stack. (The TIO link has several alternative definitions of `f` which all work, but are longer than the main answer.)

### How it works

```
: f ( u1 u2 -- -1e_or_1e )  \ Takes two integers and returns a float 1 or -1
  and 1e                    \ Bitwise and(=N), then put a 1(=R) on the FP stack
  63 for                    \ Repeat 64 times... (TIO gforth has 64-bit cells)
    s>d                       \ Sign-extend single N to double
                              \ In effect, 0 is pushed if MSB is zero, -1 otherwise
    2* 1+ s>f f*              \ Change 0_or_-1 to 1_or_-1, cast to float and multiply with R
    2*                        \ Shift N left once
  next                      \ End loop
  ;                         \ End function

```
> 3 votes

# Answer
# Python 2 - 42 bytes

```
print(-1)**bin(input()&input()).count("1")

```

This takes the two coordinates as separate lines on standard input and writes the answer to standard output.

The algorithm is this:

1. For coordinates `X` and `Y`, find `X & Y`, the bitwise AND of their values.
2. Count the number of 1 bits in `X & Y`. This is the number of times the requested coordinate is in the bottom right quadrant of a level of the matrix.
3. If the count is odd, the result is -1. If the count is even, the result is 1.

This should work for any positive integer coordinates (including large ones that need more than 32 bits).
> 2 votes

# Answer
# x86\_64 machine language for Linux, 17 bytes

```
0x00:  48 21 F7          and    rdi, rsi
0x03:  F3 48 0F B8 C7    popcnt rax, rdi
0x08:  FF C0             inc    eax
0x0a:  24 01             and    al, 1
0x0c:  01 C0             add    eax, eax
0x0e:  FF C8             dec    eax
0x10:  C3                ret

```

Same algorithm as @Blckknght's answer.

Try it online!
> 1 votes

# Answer
# K (ngn/k), ~~18~~ 16 bytes

-2 bytes by converting to tacit form

```
-:/[;1]@+/&/+2\,

```

Try it online!

Based off of @Blckknght's Python 2 answer.

* `&/+2\,` take the (equivalent of) the bitwise-and of x and y
* `+/` do a popcnt (i.e. number of bits set to 1)
* `-:/[;1]@` negate `1` that many times and return
> 1 votes

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


title: Embedded Triangles!

text:
# Question
Title: Embedded Triangles!
Your task: given an integer `n`, output an embedded triangle to the `nth` depth.

Standard methods of input and output, input in any convenient format, output should be as a string. Examples are 0-indexed, you can use 1-indexed if you want. Standard loopholes apply

The left and right sides of each figure is 2^n, when 0 indexed. The top is twice that.

Examples:

```
n=0
--
\/

n=1
----
\/ /
 \/

n=2
--------
\/ /   /
 \/   /
  \  /
   \/

```

This is , so shortest code wins!

This is NOT a duplicate of the Embedded Hexagons! challenge. I don't think any answers from that question could be trivially copied over to this one.

# Answer
> 2 votes
# Charcoal, 27 bytes

```
ＮαＷα«Ｘ²ι↙ＡＸ²⁻ι¹β↙β↑↖β→Ａ⁻α¹α

```

Try it online!

Just modified my submission from the hexagon challenge a bit to make a triangle.

# Answer
> 4 votes
# Retina, 44 bytes

```
^
\/
+`( *)/1
$1/$1 $1/
*`.
-
;+(*G`
\\..
 \

```

Try it online!

I only want to print successful replacements, but I don't really know how to do that.

As I'm no longer allowed to add another answer, here's a Batch answer for 192 bytes:

```
@echo off
set d=-
set l=\
set r=/
for /l %%i in (1,1,%1)do @call set r=%%r%%%%d:-= %%/&call set d=%%d%%-%%d%%
echo -%d%
:l
echo %l%%r%
set l= %l%
set r=%r:~2%
if not "%r%"=="" goto l

```

And here's a JavaScript (ES7) port of @lanlock4's excellent Mathematica answer for 124 bytes:

```
f=
n=>[...Array(2**n+1)].map((_,i)=>[...Array(2<<n)].map((_,j)=>i?i+~j?i>j?` `:i+j-(i+j&-i-j)?` `:`/`:`\\`:`-`).join``).join`
`
```

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

And here's a Charcoal answer for 16 bytes:

```
ＦＥＮＸ²ι«ιι↙↙ι↑↖ι→

```

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

```
  Ｎ                 Input number
 Ｅ                  Map over implicit range
    ²               Literal 2
     ι              Current index
   Ｘ                Exponentiate
Ｆ     «             Loop over resulting powers of 2
       ι            Print right
        ι           Print right again
         ↙          Move down and left
          ↙ι        Print down and left
            ↑       Move up
             ↖ι     Print up and left
               →    Move right

```

# Answer
> 2 votes
## Mathematica, 105 bytes

```
""<>Table[Which[i<1,"-",i==j,"\\",IntegerQ@Log2[i+j-1]&&j>i,"/",1>0," "],{i,0,2^#},{j,2*2^#}]~Riffle~"\n"&

```

where `\n` is replaced with a newline.

Explanation: Makes an array of characters (indexed from *i* = 0 to 2^*n* vertically, *j* = 1 to 2^(*n*+1) horizontally) according to these rules:

* If `i<1` (so *i* = 0), put a `"-"` (for the top row)
* If `i==j`, put a `"\"` (escaped, for the left-hand side)
* If `Log2[i+j-1]` is an integer (so *i*+*j*-1 is a power of 2) and `j>i`, put a `"/"` (for the other edges)
* And put `" "` everywhere else.

Then `""<>...~Riffle~"\n"&` turns this array into a string.

# Answer
> 1 votes
# JavaScript (JavaScript Shell), ~~136~~ 132 bytes

```
t=2**readline();p=print;p(v='-'.repeat(t*2));for(y=0;y<t;y++)p(' '.repeat(y)+'\\'+v.replace(/-/g,(_,i)=>i&-~i?' ':'/').slice(y*2+1))

```

Try it:

```
readline = () => prompt();
print = (...args) => output += (args.join(' ') + '\n');
output = '';

t=2**readline();p=print;p(v='-'.repeat(t*2));for(y=0;y<t;y++)p(' '.repeat(y)+'\\'+v.replace(/-/g,(_,i)=>i&-~i?' ':'/').slice(y*2+1))

document.write(`<pre>${output}</pre>`);
```

# Answer
> 1 votes
# C, 200 bytes

```
#define P printf(
i,j,k,l;f(n){for(i=0,k=pow(2,n);i++<k;)P"--");for(i=0;i<k;++i){l=P"\n%*c",i+1,92);for(j=0;j<n;++j)if(2*(int)pow(2,j)+1-i>l)l+=P"%*c",2*(int)pow(2,j)+1-i-l,47);P"%*c",2*k-i-l+1,47);}}

```

Try it online!

# Answer
> 1 votes
## JavaScript (ES6), ~~108~~ ~~95~~ ~~93~~ 92 bytes

```
let f =

n=>(g=x=>y>1<<n?'':x<2<<n?' /\\-'[y?~x+y?+!(k=x+y,x<y|k&-k-k):2:3]+g(x+1):`
`+g(!++y))(y=0)

console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
```

# Answer
> 1 votes
# 05AB1E, 45 bytes

I made it! (It's a fun challenge, I don't get why they VTC'd it)

```
<oLð×ε¨'\«}IL<oð×ε¨'/«}JDgU.sR2ô€нøJ»X>'-×s‚»

```

Try it online!

# Answer
> 1 votes
# Canvas, 22 bytes

```
╵ｒＨ２；＾／Ｌ ×；＋ｎ｝ｌ＼ｎＬ-×；∔

```

Try it here!

## Explanation

```
'rH2;^/L ×;+n}l\nL-×;∔
'                      increment input integer n
 r                     range 0..n
  H          }         push an empty string and start a loop
   2;^                 get 2^i
      /                antidiagonal of that length
       L               get width(don't pop)
         ×;_           add that many spaces to the left
            n          overlap with prev iteration
              l        get height(don't pop)
               \       create a diagonal of that length
                n      and overlap with the created sides
                 L     get width(don't pop)
                  -×;∔ add that many minuses to the top

```

# Answer
> 0 votes
# PHP, 137 Bytes

```
for(;$i<1+2**$a=$argn;++$i)for($n=0;$n<$m=2**($a+1);$s[]=2**++$n)echo$n%$m?"":"\n",$i?$i-1!=$n?$i<=$n&in_array($i+$n,$s)?"/":" ":"\\":"-";

```

Online Version

Expanded

```
for(;$i<1+2**$a=$argn;++$i)
for($n=0;$n<$m=2**($a+1);$s[]=2**++$n) # fill array for sum compare after loop
echo$n%$m?"":"\n", # print line feed
$i  # false for first line
 ?$i-1!=$n # row number - 1 equal column print \
  ?$i<=$n&in_array($i+$n,$s) # if row number lte column and sum of both in array print /
   ?"/"
   :" " # else print space
  :"\\"
 :"-"; # fill first line

```

A recursive way for 199 Bytes

```
function f($a){global$r;for(;$i<1+2**$a;$i++)for($n=0;$n<$m=2**($a+1);$n++)$r[$i][$n]=$i?$i-1!=$n?$i<=$n&&$i+$n==2**($a+1)?"/":" ":"\\":"-";$a?f($a-1):0;}f($argn);echo join("\n",array_map("join",$r));

```

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


title: Go generate some Java

text:
# Question
Title: Go generate some Java
Your boss wants you to write code like this:

```
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

```

(Martin Smith, at https://codereview.stackexchange.com/a/117294/61929)

which is efficient and so, but not that fun to type. Since you want to minimize the number of keypresses you have to do, you write a shorter program or function (or method) that outputs this function for you (or returns a string to output). And since you have your very own custom full-range unicode keyboard with all 120,737 keys required for all of unicode 8.0, we count unicode characters, instead of keypresses. Or bytes, if your language doesn't use unicode source code.

Any input your program or function takes counts towards your score, since you obviously have to type that in as well.

Clarifications and edits:

* Removed 3 trailing spaces after the last `}`
* Removed a single trailing space after `return`
* Returning a string of output from a function/method is ok

# Answer
# PostgreSQL, 158 characters

```
select'public static boolean isPowerOfTen(long input) {
  return
   '||string_agg(' input == 1'||repeat('0',x)||'L','
  ||')||';
}'from generate_series(0,18)x

```
> 15 votes

# Answer
# CJam, 52 characters

```
YA#_(""f&bY7#b:c~

```

Try it online!

### Stage 1

Using Unicode characters U+10000 to U+10FFFF, we can encode 20 bits in a single character. CJam uses 16-bit characters internally, so each one will be encoded as a pair of surrogates, one in the range from U+D800 to U+DBFF, followed by one in the range from U+DC00 to U+DFFF.

By taking the bitwise AND of each surrogate with 1023, we obtain the 10 bits of information it encodes. We can convert the resulting array from base 1024 to base 128 to decode an arbitrary string of Unicode characters outside the BMP to an ASCII string.

The code does the following:

```
YA#    e# Push 1024 as 2 ** 10.
_(     e# Copy and decrement to push 1023.

""

f&     e# Apply bitwise AND with 1023 to each surrogate character.
b      e# Convert the string from base 1024 to integer.
Y7#    e# Push 128 as 2 ** 7.
b      e# Convert the integer to base 128.
:c     e# Cast each base-128 to an ASCII character.
~      e# Evaluate the resulting string.

```

### Stage 2

The decoding process from above yields the following source code (**98 bytes**).

```
"public static boolean isPowerOfTen(long input) {
  return
   ""L
  || input == ":S6>AJ,f#S*"L;
}"

```

Try it online!

The code does the following:

```
e# Push the following string.

"public static boolean isPowerOfTen(long input) {
  return
   "

e# Push the following string and save it in S.

"L
  || input == ":S

e# Discard the first 6 characters of S. The new string begins with " input".

6>

e# Elevate 10 (A) to each exponent below 19 (J).

AJ,f#

e# Join the resulting array, using the string L as separator.

S*

e# Push the following string.

"L;
}"

```
> 8 votes

# Answer
# Java, ~~217~~ ~~215~~ ~~220~~ ~~219~~ 192 bytes

Golfed:

```
public static String b(){String s="public static boolean isPowerOfTen(long input) {\n  return\n    input == 1L",z="";for(int i=0;i++<18;){z+="0";s+="\n  || input == 1"+z+"L";}return s+";\n}";}

```

Ungolfed:

```
  public static String a(){
    String s = "public static boolean isPowerOfTen(long input) {\n  return\n    input == 1L", z="";
    for (int i=0; i++ < 18;) {
        z += "0";
        s += "\n  || input == 1"+z+"L";
    }
    return s + ";\n}";
  }

```

(first answer, wuhu)

Thanks!
-2 bytes: user902383
-1 byte: Denham Coote

Changes:

* used tabs instead of spaces
* missed the last line of output: 18 -\> 19
* removed inner loop
* changed from printing to returning string
> 7 votes

# Answer
# 05AB1E, ~~99~~ ~~97~~ ~~96~~ ~~94~~ ~~93~~ 87 bytes

Code:

```
“‚Æ£‹ÒŒ€ˆPowerOfTen(“?“¢„î®) {
 «‡
   “?19FN0›i"  ||"?}’ î® == ’?N°?'L?N18Qi';,"}"?}"",

```

Try it online!

Uses **CP-1252** encoding.
> 7 votes

# Answer
# Vim 97 keystrokes

```
ipublic static boolean isPowerOfTen(long input) {
  return
  || input == 1L<esc>qyYpfLi0<esc>q16@yo}<esc>3Gxx

```

Well, I'm on a roll today with vim producing java, so why not continue the trend!
> 7 votes

# Answer
## PowerShell, 120 bytes

```
'public static boolean isPowerOfTen(long input) {'
'  return'
"   $((0..18|%{" input == 1"+"0"*$_})-join"L`n  ||")L;`n}"

```

The first two lines are simply string literals, which are output as-is.

The third line starts with three spaces, and ends with `L;`n}"` to finish off the last couple bytes. The middle bit inside the script block `$(...)` is constructed by for-looping `%` from `0` to `18` and each iteration constructing a string that starts with  `input == 1` concatenated with the corresponding number of zeros. This will spit out an array of strings. We then `-join` each element of the array with `L`n ||` to achieve the newline-pipes. That big string is the output of the script block, which gets inserted automatically into the middle and output.

```
PS C:\Tools\Scripts\golfing> .\go-generate-some-java.ps1
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

```
> 5 votes

# Answer
# Pyth, ~~118~~ ~~106~~ 103 bytes

```
s[."
{Z-L¡JxÙÿ
LæÝ<í?¢µb'¥ÜA«Ç}h¹äÚÏß"\nb*4dj"\n  || "ms[." uøs|ÀiÝ"*d\0\L)U19\;b\}

```

Try it online!

All this string hardcoding really eats a lot of bytes up~~, but nothing I can do about it~~.

**Update:** Saved 3 bytes by using a packed string. Thanks @user81655 for the hint!
> 4 votes

# Answer
# C# (CSI) 181 180 179 byte

```
string i=" input == 1",e="public static bool";Console.Write(e+@"ean isPowerOfTen(long input) {
  return
   "+i+string.Join(@"L
  ||"+i,e.Select((_,x)=>new string('0',x)))+@"L;
}")

```

There is only one little trick involved. The straight forward way to write this would be:

```
string.Join("L\n  || input == 1",Enumerable.Range(0,18).Select(x=>new string('0',x)))

```

by using the string with the first 18 characters of the text which I need anyways I can get rid off the lengthy Enumerable.Range. This works because string implements IEnumerable and there is a version of Select that hands the item (not needed) and the index which we want to the lambda function.
> 4 votes

# Answer
# Javascript, ~~172~~ ~~157~~ ~~152~~ ~~150~~ 148 bytes

```
p=>`public static boolean isPowerOfTen(long input) {
  return${[...Array(19)].map((x,i)=>`
  ${i?'||':' '} input == 1${'0'.repeat(i)}L`).join``};
}`

```

```
f=p=>`public static boolean isPowerOfTen(long input) {
  return${[...Array(19)].map((x,i)=>`
  ${i?'||':' '} input == 1${'0'.repeat(i)}L`).join``};
}`

document.body.innerHTML = '<pre>' + f() + '</pre>'
```
> 3 votes

# Answer
# C, ~~158~~ 155 bytes

```
i;main(){for(puts("public static boolean isPowerOfTen(long input) {\n  return");i<19;)printf("  %s input == 1%0.*dL%s\n",i++?"||":" ",i,0,i<18?"":";\n}");}

```

Try it online here.
> 3 votes

# Answer
# Jelly, 75 bytes

(These are bytes in Jelly's custom codepage.)

```
0r18⁵*;@€⁶j“¢œḤḅg^NrÞḢ⁷ẉ»“⁵®UẆƓḃÐL⁴ṖịṛFþẈ¹9}¶ ƁḋȮ¦sẒẆd€Ḟɼ¿ỌṀP^µ\f@»;;“L;¶}”

```

Try it here.

### Explanation

```
0r18      Range [0..18]
⁵*        Take the 10^ of each number
;@€⁶      Prepend a space to each number
j“...»    Join by compressed string "L\n  || input =="
“...»;    Prepend compressed string "public static ... =="
;“L;¶}”   Append "L;\n}"

```
> 3 votes

# Answer
## ES6, ~~139~~ 138 bytes

```
document.write(`<pre>${(

_=>"0".repeat(19).replace(/./g,`
 || input == 1$\`L`).replace(`
 ||`,`public static boolean isPowerOfTen(long input) {
  return
  `)+`;
}`

)()}</pre>`);
```

I do so love these triangle generation questions. Note: Snippet includes header and footer, but these aren't included in the byte count.
> 3 votes

# Answer
# Vimscript, 120 bytes

Might as well use the right tool for the job.

This assumes that autoindent, etc have not been set. `^[` and `^M` are escape characters for the `ESC` and `CR` characters respectively.

The `a` macro duplicates the current line and adds a 0 to the copy. The `:norm` line generates all the boilerplate and the `indent == 1L` line, then uses `a` to create the others.

```
:let @a='yyp$i0^['
:norm ipublic static boolean isPowerOfTen(long input) {^M  return^M  || input == 1L^[18@a$a;^M}
:3s/||/ /

```

In case the trailing spaces the sample output had on two lines weren't typos, here's a 126 byte version that includes them.

```
:let @a='yyp/L^Mi0^['
:norm ipublic static boolean isPowerOfTen(long input) {^M  return ^M  || input == 1L^[18@a$a;^M}
:3s/||/ /

```
> 3 votes

# Answer
## Ruby, ~~125~~ 119 bytes

```
$><<'public static boolean isPowerOfTen(long input) {
  return
   '+(0..19).map{|i|" input == #{10**i}L"}*'
  ||'+';
}'

```

Thanks to manatwork for -6 bytes!
> 2 votes

# Answer
# jq, 123 characters

(121 characters code + 2 characters command line option.)

```
"public static boolean isPowerOfTen(long input) {
  return
   \([range(19)|" input == 1\("0"*.//"")L"]|join("
  ||"));
}"

```

Sample run:

```
bash-4.3$ jq -nr '"public static boolean isPowerOfTen(long input) {
>   return
>    \([range(19)|" input == 1\("0"*.//"")L"]|join("
>   ||"));
> }"'
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)
> 2 votes

# Answer
# Oracle SQL 9.2, 311 bytes

```
SELECT REPLACE(REPLACE('public static boolean isPowerOfTen(long input) {'||CHR(10)||'  return'||c||';'||'}', 'n  ||', 'n'||CHR(10)||'   '),CHR(10)||';', ';'||CHR(10)) FROM(SELECT LEVEL l,SYS_CONNECT_BY_PATH('input == '||TO_CHAR(POWER(10,LEVEL-1))||'L'||CHR(10),'  || ')c FROM DUAL CONNECT BY LEVEL<20)WHERE l=19

```
> 2 votes

# Answer
# Perl 5 - ~~130~~ 141

```
@s=map{'input == 1'.0 x$_."L\n  ||"}0..18;$s[$#s]=~s/\n  \|\|/;\n}/g;print"public static boolean isPowerOfTen(long input){\n  return\n    @s"

```

EDIT: fixed to have exact indentation
> 2 votes

# Answer
## Kotlin, ~~194~~ 193 characters

```
fun main(u:Array<String>){var o="public static boolean isPowerOfTen(long input) {\n\treturn"
var p:Long=1
for(k in 0..18){
o+="\n\t"
if(k>0)o+="||"
o+=" input == ${p}L"
p*=10
}
print("$o;\n}")}

```

Test it at http://try.kotlinlang.org/
> 2 votes

# Answer
## Python (3.5) ~~137~~ 136 bytes

```
print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == %rL"%10**i for i in range(19))+";\n}")

```

**Previous version**

```
print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == 1"+"0"*i+"L"for i in range(19))+";\n}")

```
> 1 votes

# Answer
# Javascript 175 bytes

Let's do this regularly

```
var s = "public static boolean isPowerOfTen(long input) {\n\treturn\n\t\tinput == 1";
for (var i = 1; i < 20; i++) {
    s += "\n\t|| input == 1";
    for (var j = 0; j < i; j++) {
        s += "0";
    }
    s += "L" ;
}
s += ";\n}";
alert(s);

```

Pretty small. Now, some javascript magic, like no semicolons needed, or no var's, etc.:

```
k="input == 1"
s="public static boolean isPowerOfTen(long input) {\n\treturn\n\t\t"+k+"L"
for(i=1;i<20;i++){s+="\n\t|| "+k
for(j=0;j<i;j++)s+="0";s+="L"}s+=";\n}"
alert(s)

```
> 1 votes

# Answer
## T-SQL ~~289~~, ~~277~~, ~~250~~, 249 bytes

```
SELECT'public static boolean isPowerOfTen(long input){return '+STUFF((SELECT'||input=='+N+'L 'FROM(SELECT TOP 19 FORMAT(POWER(10.0,ROW_NUMBER()OVER(ORDER BY id)),'F0')N FROM syscolumns)A FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'),1,2,'')+';}'

```

**Update:** Thanks @Bridge, I found a few more spaces too :)

**Update2:** Changed CTE to subquery -27 chars :) **Update3:** Another space bites the dust @bridge :)
> 0 votes

# Answer
## Java, 210 / 166

Score is depending on whether returning the input from a function meets the definition of 'output'.

Console output (210):

```
class A{public static void main(String[]z){String a=" input == 1",t="L\n  ||"+a,s="public static boolean isPowerOfTen(long input) {\n  return\n   "+a;for(int i=0;++i<19;)s+=t+="0";System.out.print(s+"L;\n}");}}

```

String return (166):

```
String a(){String a=" input == 1",t="L\n  ||"+a,s="public static boolean isPowerOfTen(long input) {\n  return\n   "+a;for(int i=0;++i<19;)s+=t+="0";return s+"L;\n}";}

```

Legible version:

```
String a() {
    String a=" input == 1", t = "L\n  ||"+a,
        s = "public static boolean isPowerOfTen(long input) {\n  return\n   "+a;
    for (int i = 0; ++i < 19;)
        s += t += "0";
    return s + "L;\n}";
}

```
> 0 votes

# Answer
# ANSI-SQL, 252 characters

```
WITH t as(SELECT '   'x,1 c,1 l UNION SELECT'  ||',c*10,l+1 FROM t WHERE l<19)SELECT 'public static boolean isPowerOfTen(long input) {'UNION ALL SELECT'  return 'UNION ALL SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19)FROM t UNION ALL SELECT'}   ';

```

Ungolfed:

```
WITH t as (SELECT '   ' x,1 c,1 l UNION
           SELECT '  ||',c*10,l+1 FROM t WHERE l<19)
SELECT 'public static boolean isPowerOfTen(long input) {' UNION ALL
SELECT '  return ' UNION ALL
SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19) FROM t UNION ALL
SELECT '}   ';

```

Not a serious attempt, just poking at the Oracle SQL/T-SQL entries.
> 0 votes

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

```
s="public static boolean isPowerOfTen(long input) {\n  return "
for(i=1;i<1e19;i*=10)s+="\n  "+(i-1?"||":" ")+" input == "+i+"L"
console.log(s+";\n}   \n")

```

The `i-1` will only be 0 (and thus falsey) on the very first round (it's just slightly shorter than `i!=1`.

Suggestions welcome!
> 0 votes

# Answer
## Perl 5, 137 bytes

Not based on the previous Perl answer, but it is somehow shorter. I believe it can be shortened down again by taking care of the first "input" inside the loop, but I didn't try anything yet (at work atm)

```
$i="input";for(1..18){$b.="  || $i == 1"."0"x$_."L;\n"}print"public static boolean isPowerOfTen(long $i) {\n  return\n    $i == 1L;\n$b}"

```
> 0 votes

# Answer
# CJam, 112 chars

```
"public static boolean isPowerOfTen(long input) {
  return
    input == 1"19,"0"a19*.*"L
  || input == 1"*"L;
}"

```
> 0 votes

# Answer
## Batch, ~~230~~ ~~208~~ ~~206~~ 205 bytes

```
@echo off
echo public static boolean isPowerOfTen(long input) {
echo   return
set m=input == 1
echo    %m%L
for /l %%a in (1,1,17)do call:a
call:a ;
echo }
exit/b
:a
set m=%m%0
echo  ^|^| %m%L%1

```

Edit: Saved 22 bytes by avoiding repeating `input ==` and reusing the subroutine for the line with the extra semicolon. Saved ~~2~~ 3 bytes by removing unnecessary spaces.
> 0 votes

# Answer
## AWK+shell, 157 bytes

```
echo 18|awk '{s="input == 1";printf"public static boolean isPowerOfTen(long input) {\n return\n    "s"L";for(;I<$1;I++)printf"\n  ||%sL",s=s"0";print";\n}"}'

```

The question did say to count everything you would have to type. This does have the added bonus of being able to select how many lines would be placed in the isPowersOfTen method when the boss inevitably changes his mind.
> 0 votes

# Answer
# R, 185 bytes

### Golfed

```
options(scipen=999);p=paste;cat(p("public static boolean isPowerOfTen(long input) {"," return",p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),"}",sep="\n"))

```

### Ungolfed

```
options(scipen=999)
p=paste
cat(
  p("public static boolean isPowerOfTen(long input) {",
        " return",
        p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),
        "}",
        sep="\n")
)

```
> 0 votes

# Answer
# Perl 6 (115 bytes)

```
say "public static boolean isPowerOfTen(long input) \{
  return
   {join "L
  ||",(" input == "X~(10 X**^19))}L;
}"

```

`X` operator does list cartesian product operation, for example `10 X** ^19` gives powers of ten (from 10 to the power of 0 to 19, as `^` is a range operator that counts from 0). Strings can have code blocks with `{` (which is why I escape the first instance of it).
> 0 votes

# Answer
# Zsh, 125 bytes

```
P="public static boolean isPowerOfTen(long input) {
  return
   ${1= input == 1}L"
repeat 18 {1+=0;P+="
  ||$1L";}
<<<$P";
}"

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 71 bytes

```
18Ý°'L«“  ||î® == “ì”„‡€‚—¿”á
“‚Æ£‹ÒŒ€ˆÿ(ƒÈî®) {
 „Á“š»…;
}«„( ¬:„||ð.;

```

Try it online.

**Explanation:**

```
18Ý                      # Push a list in the range [0,18]
   °                     # Take 10^n of each value in this list
    'L«                 '# Append an "L" to each integer
       “  ||î® == “ì     # Prepend dictionary string "  || input == " to each
”„‡€‚—¿”                 # Push dictionary string "Power Of One"
        á                # Only keep the letters / remove the spaces: "PowerOfOne"
“‚Æ£‹ÒŒ€ˆÿ(ƒÈî®) {\n „Á“ # Push dictionary string "public static boolean isÿ( long input) {\n  return",
                         # were the `ÿ` is automatically filled with the "PowerOfOne" string
    š                    # Prepend it in front of the earlier list
     »                   # Join the list by newlines
…;\n}«                   # Append ";\n}" at the end
„(                       # Push string "( "
   ¬                     # Push its first character (without popping): "("
    :                    # Replace the "( " with "("
„||ð.;                   # Replace the first "||" with " "
                         # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“ ||î® == “` is `" || input == "`; `”„‡€‚—¿”` is `Power Of One`; and `“‚Æ£‹ÒŒ€ˆÿ(ƒÈî®) {\n „Á“` is `"public static boolean isÿ( long input) {\n return"`.
> 0 votes

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


title: ASCII-Art Venn Diagram

text:
# Question
Title: ASCII-Art Venn Diagram
Given two lists that contain no duplicate elements `a` and `b`, find the crossover between the two lists and output an ASCII-Art Venn Diagram. The Venn Diagram will use a squarified version of the traditional circles for simplicity.

# Example

**Given:**

```
a = [1, 11, 'Fox', 'Bear', 333, 'Bee']
b = ['1', 333, 'Bee', 'SchwiftyFive', 4]

```

**Output (Order is 100% arbitrary, as long as the Venn Diagram is correct):**

```
+-----+----+-------------+
|11   |333 |SchwiftyFive |
|Fox  |Bee |4            |
|Bear |1   |             |
+-----+----+-------------+

```

The program may either consider `'1' == 1` or `'1' != 1`, up to your implementation. You may also choose to just handle everything as strings, and only accept string input.

---

**Given:**

```
a=[]
b=[1,2,3]

```

**Output (Notice how the two empty parts still have the right-pad space):**

```
+-+-+--+
| | |1 |
| | |2 |
| | |3 |
+-+-+--+

```

---

**Given:**

```
a=[1]
b=[1]

```

**Output:**

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

```

# Rules

* Elements of the Venn Diagram are left-aligned and padded to the max length entry plus 1.
* The ordering of the elements within sub-sections of the Venn-Diagram are arbitrary.
* Corners of the Venn Diagram (where `|` meets `-`) must be represented by a `+`.
* You are garuanteed that `a.join(b).length() > 0`, if both are empty, you may do whatever.
    + You may even print a picture of Abe Lincoln, don't care.
* This is , and .

# Bonus

Charcoal renders boxes like this naturally, but the whole set theory part... Don't know how well it does that. +100 bounty for the shortest charcoal submission before I am able to add a bounty to the question (2 days from being asked).

# Answer
# Husk, <sup>~~72~~</sup> 58 bytes

```
mṙ1₁Fz+m(₁TT' Ṡ:→S:öR'-→▲mL)TTømėF`-FnF-
Ṡz:(`:'+:'+R'|-2L

```

Try it online!

Husk does not support arrays of multiple types, so the arguments must be string arrays.

I am not sure whether I want to explain this monstrosity.

Due to it's sheer size, it takes about 28 secs(due to type inference) for the first test case mentioned. Without some of the type inference issues, this could be a lot shorter.

-14 bytes with a lot of adjustments(I got better at Husk).
> 5 votes

# Answer
# Charcoal, ~~106~~ ~~89~~ 87 bytes:

```
Ａ⟦⟧ςＡ⟦⟧λＡ⟦⟧ρＡ⟦⟧τＷＳ⊞ςιＷＳ⊞⎇№ςιτριＦς⊞⎇№τι⟦⟧λιＦ⟦λτρ⟧«Ｆι«↓Ｐκ»ＭＬι↑←Ａ⁺⌈ＥιＬκ³ζＵＲζ⁺⌈⟦ＬλＬτＬρ⟧²Ｍζ→

```

Try it online! Note that link is to verbose code for explanatory purposes, with the `-sl` option that shows the equivalent native Charcoal code. Takes input as newline-separated strings with a blank line after each set.

Edit: Saved 11 bytes thanks to @ASCII-only. Previous version actually had a bug when the last word in the first set was not in the second set and also the first column was the tallest, which manifested as an apparently inability to optimise away a temporary. Saved 2 bytes by optimising two Move commands (the deverbosifier now does this automatically but the resulting code was always valid so the answer is still competing).

Edit: I don't think `Multiprint` used to work with multiline output but it does currently and making use of that would save 6 bytes, plus a further 4 bytes because current Charcoal preinitialises the `u` variable to the empty list: Try it online!
> 3 votes

# Answer
# Python 2, ~~221~~ ~~210~~ 212 bytes

```
m=map
A,B=m(set,input())
d=A-B,B&A,B-A
e=[max(m(len,s))+1for s in d]
p,i,n='+|\n'
o=b=p+p.join(m('-'.__mul__,e))+p+n
while sum(m(len,d)):o+=i+i.join(m(str.ljust,[len(s)and s.pop()or''for s in d],e))+i+n
print o+b

```

Try it online!
> 2 votes

# Answer
# PHP\>=7.1, 287 Bytes

```
<?for([$a,$b]=$_GET,$x=max(($m=array_map)(count,$r=[($d=array_diff)($a,$b),array_intersect($a,$b),$d($b,$a)]));$n<3;$n++)for(sort($r[+$n]),$i=-1;$i<=$x;$i++){$o[$i].="|+"[$b=$i<0||$i==$x].str_pad($b?"":$r[+$n][$i],max($m(strlen,$r[+$n]))+1," -"[$b]).("|+"[$b][$n<2]);}echo join("
",$o);

```

Online Version

Expanded

```
for([$a,$b]=$_GET, # store input arrays in shorter variables
$x=max(($m=array_map)(count,   # get maximum of
$r=[($d=array_diff)($a,$b),array_intersect($a,$b),$d($b,$a)])); #the set array
$n<3;$n++)
  for(sort($r[+$n]),$i=-1;$i<=$x;$i++){ # sort array to remove keys
    $o[$i].="|+"[$b=$i<0||$i==$x].   # concat line $b boolean for first and last line beginning char
    str_pad($b?"":$r[+$n][$i]   # string of item in array if not first or last line
    ,max($m(strlen,$r[+$n]))+1  # fill till maximum length of items in array
    ," -"[$b]) # with char depends on first/last line or item line
    .("|+"[$b][$n<2]); # make end of string if last array is reach
}
echo join("
",$o); #Output

```
> 2 votes

# Answer
# 05AB1E, 47 bytes

```
ʒå}©K®¹®Kr)õζ'|ìøε€SζøJ}ø'|δªðý¬„|+`:D¬мS'-:.ø»

```

Try it online or verify all test cases.

**Explanation:**

```
ʒ               # Filter the first (implicit) input-list by:
 å              #  Check if the current item is in the second (implicit) input-list
}©              # After the filter: store this overlap in variable `®` (without popping)
  K             # Pop and remove those items from the second (implicit) input-list
®               # Push overlap `®`
¹               # Push the first input-list again
 ®K             # Remove overlap `®`
r               # Reverse the three lists on the stack
 )              # And wrap them into a list
 ζ              # Zip/transpose this list, swapping rows/columns,
õ               # with "" as filler if the lists are of unequal length
  '|ì          '# Prepend an "|" in front of each inner string
ø               # Zip/transpose back, swapping rows/columns
 ε              # Map over each row:
  €             #  Map over each string in this row:
   S            #   Convert it to a list of characters
    ζ           #  Zip/transpose, swapping rows/columns, with " " as default filler
     ø          #  And then zip/transpose back
      J         #  And join the strings back together
 }ø             # After the map: zip/transpose back
  δ             # Map over each row:
'| ª           '#  And append an "|" to it
    ðý          # Then join each inner-most list by spaces
¬               # Push the first row (without popping the list)
 „|+`:          # Replace all "|" with "+"
      D         # Duplicate this string
       ¬        # Push its first characters (without popping), which is a "+"
        м       # Remove all "+" from the duplicated string
         S      # Convert what remains to a list of characters
          '-:  '# Replace each character (except for "+") with "-"
             .ø # Surround the list of rows with this string as leading/trailing items
»               # And finally join the list by newlines
                # (after which the result is output implicitly)

```
> 1 votes

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