title: What's my lucky factor?

text:
# Question
Title: What's my lucky factor?
Lucky numbers (A000959) are numbers generated by applying the following sieve:

Begin with the list of natural numbers:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ...

```

Now, remove every second element (\\$n = 2\\$, the smallest element in the list aside from 1):

```
1,    3,    5,    7,    9,     11,     13,     15,     17,     19,     21,     23,     25, ...

```

Now, remove every third element (\\$n = 3\\$, the next remaining element after 2):

```
1,    3,          7,    9,             13,     15,             19,     21,             25, ...

```

Now, remove every seventh element (\\$n = 7\\$, the next remaining element after 3):

```
1,    3,          7,    9,             13,     15,                     21,             25, ...

```

Then continue removing the \\$n\\$th remaining numbers, where \\$n\\$ is the next number in the list after the last surviving number. Next in this example is 9, then 13 and so on.

Eventually, this converges to the lucky numbers:

```
1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99, ...

```

---

However, we've already looked at the lucky numbers. Today, we'll be looking at a related sequence: the lucky factors (A264940). These are the values of \\$n\\$ that remove a specific integer \\$x\\$.

For example, \\$x = 2\\$ is removed when \\$n = 2\\$, so \\$2\\$'s lucky factor is \\$2\\$
Additionally, \\$x = 19\\$ is removed when \\$n = 7\\$, so \\$19\\$'s lucky factor is \\$7\\$

If \\$x\\$ is lucky, its lucky factor is \\$0\\$.

The first 50 elements of this sequence are

```
0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 0, 2, 3, 2, 7, 2, 0, 2, 3, 2, 0, 2, 9, 2, 3, 2, 0, 2, 0, 2, 3, 2, 0, 2, 7, 2, 3, 2, 0, 2, 13, 2, 3, 2, 0, 2

```

---

This is a standard challenge. You may choose to:

* Take a positive integer \\$x\\$ and output the lucky factor of \\$x\\$
* Take a positive integer \\$x\\$ and output the lucky factors of each integer \\$1 \le i \le x\\$
* Output the infinite list of lucky factors

This is so the shortest code in bytes wins

---

## Test cases

```
 x  n
15  0
57  9
26  2
41  3
50  2
13  0
48  2
20  2
19  7
22  2
24  2
27  9
60  2
54  2
49  0
 2  2
 7  0
45 13
55 15

```

# Answer
# Python 2, 72 bytes

Takes a positive integer \\$ x \\$ and outputs the lucky factor of \\$ x \\$. Outputs via exit code.

```
x=input()
R=range(1,x+1)
for i in R:i+=i<2;del R[i-1::i];x>R[-1]<exit(i)

```

Try it online!
> 10 votes

# Answer
# , ~~75~~ ~~73~~ ~~71~~ 63 bytes

```
x=scan();a=b=1:x;while(x%in%a)a=a[-b*(T=c(a,0)[F<-F+1]+!T-1)];T

```

Try it online!

Returns the \\$n\\$-th lucky factor.

Thanks for -2 bytes to Giuseppe and -8 bytes to Dominic van Essen.
> 7 votes

# Answer
# Jelly, ~~33~~ 27 bytes

```
2ịŻ‘ɼ»2$‘¤ị,ḟm¥@¥ƊƲƬṪċ¥Ðḟ⁸Ḣ

```

Try it online!

A full program taking an integer as its argument and printing an integer. Could almost be used as a monadic link, but the register needs to be reset to zero before each call. The TIO link has a footer that runs all of the test cases.
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~73~~ 67 bytes

```
i=1
f@n_:=0Module[{k=++i},f@_/;n∣k++=n]
Print@f@Max[,2]~Do~{,∞}

```

Try it online!

Prints lucky factors indefinitely.

`f` is designed to be called on consecutive natural numbers, starting with `2,2,3,4...`.

Initially there is only one rule defined for `f`, a generic definition which is called only when `n` is lucky. It returns 0, and adds a new, more specific definition: a sieve which returns `n` every `n`th it's called.

Mathematica tries more specific definitions before more general ones. When rules have the same generality (as will be generated by the lucky numbers), they're tried in order of definition. Thus a sieve is only attempted if earlier ones did not filter that number.

---

### ~~69~~ ~~67~~ 69 bytes

```
Array[Clear@f;f[i=1]=f@2;f@n_:=0Module[{k=++i},f@_/;n∣k++:=n];f,#]&

```

Try it online!

Function which returns the lucky factors of `1..x`.
> 4 votes

# Answer
# Python 2, 143 bytes

```
def f(x):
	m=1;n=range(1,x+1)
	while x in n and max(n)>m:m=min(q for q in n if q>m);n=[q for i,q in enumerate(n)if-~i%m]
	print 1-(x in n)and m

```

Try it online!

a very unintelligent and trivial implementation of this
> 3 votes

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

```
f=lambda n,k=2:n>=k and(f(n+n//k*~-t,k+1)if(t:=k>2<=f(k))+n%k else k)

```

Try it online!

Direct recursion. Returns the lucky factor of `x`, using `False` instead of `0`.
> 3 votes

# Answer
# Java (JDK), 107 bytes

```
x->{int s[]=new int[x+1],i=1,j,c;for(;++i<x;)for(c=j=s[i]<1?0:x;j++<x;)s[j]+=s[j]<1&&++c%i<1?i:0;return s;}

```

Try it online!

* This outputs the lucky factors of each integer \\$1 \le i \le x\\$ in a 0-indexed array, but the mapping basically stays `result[x] = factor` (plus has `result[0] = 0`, which shouldn't be taken into consideration).

### Explanation

This answer basically counts the number of zeroes, and every "lucky"-th zero is changed into the current lucky factor.
> 3 votes

# Answer
# 05AB1E, 37 bytes

```
L∞IFD®LKн©ôD€θI£®‚ˆ€¨˜}I£ILå≠÷¯vy`¸Þ‡

```

It's slow, ugly, and long, but it works.. :/ I might try to revisit this one from scratch later on.

Given an input \\$n\\$, outputs the first \\$n\\$ values.

Try it online.

**Explanation:**

```
L                   # Push a list in the range [1, (implicit) input]
 ∞                  # Push an infinite positive list: [1,2,3,...]
  IF                # Loop the input amount of times:
    D               #  Duplicate the infinite list
     ®L             #  Push a list in the range [1,`®`]
                    #  (`®` is -1 by default, so the first iteration is [1,0,-1])
       K            #  Remove these values from the duplicated infinite list
        н           #  Pop and only leave the first (smallest) value
                    #  (this is basically the smallest value above `®` (and 1))
         ©          #  Store it as new `®` (without popping)
          ô         #  Split the infinite list into parts of that size
           D        #  Duplicate this list of parts
            €θ      #  Only leave the last value of each part
              I£    #  Only keep the first input amount of values of this infinite list
                ®‚  #  Pair it with `®`
                  ˆ #  And pop and add it to the global array
            €¨      #  Remove the last value from each part
              ˜     #  And flatten the list
   }I£              # After the loop: only leave the first input amount of values
      IL            # Push a list in the range [1,input]
        å≠          # Check for each that it's NOT in this list
          ÷         # Integer-divide the initial [1,input] list by these 0s/1s,
                    # where division-by-0 results in 0
                    # (this basically mapped all Lucky numbers to 0s)
    ¯               # Push the global array
     vy             # Loop over each pair `y`:
       `            #  Pop and push the list and integer separated to the stack
        ¸Þ          #  Create an infinite list only containing this integer
          ‡         #  Transliterate all values in the list to the integer in our list
                    # (after which the list is output implicitly as result)

```
> 3 votes

# Answer
# Dart, 151 143 138 bytes

```
f(x)=>([n,c,i,s]){for(s=[for(;i<x;)++i];n<s.last;i=s.length)for(n=s[c];i>0;c=s[i]>n?i:c)if(i--%n<1&&s.removeAt(i)==x)return n;}(0,1,0)??0;

```

Try it online!

Takes a positive integer `x` and output the lucky factor of `x`. I tried to reduce this as much as possible since Dart is a little verbose and that's the best I could come with.

Ungolfed:

```
int f(int x) {
  int c = 1;
  var s = [for(int i = 1; i <= x; i++) i];
  for (int n = 0; n < s.last;) {
    n = s[c];
    for (int i = s.length; i > 0; --i) {
      if ((i + 1) % n == 0) {
        if (s.removeAt(i) == x)
          return n;
      }
      if (s[i] > n) c = i;
    }
  }
  return 0;
}

```
> 2 votes

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


title: Count my Pluses

text:
# Question
Title: Count my Pluses
Your task is, to count how many pluses I have.

## What Pluses?

* The no plus: 0 Points

```
-

```
* The naïve Plus: 1 Point

```
+

```
* The double Plus: 2 Points

```
 +
+++
 +

```
* The mega double plus: 3 Points

```
    +
   +++
    +
 +  +  +
+++++++++
 +  +  +
    +
   +++
    +

```

Pluses of higher order than 3 must be ignored.

## Rules

* Input will only consist of two characters - and +, and it will always be rectangular.
* Input can be a string, an array or a binary matrix (then + is 1 and - is 0).
* Output must be the sum of all detected pluses (trailing newline/ whitespace allowed).
* Pluses can overlap (see Examples below)
* Default I/O rules apply
* Default Loop holes apply

## Examples

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

```

Out: 4

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

```

Out: 9 (7 naïve pluses and 1 double plus)

```
++++++
++++++
++++++
++++++

```

Out: 40 (24 naïve pluses and 8 double pluses)

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

```

Out: 49 (36 naïve pluses, 5 double pluses and 1 mega double plus)

```
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++

```

Out: 208 (90 naïve pluses, 56 double pluses and 2 mega double plus)

# Answer
# MATL, ~~29~~ ~~28~~ 24 bytes

```
z2Y6ttX*,GbZ+5Mz=z]yytvs

```

Input is a binary matrix with `1` for `'+'` and `0` for `'-'`.

Try it online! Or verify all test cases.

### Explanation

> Convolution is the key to success

```
z       % Implicit input. Number of nonzeros. This is the number of naive pluses
2Y6     % Push [0 1 0; 1 1 1; 0 1 0] (predefined literal): pattern of double plus
ttX*    % Duplicate twice. Kronecker product: pattern of mega-double plus
,       % Do twice
  G     %   Push input again
  b     %   Bubble up third-topmost entry in the stack. This moves either the
        %   double of mega-double pattern to top
  Z+    %   2D convolution, maintaining size
  5M    %   Push the last input to the last function again: the pattern
  z     %   Number of nonzeros. This gives 5 or 25 for double or mega-double
  =     %   Equal? Element-wise. This detects if the result of the convolution
        %   equals the number of ones in the pattern, which implies that the
        %   pattern has been found
  z     %   Number of nonzeros. This is how many times the pattern has been found
]       % End
yyt     % Duplicate the top two elements, then the top element. This effectively
        % gives weight 2 and 3 to double and mega-double pluses
vs      % Concatenate all stack contents. Sum. Implicit display

```
> 16 votes

# Answer
# JavaScript (ES6),  ~~146 ... 140~~  137 bytes

Expects a binary matrix.

```
m=>m.map((r,y)=>r.map((c,x)=>t+=c+=(g=(X,k=6)=>k>>8||(m[y+Y+k%5%3]||0)[x-X+k%27%4]&g(X,k+46))(Y=0)&&2+3*g(Y=3)*g(-3)*g``*g(0,Y=6)),t=0)|t

```

Try it online!

## How?

### Helper function

The helper function \\$g\\$ tests whether there's a 'Double Plus' inside the \\$3\times3\\$ submatrix whose top-left corner is located at position \\$(x-X,y+Y)\\$.

We start with \\$k=6\\$ and add \\$46\\$ to \\$k\\$ after each iteration. The relative coordinates in the submatrix are given by:

$$\begin{align}&dx=(k\bmod 27)\bmod 4\\ &dy=(k\bmod 5)\bmod 3\end{align}$$

```
  k | k%27 | dx=k%27%4 | k%5 | dy=k%5%3 | (dx, dy)          | 0 1 2
----+------+-----------+-----+----------+--------------  ---+-------
  6 |   6  |     2     |  1  |     1    | (+2, +1) (A)    0 | - C -
 52 |  25  |     1     |  2  |     2    | (+1, +2) (B)    1 | E D A
 98 |  17  |     1     |  3  |     0    | (+1, +0) (C)    2 | - B -
144 |   9  |     1     |  4  |     1    | (+1, +1) (D)
190 |   1  |     1     |  0  |     0    | (+1, +0) (C)
236 |  20  |     0     |  1  |     1    | (+0, +1) (E)

```

The cell at \\$(+1, +0)\\$ is tested twice, which is not an issue.

The next value of \\$k\\$ is \\$282\\$ which triggers the test `k >> 8` and stops the recursion.

```
g = (X, k = 6) =>    // g is a recursive function taking X and a counter k
  k >> 8 || (        //   if k = 282, stop the recursion and return 1
    ( m[ y + Y +     //   otherwise, test the cell located at
         k % 5 % 3 ] //   row y + Y + ((k mod 5) mod 3)
      || 0           //
    )[ x - X +       //   and column x - X + ((k mod 27) mod 4)
       k % 27 % 4 ]  //
  )                  //
  & g(X, k + 46)     //   do a recursive call with k + 46

```

### Main function

**NB**: Among many different possible choices, the initial value of \\$k\\$ in \\$g\\$ was forced to \\$6\\$ so that it allows us to do `g(0, Y = 6)` in the main function without breaking anything.

```
m =>                 // m[] = input matrix
m.map((r, y) =>      // for each row r[] at position y in m[]:
  r.map((c, x) =>    //   for each cell c at position x in r[]:
    t +=             //     add to t:
    c +=             //       1 point if c = 1
      g(Y = 0) && 2  //       2 points if there's a Double Plus at (x, y)
      + 3 *          //       3 points if there are also Double Pluses at:
      g(Y = 3) *     //         (x - 3, y + 3)
      g(-3) *        //         (x + 3, y + 3)
      g`` *          //         (x, y + 3)
      g(0, Y = 6)    //         (x, y + 6)
  ),                 //   end of inner map()
  t = 0              //   start with t = 0
) | t                // end of outer map(); return t

```
> 9 votes

# Answer
# Jelly, 33 bytes

```
×3\€ḊṖ
ZÇZaÇḤ
ÇJ%3ZƙƲ⁺€Ç€€a3,,ÇFS

```

Try it online!

:/

I want to say this is very golfable, but the entire approach is probably not the ideal one. Now agrees with Luis Mendo's MATL solution on a test case I made up, and at the cost of only one byte so that's cool I guess

```
×3\€ḊṖ    Helper link 1: detect centers of +++
   €      For each row,
 3\       reduce over overlapping windows of length 3:
×         multiply.
    ḊṖ    Remove the first and last rows.

ZÇZaÇḤ    Helper link 2: detect double plus centers
   aÇ     Keep the horizontal (centers of) +++es which align with
ZÇZ       the vertical (centers of) +++es,
     Ḥ    and double.

ÇJ%3ZƙƲ⁺€Ç€€a3,,ÇFS    Main link: sum each tier of plus
Ç                      Get the matrix of double plus centers.
     ƙƲ                Group rows by
 J%3                   their indices mod 3
    Z                  and transpose each group;
       ⁺€              do it again to each group.
          €€           For each group in each group,
         Ç             detect the double plus pattern,
            a3         and replace the 16s with 3s.
              ,        Pair the result with the input,
               ,Ç      pair that pair with the double pluses,
                 FS    then flatten that all and return the sum.

```
> 8 votes

# Answer
# , 141 bytes

```
function(m)sum(m,a<-f(m,n<-nrow(m))*2,f(a,n,3)*3,na.rm=T)
f=function(m,n,k=1)sapply(n*k+seq(!m),function(i)all(i%%n>1,m[i+k*c(0,1,-1,n,-n)]))

```

Try it online!

This can probably be improved by a lot.

The helper function `f` scans the matrix. For each cell, it counts 1 iff the cell and the cells at distance `k` in each of the 4 directions are all worth 1. For `k=1`, this corresponds to checking the 4 neighbours, and creates `a` which encodes the centres of the double pluses. We then run `f` on `a` with `k=3` to find the triple pluses. The entries near the edges end up as `NA`; they are ignored thanks to `na.rm=T`.
> 8 votes

# Answer
# , 80 69 60 bytes

```
[:+/@,[,2 3*((;[:,./^:2#"{~)#:2 7 2)4 :'y(x-:x&*);._3~$x'&><

```

Try it online!

-9 thanks to xash
> 6 votes

# Answer
# Python 3.8 (pre-release), ~~150 149~~ 145 bytes

```
lambda a:len(x("\+",a)+2*x((d:="\+(?="+(s:="\W"*~-a.find("\n"))+3*"\+"+s+"\+)..")[:-2],a)+3*x(d+f"(?={3*s+3*d+3*s+d})",a))
import re
x=re.findall

```

Try it online!

Input is a multiline string

Thanks to @Tipping Octopus for -1 byte Thanks to @Neil for -4 bytes

## Ungolfed version

```
import re
def f(a):
  s="\W"*(a.find("\n") - 1)
  d=f"\+(?={s}\+\+\+{s}\+).."

  return len(re.findall("\+", a) +
             2 * re.findall(d[:-2], a) +
             3 * re.findall(d + f"(?={3*s + 3*d + 3*s + d})", a)
            )

```

Try it online!

## How it works :

I created a regex that can detect double plusses and mega-double-pluses

* `s="\W"*~-a.find("\n")` stock in `s` the string `\W\W...\W` whose length is equal to the number of character of a line minus 1. (`\W` matches any non-word character including `\n`)
* `d=f"\+(?={s}\+\+\+{s}\+).."` is the pattern for double plus (+ `..` wich will be removed on the double plus check)
* `re.findall(<pattern>, a)` returns a list containing all the matches of pattern.
* `len(re.findall()+2*re.findall()+3*re.findall()` concatenate theses lists and return the length
> 5 votes

# Answer
# Charcoal, 71 bytes

```
ＷＳ⊞υιυＦＬυＦＬθ«Ｊκι¿⁼⁷ＬΦ⪫ＫＶＫＫΣλ3»ＦＬυＦＬθ«Ｊκι¿∧⁼3ＫＫ⬤urdl‹1⊟ＫＤ⁴✳λ6»≔Σ⪫ＫＡωθ⎚Ｉθ

```

Try it online! Link is to verbose version of code. Takes input as a binary matrix of newline-terminated strings. Explanation:

```
ＷＳ⊞υιυ

```

Read in the matrix and print it to the canvas.

```
ＦＬυＦＬθ«Ｊκι

```

Loop over all of the cells.

```
¿⁼⁷ＬΦ⪫ＫＶＫＫΣλ3»

```

If this cell and all of its neighbours are `1`s or `3`s then change this cell to a `3`.

```
ＦＬυＦＬθ«Ｊκι

```

Loop over all of the cells again.

```
¿∧⁼3ＫＫ⬤urdl‹1⊟ＫＤ⁴✳λ6»

```

If this cell is a `3` and all of the cells 3 away in all four orthogonal directions are greater than `1` then change this cell to a `6`.

```
≔Σ⪫ＫＡωθ⎚Ｉθ

```

Take the sum of the grid, clear the canvas, and output the sum in decimal.
> 5 votes

# Answer
# Ruby, 135 bytes

```
->a{i=0;[1,186,0x101c04125ff490407010].sum{|s|a.each_cons(y=3**i).sum{|w|w.transpose.each_cons(y).count{|z|z.join.to_i(2)&s==s}}*i+=1}}

```

Try it online!
> 4 votes

# Answer
# Jelly, 37 bytes

```
Zœs3Ɗ⁺€aZ$2ịP))
3*³ṡZ€ṡ€ɗÇ⁸¡
3’Ç×Ɗ€FS

```

Try it online!

A full program taking a Boolean matrix as its argument and printing the number of pluses. This is extensible to higher degrees of plus by changing the 3 at the beginning of the last line to a higher number. For example, here is a version that goes up to mega-mega-mega double pluses in a matrix of 82x82 1s.
> 4 votes

# Answer
# JavaScript (ES2020), 136 bytes

```
m=>m.map((r,y)=>r.map((c,x)=>t+=(d=X=>D=Y=>e+2?m[Y+e--%3%2]?.[X+e%2]*D(Y):e=3)(x)(y,e=3)?D(y-3)*D(y+3)*d(x-3)(y)*d(x+3)(y)?6:3:c),t=0)|t

```

```
f=

m=>m.map((r,y)=>r.map((c,x)=>t+=(d=X=>D=Y=>e+2?m[Y+e--%3%2]?.[X+e%2]*D(Y):e=3)(x)(y,e=3)?D(y-3)*D(y+3)*d(x-3)(y)*d(x+3)(y)?6:3:c),t=0)|t

testcases = `
-+-
+-+
+--

-+-
+++
+++

++++++
++++++
++++++
++++++

----+-----
+--+++----
----++----
-+--+--++-
+++++++++-
-+--+--++-
----+-+---
---+++----
+---++++++

++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
`.trim().split('\n\n').map(s => s.split('\n').map(r => [...r].map(c => c === '+' ? 1 : 0)));

testcases.forEach(t => { console.log(f(t)); });
```

```
m=> // input 0-1 [m]atrix
m.map((r,y)=> // for each [y]-th [r]ow
r.map((c,x)=> // for each [x]-th [c]eil
t+= // [t]otal points add...
(d=X=> // Check if [d]ouble plus exist on [X], [Y]
D=Y=>e+2?         // for [e]ach 3, 2, 1,  0, -1
m[Y+e--%3%2]?.    //         Y+ 0, 0, 1,  0, -1
[X+e%2]           //         X+ 0, 1, 0, -1,  0
                  // check if certain position is a plus sign
*D(Y,e)           // return 0 or NaN as falsy
:e=3              // return 3 as truthy
)
(x)(y,e=3)? // Is [x][y] a double plus?
D(y-3)*D(y+3)*d(x-3)(y)*d(x+3)(y)? // Is [x][y] a double double plus?
6:3:c // assign different points
),
t=0 // initial [t]otal points to 0
)|t // return total points

```
> 3 votes

# Answer
# Perl 5 (`-00p`), 125 bytes

```
/(....)?(..)?(.)
/;($a,$:,$;,$,)=map"."x$_,@-;/(1$,111$,1)(?{$x+=2})($;(1..1..1)$:1{9}$:(?3)$;(?1)(?{$x+=3}))?^/s;$_=y/1//+$x

```

Try it online!

Using `1` instead of `+` and using regex to match pluses.

Or 124 bytes using `}{` at the end trick

```
/(....)?(..)?(.)
/;($a,$:,$;,$,)=map"."x$_,@-;$\=y/1//;/(1$,111$,1)(?{$\+=2})($;(1..1..1)$:1{9}$:(?3)$;(?1)(?{$\+=3}))?^/s}{

```

Try it online!
> 1 votes

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


title: Write a domino effect

text:
# Question
Title: Write a domino effect
Using the fewest Unicode characters, write a function that accepts three parameters:

* Total number of dominoes
* `n`th affected domino
* Topple direction of the affected domino (`0` or `L` for left, `1` or `R` for right)

Once a domino is toppled, it must also topple the remaining dominoes in the same direction.

You should output the dominoes with `|` representing a standing domino and `\` and `/` representing a domino toppled to the left and right respectively.

## Examples

`10, 5, 1` should return `||||//////`
`6, 3, 0` should return `\\\|||`

# Answer
> 14 votes
## Ruby, 38 (46) characters

```
e=->n,k,r{k-=r;'\|'[r]*k+'|/'[r]*n-=k}

```

This function takes the direction as an integer (`1` for right, `0` for left). A function that takes a string is 8 characters longer:

```
d=->n,k,r{n-=k;r<?r??\\*k+?|*n :?|*~-k+?/*-~n}

```

Usage examples:

```
puts e[10, 5, 1] # or d[10, 5, 'r']
||||//////
puts e[10, 5, 0] # or d[10, 5, 'l']
\\\\\|||||

```

# Answer
> 8 votes
# J - 32 26 char

J can't handle more than two arguments without using a list, and it can't handle non-homogenous lists without boxing. So having the input as a list of three integers is ideal. The parameter order is the reverse of the standard one: 0 for left or 1 for right, then position, then total number of dominoes. The reason for this is because J will end up going through them right-to-left.

```
{`(('|/\'{~-@>:,:<:)1+i.)/

```

Here's what's going on. `F`G/` applied to a list `x,y,z` will evaluate `x F (y G z)`. `y G z` constructs both possible ways the dominoes could have toppled, and then `F` uses `x` to select which of the two to use.

Below is a back-and-forth with the J REPL that explains how the function is built together: indented lines are input to the REPL, and responses are flush with the left margin. Recall that J evaluates strictly right to left unless there are parens:

```
   1 ] 3 (]) 10            NB. ] ignores the left argument and returns the right
10
   1 ] 3 (] 1+i.) 10       NB. hook: x (F G) y  is  x F (G y)
1 2 3 4 5 6 7 8 9 10
   1 ] 3 (>: 1+i.) 10      NB. "greater than or equal to" bitmask
1 1 1 0 0 0 0 0 0 0
   1 ] 3 (-@>: 1+i.) 10    NB. negate
_1 _1 _1 0 0 0 0 0 0 0
   1 ] 3 (<: 1+i.) 10      NB. "less than or equal to"
0 0 1 1 1 1 1 1 1 1
   1 ] 3 ((-@>:,:<:)1+i.) 10          NB. laminate together
_1 _1 _1 0 0 0 0 0 0 0
 0  0  1 1 1 1 1 1 1 1
   1 ] 3 (('|/\'{~-@>:,:<:)1+i.) 10   NB. turn into characters
\\\|||||||
||////////
   1 { 3 (('|/\'{~-@>:,:<:)1+i.) 10   NB. select left or right version
||////////
   {`(('|/\'{~-@>:,:<:)1+i.)/ 1 3 10  NB. refactor
||////////
   {`(('|/\'{~-@>:,:<:)1+i.)/ 0 3 10
\\\|||||||

```

At the expense of a few characters, we can make the order the standard order: just append `@|.` to the end of the function:

```
   |. 10 3 1
1 3 10
   {`(('|/\'{~-@>:,:<:)1+i.)/@|. 10 3 1
||////////

```

Adapting this to work with a string argument for direction would be much more costly, however.

# Answer
> 8 votes
**Haskell, 70**

```
f R i l=(i-1)#'|'++(l-i+1)#'/'
f L i l=i#'\\'++(l-i)#'|'
(#)=replicate

```

assuming there is a type *Direction*, which has constructors *R* and *L*.

# Answer
> 7 votes
## PowerShell, 66

```
filter d($n,$k,$d){"$('\|'[$d])"*($k-$d)+"$('|/'[$d])"*($n-$k+$d)}

```

Probably the same idea every one else had.

* Takes either 0 or 1 as the direction parameter (for left and right, respectively)

# Answer
> 6 votes
## Golfscript (44 ~~53~~)

My first ever Golfscript program. Took me way longer than it should have and can probably be done in a smarter, more concise way (I'm sure someone will prove that :) ):

```
:d;:j;:^,{:x j<d&'\\'{x^j)->d!&'/''|'if}if}%

```

A sample input is `10 5 0`.

Ungolfed:

```
:d;:j;:^      # save input in variables and discard from stack, except total length ^
,             # create an array of numbers of length ^
{             # start block for map call
  :x          # save current element (= index) in variable
  j<          # check whether we are left of the first knocked over domino
  d           # check whether the direction is to the left
  &           # AND both results
  '\\'        # if true, push a backslash (escaped)
  {           # if false, start a new block
    x^j)->    # check whether we are on the right of the knocked over domino
    d!        # check whether the direction is to the right
    &         # AND both results
    '/'       # if true, push a slash
    '|'       # if false, push a non-knocked over domino
    if
  }
  if
}%            # close block and call map

```

# Answer
> 4 votes
## JS (ES6) - ~~79~~ ~~74~~ ~~72~~ ~~65~~ 62

thanks to @nderscore!

The 3rd param is a boolean (0: left / 1: right)

```
d=(a,b,c)=>"\\|"[a-=--b,c].repeat(c?b:a)+"|/"[c].repeat(c?a:b)

// Test
d(10,3,1); // => "||////////"
d(10,3,0); // => "\\\\\\\\||"

```

# Answer
> 4 votes
# Python - 45 ~~52~~

This requires `1` for right and `0` for left.

```
x=lambda n,k,d:'\\|'[d]*(k-d)+"|/"[d]*(n-k+d)

```

Here's a version that takes `r` and `l` correctly, at **58**:

```
def x(n,k,d):d=d=='r';return'\\|'[d]*(k-d)+"|/"[d]*(n-k+d)

```

Some usage examples...

```
>>> print(x(10,3,0))
\\\|||||||
>>> print(x(10,3,1))
||////////
>>> print(x(10,5,1))
||||//////
>>> print(x(10,5,0))
\\\\\|||||
>>> print(x(10,3,0))
\\\|||||||

```

# Answer
> 4 votes
### GolfScript, 28 23 characters

```
'\\'@*2$'|/'*$-1%1>+@/=

```

Arguments on top of stack, try online:

```
> 10 5 1
||||//////

> 10 5 0
\\\\\|||||

```

# Answer
> 3 votes
**Python2/3 - 54**

That last added on rule was quite nice (the 0/1 instead of 'l'/'r'). Made mine actually smaller than the existing python solution. 0 is left, 1 is right

```
def f(a,b,c):d,e='\|/'[c:2+c];h=b-c;return d*h+e*(a-h)

# Usage:
print(f(10,5,1)) # => ||||//////
print(f(10,5,0)) # => \\\\\|||||

```

# Answer
> 3 votes
# Haskell, 42 bytes

```
(n%k)b=["\\|/"!!(b-div(k-b-c)n)|c<-[1..n]]

```

Try it online!

Takes input like `(%) n k b` for `n` dominos, `k`'th domino toppled, direction `b`.

Finds the character at each position `c` ranging from `1` to `n` by using an arithmetic expression to compute the character index 0, 1, or 2.

Test cases taken from here.

---

**Haskell, 44 bytes**

```
(n%k)b=take n$drop(n+n*b+b-k)$"\\|/"<*[1..n]

```

Try it online!

An interesting strategy that turned out a bit longer. Generates the string `"\\|/"<*[1..n]` with `n` consecutive copies of each symbol, then takes a slice of `n` contiguous characters with start position determined arithmetically.

# Answer
> 2 votes
## Python 2.7, 68 65 61 59 58 chars

Use `d=1` for left and `d=0` for right

```
f=lambda a,p,d:['|'*(p-1)+'/'*(a-p+1),'\\'*p+'|'*(a-p)][d]

```

Note: Thanks to @TheRare for further golfing it.

# Answer
> 2 votes
## Perl, ~~67~~ 65 Characters

```
sub l{($t,$p,$d)=@_;$p-=$d;($d?'|':'\\')x$p.($d?'/':'|')x($t-$p)}

```

Assign the first three params (total, position, direction as an integer \[0 left, 1 right\]). Extras go into the ether. Subtract 1 from the position if we're headed right so the domino in position X is flipped, too.

# Answer
> 2 votes
# JavaScript (ES6) 61 ~~63~~

**Edit** It was buggy - shame on me.

Not so different from @xem, but found it myself and it's shorter. Parameter d is 0/1 for left/right

```
F=(a,p,d,u='|'.repeat(--p),v='\\/'[d].repeat(a-p))=>d?u+v:v+u

```

**Test** In Firefox console

```
for(i=1;i<11;i+=3) console.log('L'+i+' '+F(10,i,0) + ' R'+i+' '+ F(10,i,1))

```

**Output**

```
L1 \\\\\\\\\\ R1 //////////
L4 \\\\\\\||| R4 |||///////
L7 \\\\|||||| R7 ||||||////
L10 \||||||||| R10 |||||||||/

```

# Answer
> 2 votes
**Javascript, 46 characters**

Seems like cheating to do 0=l and 1=r but there is is. Shrunk it with a little recursion.

```
f=(a,p,d)=>a?'\\|/'[(p-d<1)+d]+f(a-1,p-1,d):''

```

edit: missed an obvious character

# Answer
> 2 votes
# Haskell, 57 bytes

*4 bytes saved thanks to this tip*

```
f 0 b _=[]
f a b c=last("|/":["\\|"|b>c])!!c:f(a-1)(b-1)c

```

Try it online!

# Haskell, ~~69~~ ~~61~~ ~~60~~ 58 bytes

```
(0!b)_=[]
(a!b)c|b==c=a!b$c+1|1>0="\\|/"!!c:((a-1)!(b-1))c

```

Try it online!

Not a very complex answer but it beats both of the existing Haskell answers.

# Answer
> 2 votes
# , ~~75~~ ~~68~~ ~~61~~ 57 bytes

An anonymous function. I'll post a fuller explanation if there is interest.

```
function(t,n,d)cat(c("\\","|","/")[(1:t>n-d)+1+d],sep="")

```

Try it online!

# Answer
> 2 votes
# Haskell, 51 bytes

```
f a b c=("\\|"!!c<$[1..b-c])++("|/"!!c<$[b-c..a-1])

```

`a` = number of dominoes, `b` = 1-based index of the touched one, `c` = direction (`0` is left and `1` is right).

Try it online!

# Answer
> 1 votes
**PHP, 89 Characters**

```
function o($a,$p,$d){for($i=0;$i<$a;$i++)echo$d==0?($i+1>$p)?'|':'\\':($i+1<$p?'|':'/');}

```

Just because I love PHP.

**EDIT:** The following code does the same.

```
function dominoes ($number, $position, $direction) {
    for ($i=0; $i<$number; $i++){
        if ($direction==0) {
            if (($i+1) > $position) {
                echo '|';
            } else {
                echo '\\';
            }
        } else {
            if (($i+1) < $position) {
                echo '|';
            } else {
                echo '/';
            }
        }
    }
}

```

# Answer
> 1 votes
# PHP - 64

```
function f($a,$b,$c){for($w='\|/';++$i<=$a;)echo$w[$c+($i>$b)];}

```

A simple loop, and echo-ing the character.

Generates a `Notice: Undefined variable: i`, here's another version silenting the error (65 characters) :

```
function f($a,$b,$c){for($w='\|/';@++$i<=$a;)echo$w[$c+($i>$b)];}

```

And a version withtout any error (69 characters) :

```
function f($a,$b,$c){for($w='\|/',$i=0;++$i<=$a;)echo$w[$c+($i>$b)];}

```

---

Other functions in PHP :

`sprintf` / `printf` padding

```
function f($a,$b,$c){printf("%'{${0*${0}=$c?'|':'\\'}}{$a}s",sprintf("%'{${0*${0}=$c?'/':'|'}}{${0*${0}=$a-$b+$c}}s",''));}

```

padding via `str_pad` / `str_repeat` functions

```
function f($a,$b,$c){$f='str_repeat';echo$f($c?'|':'\\',$b-$c).$f($c?'/':'|',$a-$b+$c);}
function f($a,$b,$c){echo str_pad(str_repeat($c?'|':'\\',$b-$c),$a,$c?'/':'|');}

```

using both `printf` and `str_repeat` functions

```
function f($a,$b,$c){printf("%'{${0*${0}=$c?'|':'\\'}}{$a}s",str_repeat($c?'/':'|',$a-$b+$c));}
function f($a,$b,$c){$w='\|/';printf("%'$w[$c]{$a}s",str_repeat($w[$c+1],$a-$b+$c));}

```

# Answer
> 1 votes
# Scala 75 characters

```
def f(l:Int,p:Int,t:Char)=if(t=='l')"\\"*p++"|"*(l-p) else "|"*(l-p):+"/"*p

```

# Answer
> 1 votes
# CJam - 20

```
q~
:X-_"\|"X=*o-"|/"X=*

```

The main code is on the second line, the first line is just for getting the parameters from the standard input (otherwise you need to put the parameters in the code).

Try it at http://cjam.aditsu.net/

**Examples:**

```
12 4 1
|||/////////

8 5 0
\\\\\|||

```

**Explanation:**

`:X` stores the last parameter (0/1 direction) in variable X
`-` subtracts X from the knock-over position, obtaining the length of the first sequence of characters (let's call it L)
`_` makes a copy of L
`"\|"X=` gets the character to use first: `\` for X=0 and `|` for X=1
`*` repeats that character L times
`o` prints out the string, removing it from the stack
`-` subtracts L from the number of dominoes, obtaining the length of the second sequence of characters (let's call it R)
`"|/"X=` gets the character to use next: `|` for X=0 and `/` for X=1
`*` repeats that character R times

# Answer
> 1 votes
## Common Lisp

This won't win in a code golf, but it highlights Common Lisp's justification format directive:

```
(lambda (n p d &aux (x "\\|/"))
   (format t "~v,,,v<~v,,,v<~>~>" n (aref x d) (+ d (- n p)) (aref x (1+ d))))

```

The arithmetic isn't bad: `n` is the total number of dominoes; `p` is the position of the first toppled domino; `d` is either `0` or `1`, representing left and right (as allowed in the comments), and is used as an index into `x`; `x` is a string of `\`, `|`, and `/`. The format string uses two (nested) justification directives, each of which allows for a padding character. Thus:

```
(dotimes (d 2)
  (dotimes (i 10)
    ((lambda (n p d &aux (x "\\|/"))
       (format t "~v,,,v<~v,,,v<~>~>" n (aref x d) (+ d (- n p)) (aref x (1+ d))))
     10 (1+ i) d)
    (terpri)))

\|||||||||
\\||||||||
\\\|||||||
\\\\||||||
\\\\\|||||
\\\\\\||||
\\\\\\\|||
\\\\\\\\||
\\\\\\\\\|
\\\\\\\\\\
//////////
|/////////
||////////
|||///////
||||//////
|||||/////
||||||////
|||||||///
||||||||//
|||||||||/

```

# Answer
> 1 votes
# , ~~23 21~~ 19 bytes

```
'|/\'{~{:-(>i.)~`-/

```

Try it online!

Input is a list of integers in the standard order.

# Answer
> 1 votes
# 05AB1E, 19 bytes

```
αα©„\|³è×¹®-„|/³è×J

```

I still have the feeling it's a bit long, but it works.. And better than the initial 23 bytes solution I had with if-else construction, which I quickly dropped..

Input order is the same as in the challenge: total length, index, `1`/`0` for left/right respectively.

Try it online or verify both test cases.

**Explanation:**

```
α                     # Take the absolute difference of the first two (implicit) inputs
                      #  i.e. 10 and 5 → 5
                      #  i.e. 6 and 3 → 3
 α                    # Then take the absolute difference with the third (implicit) input
                      #  i.e. 5 and 1 → 4
                      #  i.e. 3 and 0 → 3
  ©                   # Store this number in the register (without popping)
   „\|                # Push "\|"
      ³è              # Use the third input to index into this string
                      #  i.e. 1 → "|"
                      #  i.e. 0 → "\"
        ×             # Repeat the character the value amount of times
                      #  i.e. 4 and "|" → "||||"
                      #  i.e. 3 and "\" → "\\\"
         ¹®-          # Then take the first input, and subtract the value from the register
                      #  i.e. 10 and 4 → 6
                      #  i.e. 6 and 3 → 3
            „|/       # Push "|/"
               ³è     # Index the third input also in it
                      #  i.e. 1 → "/"
                      #  i.e. 0 → "|"
                 ×    # Repeat the character the length-value amount of times
                      #  i.e. 6 and "/" → "//////"
                      #  i.e. 3 and "|" → "|||"
                  J   # Join the strings together (and output implicitly)
                      #  i.e. "||||" and "//////" → "||||//////"
                      #  i.e. "///" and "|||" → "///|||"

```

# Answer
> 1 votes
# Vyxal, 23 bytes

```
[-‹\|*₴+\/*,|-\\*₴+\|*,

```

Try it Online!

# Answer
> 0 votes
# C - 62 64 ('l':left, 'r':right)

```
f(a,b,c){for(b=a-b;a--;)putchar(c&2?a<b?47:124:a>b-2?92:124);}

```

# C - 58 (0:left,1:right)

```
f(a,b,c){for(b=a-b;a--;)putchar(124-(a<b-!c?c*77:!c*32));}

```

recursive approach, but still, same length

```
f(a,b,c){a&&f(a-1,b,c)+putchar(124-(a<=b+!c?!c*32:c*77));}

```

awfully long (75) but most complex one (repeat function integrated into it)

```
f(a,b,c){c>1?a&&f(a-1,putchar(b),2):f(b+c,c?92:124,2)+f(a-b-c,c?124:47,2);}

```

# Answer
> 0 votes
### PowerShell (~~107~~ 95)

```
filter d($a,$b,$c){-join(1..$a|%{if($_-ge$b-and$c){'/'}elseif($_-le$b-and!$c){'\'}else{'|'}})}

```

If we're allowed to treat the third parameter as an integer (0=l,1=r), then I can shave a little off here.

Test input:

```
d 10 5 r
||||//////
d 10 5 l
\\\\\|||||

```

Update:

```
d 10 5 1
||||//////
d 10 5 0
\\\\\|||||

```

If anyone by chance wants an explanation I will gladly add one. And as always I'm open to suggestions.

Original:

```
function d($a,$b,$c){-join(1..$a|%{if($_-ge$b-and$c-eq'r'){'/'}elseif($_-le$b-and$c-eq'l'){'\'}else{'|'}})}

```

# Answer
> 0 votes
## C++ 181

```
#define C(x) cin>>x;
#define P(x) cout<<x;
int n,k,i;char p;
int main(){C(n)C(k)C(p)
for(;i<n;i++){if(p=='r'&&i>=k-1)P('/')else if(p=='l'&&i<=k-1)P('\\')else P('|')}
return 0;}

```

# Answer
> 0 votes
## VBScript 101 95 74

Edit: Looks like a lot of answers accept bool directions. For char directions, replace `-d` with `+(d="r")` for a score increase of 6.

```
function f(a,p,d):for x=1to a:f=f+mid("/|\",3-d+(x>p),1):next:end function

```

# Answer
> 0 votes
# C# 92('\\':left, '/':right)

```
String d(int c, int p, char d){ String r="";for(int i=0;i<c;i++)r+=(i>=c-p)?d:'|';return r;}

```

# Answer
> 0 votes
## AWK, 76 61

```
{ORS="";for(i=1;i<$2;i++)print"|";for(i=$2;i<=$1;i++)print($3=="r"?"/":"\\")}

```

Usage:

```
echo 10 5 r | awk '{ORS="";for(i=1;i<$2;i++)print"|";for(i=$2;i<=$1;i++)print($3=="r"?"/":"\\")}'

```

Although I'm wondering if I can nest ternary operators to make this shorter (although I'm playing around in bash right now and it doesn't seem like you can).

**edit** -- shorter version:

```
{ORS="";for(i=0;i<$1;i++)print i<$2?"|":($3=="r"?"/":"\\");}

```

# Answer
> 0 votes
# PHP - 105,97, 96

```
 function a($r,$l,$f){$a=str_repeat('|',$l-$f);$b=str_repeat($r?'/':'\\',$f);echo$r?$a.$b:$b.$a;}

```

Example results:

```
a(true,10,4);  -> \\\\||||||
a(false,10,5); -> |||||/////
a(false,10,2); -> ||||||||//

```

# Answer
> 0 votes
# Javascript, 81 85 characters

```
function e(a,b,c){l='repeat';d='|'[l](--a-b++);return c>'q'?d+"/"[l](b):"\\"[l](b)+d}

```

First time trying codegolf, was fun thanks :)

# Answer
> 0 votes
# JavaScript - 85 chars

```
function d(a,b,c){for(r=c?"\\":"/",p="",b=a-b;a--;)p+=c?a<b?"|":r:a>b?"|":r;return p}

```

1 = Left, 0 = Right

```
d(10,3,1)
\\\|||||||
d(10,3,0)
||////////
d(10,7,1)
\\\\\\\|||
d(10,7,0)
||||||////

```

# Answer
> 0 votes
**vb.net (~75c)**

```
Dim f=Function(l,p,d)(If(d="l",StrDup(p,"\"),"")& StrDup(l-p-If(d="l",1,0),"|")).PadRight(l,"/")

```

# Answer
> 0 votes
**Clojure, 81 chars**

```
(defn g[a,p,d](apply str(map #(nth "\\|/"(+(if(>= % (- p d)) 1 0) d))(range a))))

```

# Answer
> 0 votes
## JavaScript (ES5) - 86 chars

```
function f(a,p,d){r='';while(a-->p+1)r+='|';while(a-->=0)r=d>'q'?r+'/':'\\'+r;return r}

```

# Answer
> 0 votes
# Autoit 245 Bytes

```
Local $1 = "",$dir = "l",$amout = 100,$pos = 33
for $i=1 to $pos
    if $dir = "r" then
    $1 = $1 & "|"
Else
    $1 = $1 & "\"

EndIf
next
for $i=1 to $amout-$pos
    if $dir = "r" then
    $1 = $1 & "/"
Else
    $1 = $1 & "|"
EndIf
next
ConsoleWrite($1 & @cr)

```

# Answer
> 0 votes
# Python 71 59

```
def k(n,p,d):c,r='\/'[d],n-p;return[c*p+'|'*r,'|'*p+c*r][d]

```

# Answer
> 0 votes
# Haskell (72)

Using guards and the characters `'r'` and `'l'` as directions:

```
r=replicate;k a o d|d=='r'=r(a-o)'|'++r o '/'|d=='l'=r o '\\'++r(a-o)'|'

```

# Answer
> 0 votes
# Perl : 66 characters

My first code golf submission! Thanks for the fun challenge.

```
sub k{($n,$p,$r)=@_;$n-=$p;$d=$r?"|"x--$p.'/'x++$n:'\\'x$p.'|'x$n}

```

Explanation with whitespace:

```
sub k{
  ($n,$p,$r) = @_;      # get function arguments: <# dominos> <position> <0=left, 1=right>
  $n -= $p;             # total number of dominos - position
  $d = $r ? "|"x--$p . '/'x++$n : '\\'x$p . '|'x$n
                        # if direction = 1, make pos - 1 '|'s and (total - position  + 1) '/'s
                        # if direction = 0, make pos '\'s and (total - position) '|'s
                        # return is the last action of the function, it returns the string in $d.
                        # Semicolon at end of line can be left off, as it is the last statement of the function
}

```

Example usage and output:

```
my $result = k(10,5,1); print "$result\n";
||||//////
my $result = k(10,5,0); print "$result\n";
\\\\\|||||

```

# Answer
> 0 votes
# Python, 69

My first code golf submission, with Python in 69 characters:

```
def d(a,b,c):print "|"*(b-1)+"/"*((a+1)-b) if c else "\\"*b+"|"*(a-b)

```

Usage: d(10,5,1)

# Answer
> 0 votes
# PHP, 55 bytes

```
for([,$c,$n,$d]=$argv;$c--;)echo"\|/"[$d+(++$i+$d>$n)];

```
* requires PHP 7.1 or later
* replace `[...]=$argv` with `list(...)=$argv` for PHP 5.5 or later
* for older PHP, insert `$s="\|/",` before that and replace the other `"\|/"` with `$s`.

Run with `php -nr '<code>' <total> <N> <numeric direction>` or try it online.

# Answer
> 0 votes
# Japt, 15 bytes

I'm sure this could probably be shorter but it's been a long day. Uses `0` & `1` for left and right.

```
ç| hW*VVçWg"\\/

```

Try it

```
ç| hW*VVçWg"\\/     :Implicit input of integers U=total, V=n & W=direction
ç|                  :Repeat "|" U times
   h                :Replace the characters starting at 0-based index ...
    W*V             :W times V with ...
       Vç           :V times repeat ...
         Wg"\\/     :Index W into "\/"

```

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


title: Is it a checkered tiling?

text:
# Question
Title: Is it a checkered tiling?
## Background

A **checkered tiling** of a rectangular grid is a tiling using some polyominoes, where each region can be colored either black or white so that no two polyominoes sharing an edge has the same color. In graph-theoretic terms, the chromatic number of the adjacency graph is 2.

Terminology adapted from a Fillomino variant recently posted on GMPuzzles.

The following is an example of a checkered tiling, with a possible black-and-white coloring on the right:

```
+-+-+-+-+-+   +-+-+-+-+-+
|A A A|B|C|   |X X X| |X|
+ +-+-+-+ +   + +-+-+-+ +
|A|D D|C C|   |X|   |X X|
+-+-+ + +-+   +-+-+ + +-+
|E|F|D|C|G|   | |X| |X| |
+ +-+-+-+ +   + +-+-+-+ +
|E E|H|G G|   |   |X|   |
+ + + +-+-+   + + + +-+-+
|E E|H H H|   |   |X X X|
+-+-+-+-+-+   +-+-+-+-+-+

```

The following is not a checkered tiling, because it is not possible to color E, H, I with two colors.

```
+-+-+-+-+-+
|A A A|B|C|
+ +-+-+-+ +
|A|D D|C C|
+-+-+ + +-+
|E|F|D|C|G|
+ +-+-+-+ +
|E E|H|G G|
+ +-+ +-+-+
|E|I|H H H|
+-+-+-+-+-+

```

## Task

Given a tiling, test if it is a checkered tiling.

A tiling can be input as a 2D array or string where each region is represented by a unique single alphanumeric character or integer. For example, the top array can be represented as

```
AAABC
ADDCC
EFDCG
EEHGG
EEHHH

```

or

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

```

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.

## Test cases

**Truthy**

```
0

00
00

012

0011
2013
2233

01234
56789
ABCDE
FGHIJ

000
010
002

```

**Falsy**

```
01
22

00
12

01
02

01234
05674

0011
0221
3244
3345

```

Brownie points to the first answer that beats or ties with 17 bytes in Dyalog APL (any version) or 96 bytes in JS (latest browser support, not very well golfed).

# Answer
> 16 votes
# JavaScript, ~~106~~ 101 bytes

```
s=>[...s,'!',s].reverse().join``.match(`(.)((?!\\1).)[^!]{${s.indexOf`
`-1}}((?!\\1|\\2).)(\\2|\\3)`)

```

Try it online!

(Returns inverted truthy/falsy.)

-5 by using spread syntax.

Focus on the boundaries of the tiling.

Suppose the tiling is not checkered. Then there is an odd cycle in the adjacency graph. Draw the odd cycle by connecting adjacent squares' centres, like this:

Since the cycle is odd, the route crosses an odd number of boundaries.

Now divide the space enclosed by the route into small squares.

Notice that the route's boundary-crossing count has the same parity as the sum of the squares' boundary-crossing counts. Thus at least one of the squares has an odd boundary-crossing count. It cannot be 1, so it must be 3, giving a T shape.

A regular expression is used to look for a T shape oriented as ┤ or ┴, and applied to a combination of the given string and its reverse to cover all four orientations. This relies on `.` not matching `\n` by default, and `!` not being a character used in the input.

# Answer
> 13 votes
# Python 3, ~~100 99~~  88 bytes

```
lambda a:2in[len({i,l}^{k,j})for x,y in zip(a,a[1:])for i,j,k,l in zip(x,x[1:],y,y[1:])]

```

Try it online!

Return `True` if it isn't checkered tiling, `False` otherwise

-1 byte by inversing True/False for return value

-11 thanks to @xnor

## How it works:

The pattern is True if any of the following sub-pattern appears in the pattern :

```
AA  Ax  xy  xA
xy  Ay  AA  yA

```

We will then check each 2 by 2 sub-pattern.

* `for x,y in zip(a,a[1:])` allows me to iterate through 2 adjacent row at the same time
* `for i,j,k,l in zip(x,x[1:],y,y[1:])` define the 4 elements of our subpattern,
* `len({i,l}^{k,j})` do the mutual difference on the `2` diagonals (keeps only the elements which are not in both) and compute the length. This value is equal to 2 only for all the truthy sub-patterns (and for a case not possible geometricaly in this puzzle)
* `2in[ ... ]` verify that at least one of the subpatterns has his value equal to `2`

# Answer
> 10 votes
# Python 2, ~~167~~ ~~153~~ 143 bytes

```
def f(a):
 m={a[0][0]:1}
 for R in a+zip(*a)+a:
  p=0
  for c in R:
    P=m.get(p);Q=m.get(c,0)
    if(c==p)*2<Q==P:return 1
    if(P>0)>Q:m[c]=3-P
    p=c

```

Try it online!

*-10 or so bytes from @Bubbler*

*-1 byte independently from @Recursive Co.*

*-11 bytes from @ovs*

*+2 bytes from fixing a bug spotted by @tsh*

Returns `None` for truthy and `1` for falsey. Takes input as a list of lists of strings (it was numbers before, but strings saves a byte by making them distinct from `0` on line 4).

Using Python 2 to save indentation by mixing tabs and spaces.

## Ungolfed

```
def is_checkered(arr):
    # mark the top-left column as color 0
    m = {arr[0][0]: 0}
    # zip(*arr) is the transpose of arr
    # iterate over each row and column, then row again
    # 1) loop over rows to guarantee computing colors for the top row
    # 2) loop over columns to guarantee computing colors for the entire grid
    #   - at the same time, this checks that horizontally adjacent tiles have different colors
    # 3) loop over rows again to check that vertically adjacent tiles have different colors
    for transposal in [arr, zip(*arr), arr]:
        for row in transposal:
            prev = row[0]
            for c in row:
                if c != prev and c in m and prev in m and m[c] == m[prev]:
                    # this tile and the previous are the same color
                    return False
                if c not in m and prev in m:
                    # this tile does not yet have a color,
                    # but the previous tile does, so assign the opposite color
                    m[c] = 1 - m[prev]
                prev = c
    return True

```

# Answer
> 9 votes
# JavaScript, 98 bytes

*-3 bytes by Arnauld*

```
a=>a.every(m=l=>a=!l.some((c,x)=>m[v=a[x],u=l[x-1]]==(M=m[c]??=-m[u??v]|1)&&c-u||m[v]==M&&c-v)&&l)

```

```
f=

a=>a.every(m=l=>a=!l.some((c,x)=>m[v=a[x],u=l[x-1]]==(M=m[c]??=-m[u??v]|1)&&c-u||m[v]==M&&c-v)&&l)

testcases = `
0

00
00

012

0011
2013
2233

01234
56789
ABCDE
FGHIJ

000
010
002

01
22

00
12

01
02

01234
05674

0011
0221
3244
3345
`.trim().split('\n\n').map(x => x.trim().split('\n').map(l => [...l].map(v => Number.parseInt(v, 36) + 1)));

testcases.forEach(t => {
  console.log(f(t));
});
```

Input a 2-d array with positive numbers.

Output true / false.

```
a=>a.every( // For each row
m= // m is the mapping from regions to its color (-1 or 1)
l=>
a= // `a` is reused to storage last row
!l.some((c,x)=>
m[
v=a[x], // `v` is its upper neighbor
u=l[x-1] // `u` is its left neighbor
]==(
M=m[c]??= // If we haven't assign a color to current grid, assign color
-m[u??v]|1 // If this is first column, we use its upper neighbor
           // Otherwise we use its left neighbor
           // We use different color to its neighbor
           // If this is the most top left one, we use 1
)&& // If this cell have same color with its left neighbor
c-u|| // But they are in different region
m[v]==M&&c-v // Check its upper neighbor this time
)&&l // Assign `l` to `a` for so you can access it when check next row
)

```

# Answer
> 8 votes
# Ruby, 108 bytes

```
->a{w,i,j,q=0;a.map{|x|w,i=(j=x.zip(j||x).map{|y,c|[y==i ?w:w^=1,i=y,q||=((c[0]==w)^(c[1]==i))&&j]})[0]};!q}

```

Try it online!

# Answer
> 6 votes
# 05AB1E, ~~36~~ ~~33~~ ~~27~~ 26 bytes

Prints 1 if the input is a checkered tiling and 0 if not.

```
˜Ù2.Œε€ã€`€ÙIDø«€ü2€`Ãg]0å

```

Try it online! or Try more cases.

This tests if the graph of polyominoes is bipartite by trying all partitions into two subsets until it finds one where no polyominoes in the same subset are adjacent.

Technically `Ù` is not necessary, but this is already quite slow and would be unusable otherwise.

```
˜Ù                # all unique integers from the input
  2.Œ             # all ways to partition those into two subsets
     ε            # for each partition:
      €ã€`        #   generate pairs of two elements from the same subset
          €Ù      #   deduplicate each pair, if both values were equal, this results into a singleton list

IDø«              #   input and input transpose concatenated (list of rows and columns)
    €ü2           #   for each row or column: get all adjacent pairs
       €`         #   and flatten into a single list of pairs
         Ã        #   list intersection with the list from before
          g       #   take the length

]0å               # after the map: was the result 0 for any partition?

```

# Answer
> 5 votes
# Jelly, 22 bytes

```
FQŒPðfLḂɗþPẸµ;Z,Ɲ€ẎEÐḟ

```

Try it online! (comes with test cases)

Uses the same approach as my Pyth answer and ovs's 05AB1E solution.

Turns out I just needed a love-hate relationship to Jelly for like 3 years to finally understand how the chains work.

### Explanation

```
FQŒPðfLḂɗþPẸµ;Z,Ɲ€ẎEÐḟ
F                        Flatten the input rows.
 Q                       Find unique characters (polyominos).
  ŒP                     Get all subsets of the characters.
              Z          Get the columns of the input.
             ;           Append them to the input rows.
               ,Ɲ        Get all overlapping pairs...
                 €       ...of each row/column. (Alternatively, ṡ€2.)
                  Ẏ      Concatenate the lists of pairs.
                    Ðḟ   Filter for pairs where...
                   E     ...the elements are not equal.
         þ               For each subset/pair combination:
     f                     Find items in the subset that are also in the pair.
      L                    Take the length of the result.
       Ḃ                   Take the length modulo 2.
                         This gives a 2D array where the outer index specifies
                         the pair and the inner index the subset.
          P              Take an elementwise product of the rows. This gives
                         1 for each subset that results in a product of 1.
           Ẹ             See if there are any subsets that produced a 1.

```

# Answer
> 4 votes
# Charcoal, 57 bytes

```
ＷＳ⊞υι≔⭆υ⭆ι⁺⎇κ⁺§§υ⊖κμλω⎇μ⁺§ι⊖μλωθ≔⁻⪪⁺θ⮌θ²Ｅθ⁺ιιη⊙η⊙θ⬤ι№η⁺λν

```

Try it online! Link is to verbose version of code. Reverse output, i.e. `-` if not chequered. Explanation:

```
ＷＳ⊞υι

```

Input the tiling.

```
≔⭆υ⭆ι⁺⎇κ⁺§§υ⊖κμλω⎇μ⁺§ι⊖μλωθ

```

For each cell, concatenate it with the cell above and to the left (if any) and concatenate all of the results together.

```
≔⁻⪪⁺θ⮌θ²Ｅθ⁺ιιη

```

Concatenate that with its reverse, split it back into pairs, but remove all identical pairs.

```
⊙η⊙θ⬤ι№η⁺λν

```

Does there exist a pair in the adjacency list and a cell having the property that the cell is adjacent to both cells in the pair?

A port of @Jakque's answer is the same length but much faster:

```
ＷＳ⊞υι⊙υ∧κ⊙ι∧μ¬⁼⁼⁼λ§ι⊖μ⁼§§υ⊖κμ§§υ⊖κ⊖μ⁼⁼λ§§υ⊖κμ⁼§ι⊖μ§§υ⊖κ⊖μ

```

Try it online! Link is to verbose version of code. Reverse output, i.e. `-` if not chequered.

# Answer
> 2 votes
# Pyth, 25 bytes

```
sm!-ml@dk{I#s.:R2+CQQ1y{s

```

Try it online!

Might time out on test cases with lots of unique characters (polyominos).

Turns out I came up with the exact same algorithm as ovs's 27-byte 05AB1E answer ¯\\\_(ツ)\_/¯

### Explanation

Essentially, the program tries all colorings of the tiling, and sees if there is a coloring for which all adjacent pairs have exactly one black tile.

`Q` is implicitly appended to the program and the input is read into `Q`.

```
                        sQ   Concatenate the input rows.
                       {     Find unique characters in input.
                      y      Take the powerset of these.
 m                           For each subset d of the characters:
                  CQ           Get the columns of the input.
                 +  Q          Append the rows of the input.
             .: 2              Get length-2 substrings...
               R               ...of each row/column.
            s                  Concatenate the substring lists of rows/columns.
           #                   Find substrings (pairs) that...
          I                    ...stay the same when...
         {                     ...duplicates are removed.
    m                          For each such pair k:
      @dk                        Find the characters of k that are in d.
     l                           Get the length of that.
   -                 1         Remove all ones from that array of lengths.
  !                            True if the list is now empty.
s                            Sum the booleans in that list.

```

# Answer
> 1 votes
# Julia 1.5, ~~128~~ 99 bytes

```
M->(~M=diff(M,dims=1).!=0;!M=~x[M]!=~M;x=1:max(M...).>0;while(s=x[end])&&!M|!M' x.chunks.-=1end;s)

```

This basically tests each possible way of assigning each number either a 0 or 1 value, and determines whether the assignment keeps the number of boundaries constant (if two adjacent tiles are coloured the same, the boundary between them is removed).

M should take the form of an array of small positive integers (no zero or negatives).

This uses BitVectors - as it turns out, a bitvector is stored internally as an integer, so you can iterate through all combinations by incrementing the bitvector's internal representation (accessed as a "chunks" property of the variable).

**Ungolfed**:

```
function f(M)
  # This is the function you use to determine whether the tiling is chequered.
  x=trues(maximum(M)) #Initialise a bitarray, representing the assignment of tiles
  while x[end] #Loop until the assignment of the last tile is changed
               #from that point, all assignments are just bit-flips of the ones before!
    if (diff(M,dims=1).!=0)==(diff(x[M],dims=1).!=0)
      if (diff(M',dims=1).!=0)==(diff(x[M'],dims=1).!=0)
        break #If both horizontal and vertical boundaries are retained...
              #a successful tiling has been found!
      end
    end
    x.chunks.+=1 #Move to the next tile assignment
  end
  return x[end] #x[end] is true if it finds a successful tiling
                #but the loop ends if x[end] becomes false, indicating
                #that no tiling is found.
end

```

# Answer
> 1 votes
# Retina 0.8.2, 109 bytes

```
1`(?<=(.)*)(.)(?(\2).+¶(?>(?<-1>.)*)(?!\2)(.)(?!\2|\3)|(.).*¶(?>(?<-1>.)*)(?(\2).(?!\2|\4)|(?!\4)(.)(\4|\5)))

```

Try it online! Reverse output, i.e. `1` if not chequered (-2 bytes if arbitrary non-zero output is allowed for not chequered). Explanation: Port of @Jakque's Python answer.

```
1`

```

Only look for 1 match.

```
(?<=(.)*)

```

Count the column of this cell.

```
(.)

```

Capture the top left cell of a 2×2 square.

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

```

If the top right cell of the square has the same symbol, ...

```
.+¶(?>(?<-1>.)*)

```

Skip ahead to the bottom left cell of the square.

```
(?!\2)

```

This must not have the same symbol as the top left cell.

```
(.)(?!\2|\3)

```

The bottom right cell must not have the same symbol as either of the other cells.

```
(.)

```

Otherwise, capture the top right cell of the square.

```
.*¶(?>(?<-1>.)*)

```

Skip ahead to the bottom left cell of the square.

```
(?(\2).(?!\2|\4)|(?!\4)(.)(\4|\5))

```

If this has the same symbol as the top left cell, then check that the bottom right cell does not have the same symbol as the either of the other cells, otherwise check that the bottom left cell does not have the same symbol as the top right cell but the bottom right cell has the same symbol as either the top right or bottom left cell.

# Answer
> 1 votes
# Haskell, 111 bytes

```
w=zipWith
s=scanl
f(x,a)b=(x/=(a/=b),b)
u(a:b)=s f(1>0,a)b
z x@(a:b)=w(.tail)(s f<$>u(head<$>x))x==s(w f)(u a)b

```

Try it online!

# Haskell, 116 bytes

```
f(x,a)b=(x/=(a/=b),b)
(i#j)(a:b)=scanl i(j a)b
k=w f#(f#(,)(1>0))
e=[]:e
t=foldr(w(:))e
w=zipWith
z=((==).t.k.t)<*>k

```

Try it online!

Probably not going to win any awards, but I had fun with both of these. They are a bit incomprehensible.

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


title: Generate information cards with titles

text:
# Question
Title: Generate information cards with titles
You must take input in the form of

```
title|line1|line2|(...)|line[n]

```

And output an information card. It's hard to explain how to make the card, so here's a quick example:

Input

```
1234567890|12345|1234567890123|pie|potato|unicorn

```

Output

```
/===============\
|  1234567890   |
|===============|
| 12345         |
| 1234567890123 |
| pie           |
| potato        |
| unicorn       |
\---------------/

```

Detailed specifications:

* The title must be centered (if there are an odd number of characters you can decide whether to put an extra space after or before it).
* The remaining lines must be left-aligned.
* All of them must have at least one space of padding before and after.
* Each line must be the same length.
* The lines must be the smallest length possible in order to fit all of the text.
* The first and last character of each row (except for the first and last rows) must be a `|`.
* There must be a `/`, a row of `=`s, and a `\` in the line right before the title. (the first line)
* There must be a `|`, a row of `=`s. and a `|` in the line right after the title. (the third line)
* There must be a `\`, a row of `-`s, and a `/` in the last line.
* For the example input provided, your program's output must exactly match the example output provided.
* The input will always contain at least one `|`; your programs behaivior when a string like `badstring` is input does not matter.

This is so the shortest code in character count wins.

# Answer
### GolfScript, 97 characters

```
'|'/{'  ':!{1/*}:E~}%.{,}%$-1=:L'='*:§'/\\'E\(.,L\-)2/{!E}*L<'||':^E§^E@{!L*+L<^E}/L'-'*'\\/'E]n*

```

Example:

```
> 1234567890|12345|1234567890123|pie|potato|unicorn

/===============\
|   1234567890  |
|===============|
| 12345         |
| 1234567890123 |
| pie           |
| potato        |
| unicorn       |
\---------------/

```
> 3 votes

# Answer
## Ruby, ~~153~~ ~~147~~ 140 characters

```
h,*d=s=gets.chop.split(?|)
puts"/%s\\
|%s|
|%s|"%[e=?=*k=2+l=s.map(&:size).max,h.center(k),e]
d.map{|x|puts"| %%-%ds |"%l%x}
$><<?\\+?-*k+?/

```

Double format string in the second-to-last line `:D`
> 4 votes

# Answer
# Python 2.7 - 168 = 166 + 2 for quotes.

This assumes we can accept the input with surrounding quotes, hence the possible +2. Either way +2 is better than the +4 required if you use `raw_input()` vs. just `input()`.

```
b="|"
s=input().split(b)
w=max(map(len,s))
x=w+2
S="| %s |"
print"\n".join(["/"+"="*x+"\\",S%s[0].center(w),b+"="*x+b]+[S%i.ljust(w)for i in s[1:]]+["\\"+"-"*x+"/"])

```

Thanks to Volatility for the `max(map(len,s))` tip. A very cool tip.

**edit:** Corrected top row problem.

And the above outputs this:

```
> python i.py
"1234567890|12345|1234567890123|pie|potato|unicorn"
/===============\
|   1234567890  |
|===============|
| 12345         |
| 1234567890123 |
| pie           |
| potato        |
| unicorn       |
\---------------/

```
> 4 votes

# Answer
# Charcoal, 66 bytes

```
≔∕Ｓ|ι≔⁺⌈ＥιＬκ²ς/×=ς↓\↓⁺Ｌι¹←/←ς↑\↑⁺Ｌι¹↘Ｍ∕⁻ςＬ§ι⁰¦²→Ｐ§ι⁰Ｍ±²¦¹Ｐ×=ςＭ↘✂ι¹

```

My first Charcoal answer!

I wasn't getting a proper result with reflection, so I made the box manually.

Try it online!

# Charcoal (Verbose), 385 bytes

```
Assign(Divide(InputString,"|"),i)
Assign(Add(max(Each(i,Length(k))),2),v)
Print("/")
Print(Times("=",v))
Print(:Down,"\\")
Print(:Down,Length(i)+1)
Print(:Left,"/")
Print(:Left, v)
Print(:Up, "\\")
Print(:Up,Length(i)+1)
Move(:DownRight)
Move(Minus(v,Length(AtIndex(i,0)))/2,:Right)
MultiPrint(AtIndex(i,0))
Move(Negate(2),1)
MultiPrint(Times("=",v))
Move(:DownRight)
Print(Slice(i,1))

```

Try it online!
> 4 votes

# Answer
## Haskell, 292

```
import Data.List.Split
z=replicate
l=length
p w s=' ':s++z(w-l s)' '
c w s=p w$z(div(w-l s-1)2)' '++s
t(i:s)=let r=z m;m=(+)1$maximum$map l(i:s)in"/="++r '='++"\\\n"++"|"++c m i++"|\n|="++r '='++"|\n"++concat['|':p m x++"|\n"|x<-s]++"\\-"++r '-'++"/"
main=do l<-getLine;putStrLn$t$splitOn"|"l

```

… I’m a little new to this one :D
> 2 votes

# Answer
# Vyxal, 60 bytes

```
\|/DvLG⇧D\=*\/p\\+,„h⋏\|pǏ,:\|$-Ǐ,‹£Ḣƛ¥↲ðp\|pǏ,;¥›\=*\\p\/+,

```

Try it Online!

Longer than I'd like...
> 2 votes

# Answer
# C# 4.5 - 375 347 chars

`;)` \[If someone is interested to see how C# differs from others\]

---

```
var c = input.Split('|').ToList();
int l = c.Select(s => s.Length).Max() + 2;
Console.WriteLine("/{0}\\\r\n| {1} |\r\n|{0}|\r\n{2}\r\n\\{3}/\r\n", "=".PadRight(l, '='), c[0].PadLeft(c[0].Length + ((l - c[0].Length) / 2)-1).PadRight(l-2), string.Join("\r\n", c.Select(s => "| " + s.PadRight(l - 2) + " |").Skip(1)), "-".PadRight(l, '-'));

```

---
> 1 votes

# Answer
# Javascript, ~~373~~ 364

```
l="length";m=" ";a="\\";b="/";c="|";p=m+c;v="join";u="concat";o=[];q=Array;i=prompt().split(c);j=i.slice().sort(function(d,e){return e[l]-d[l]})[0][l]+3;i=i.map(function(d,e){s=q(o[l]=0|(e?j-d[l]-1:(j-d[l])/2))[v](m);return(e?p:c+s+(d[l]&1?m:""))+d+(e?s:s+m)+p});x=q(o[l]=j)[v]("=");r=[b+x+a,i.shift(),c+x+c][u](i)[u](a+q(o[l]=j)[v]("-")+b);console.log(r[v]("\n"))

```

Output

```
/===============\
|  1234567890   |
|===============|
| 12345         |
| 1234567890123 |
| pie           |
| potato        |
| unicorn       |
\---------------/

```

<sub> Edit Notes:
Thanks @Doorknob!: -9 Characters =) </sub>
> 1 votes

# Answer
# Java - ~~549~~ ~~492~~ ~~468~~ ~~453~~ 432

```
class a{static<T>void p(T p){System.out.println(p);}public static void main(String[]a){String b="/=";int l=0,t,i;a=a[0].split("\\|");for(String s:a)l=(t=s.length())>l?t:l;for(t=0;t<l;t++)b+="=";b+="=\\";p(b);i=a[0].length();p(String.format("| %"+(l+i)/2+"s%"+(l-i)/2+"s |",a[0]," "));b="|=";for(t=0;t<l;t++)b+="=";b+="=|";p(b);for(t=1;t<a.length;t++)p(String.format("| %-"+l+"s |",a[t]));b="\\-";for(t=0;t<l;t++)b+="-";b+="-/";p(b);}}

```

**With line breaks and tabs**

```
class a{

    static<T>void p(T p){System.out.println(p);}

    public static void main(String[]a){
        a=a[0].split("\\|");
        String b="/=";
        int l=0,t,i;

        for(String s:a)l=(t=s.length())>l?t:l;

        for(t=0;t<l;t++)b+="=";
        b+="=\\";
        p(b);

        p(String.format("| %"+(l+i)/2+"s%"+(l-i)/2+"s |",a[0]," "));

        b="|=";
        for(t=0;t<l;t++)b+="=";
        b+="=|";
        p(b);

        for(t=1;t<a.length;t++)p(String.format("| %-"+l+"s |",a[t]));

        b="\\-";
        for(t=0;t<l;t++)b+="-";
        b+="-/";
        p(b);
    }
}

```
> 1 votes

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


title: ASCII Landscapes

text:
# Question
Title: ASCII Landscapes
**Objective**: Write a program that generates beautiful (?) ASCII-art landscapes and skylines!

Your program has just one input: a string composed of any combination/repetition of the chars `0123456789abc`.

For each input character, output a vertical line composed as follows:

```
         .
        ..
       ...
      oooo
     ooooo
    OOOOOO
   OOOOOOO
  XXXXXXXX
 XXXXXXXXX
XXXXXXXXXX

0123456789

```

Letters `abc` instead are followed by one number n, and draw the vertical line n with respectively 1,2 or 3 holes (spaces) at the bottom.

**Examples**

**The Chrysler Building**

Input: `2479742`

```
   .
   .
  ...
  ooo
  ooo
 OOOOO
 OOOOO
XXXXXXX
XXXXXXX
XXXXXXX

```

**The Taj Mahal**

Input: `0804023324554233204080`

```
 .                  .
 .                  .
 o                  o
 o        oo        o
 O O     OOOO     O O
 O O  OO OOOO OO  O O
 X X XXXXXXXXXXXX X X
 X X XXXXXXXXXXXX X X
XXXXXXXXXXXXXXXXXXXXXX

```

**The Eiffel Tower**

Input: `011a2b3b5c9c9b5b3a2110`

```
      ..
      ..
      ..
      oo
     oooo
     OOOO
    OOOOOO
   XXX  XXX
 XXX      XXX
XXX        XXX

```

You can assume input is not empty and that it's well-formed.
Any language is accepted, from A+ to Z++.

This is code-golf: **the shortest source code wins**.
If anything in the rules is not clear, feel free to ask below in the comments.

Have fun, and capture hundred meters high structures in a few bytes!

(and don't forget to include your favourite building in your solution)

P.S.: no, you can't download/access data from the Internet, use your file name as data and all that stuff. Be fair, and use only your code-golf skills.

# Answer
## GolfScript, 69

```
'XXXOOoo...':s\{.96>{96-.' '*\@>+}{47-<' '10*+10<s\}if}%10/zip-1%n*\;

```

Not far off the APL solution.

Test online
> 6 votes

# Answer
## Ruby, ~~88~~ 85

Fun challenge!

```
9.downto(0){|h|puts$*[0].gsub(/(\D?)(.)/){'XXXOOoo... '[h<$1.hex-9||$2.hex<h ?-1:h]}}

```

Takes input on the commandline, eg:

```
ruby landscapes.rb 011a2b3b5c9c9b5b3a2110

```

Will print out:

```
      ..
      ..
      ..
      oo
     oooo
     OOOO
    OOOOOO
   XXX  XXX
 XXX      XXX
XXX        XXX

```
> 6 votes

# Answer
## C, ~~130~~ 126 chars

Kinda long compared to the competition, but I blame the language...

```
char*p,b[99];r=10,q;main(o){for(gets(&b);r--;puts(""))
for(p=b;q=*p++;)o=q<60?putchar("XXXOOoo... "[o<r&r<q-47?r:10]),-1:q-97;}

```

I don't know about *favourite* building, but one of the more recognizable ones around here is Globen, so here is a poor rendition of it.

```
% ./a.out <<<24556667777776665542

       ......
    oooooooooooo
  oooooooooooooooo
 OOOOOOOOOOOOOOOOOO
 OOOOOOOOOOOOOOOOOO
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX

```
> 6 votes

# Answer
## Python 2.7 - 186

Probably can be shorter...

```
x=[]
l=iter(raw_input())
a="XXX00oo..."
for i in l:
 try:i=int(i);o=0
 except:o=" abc".index(i);i=int(next(l))
 x.append(" "*o+a[o:i+1]+" "*(9-i))
for i in zip(*x)[::-1]:print''.join(i)

```

Sample run:

```
08040233245542332040800000247974200000011a2b3b5c9c9b5b3a2110
                             .              ..
 .                  .        .              ..
 .                  .       ...             ..
 o                  o       ooo             oo
 o        oo        o       ooo            oooo
 0 0     0000     0 0      00000           0000
 0 0  00 0000 00  0 0      00000          000000
 X X XXXXXXXXXXXX X X     XXXXXXX        XXX  XXX
 X X XXXXXXXXXXXX X X     XXXXXXX      XXX      XXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX        XXX

```

## Sydney Harbour Bridge

```
a1a13443a1a2a3a4a5a6a6a7a7a8a8a8a8a9a9a9a9a9a9a8a8a8a8a7a7a6a6a5a4a4a3a2a13443a1a1
                   ......
               ..............
             ..................
           oooooooooooooooooooooo
          oooooooooooooooooooooooo
   00    000000000000000000000000000    00
  0000  00000000000000000000000000000  0000
  XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  XXXX                                 XXXX

```

## Golden gate bridge / Cisco logo

```
a2a0a0a4a0a06a0a0a4a0a0a2a0a0a4a0a06a0a0a4a0a0a2

      o           o
      o           o
   0  0  0     0  0  0
   0  0  0     0  0  0
X  X  X  X  X  X  X  X  X
X  X  X  X  X  X  X  X  X
      X           X

```

Great question by the way!
> 6 votes

# Answer
# C64 BASIC, 276 PETSCII chars

My own solution, golfed down to 276 chars and 10 lines of BASIC V2.0!

```
0inputa$:dIc$(10):fOi=0to9:rE c$(i):nE:fOr=0to9
1z=1
2c=aS(mI(a$,z,z+1))
3ifc>57tHgO8
4ifc>=57-r tH?c$(9-r);:gO6
5?" ";
6z=z+1:ifz<=len(a$)gO2
7?:nE:eN
8z=z+1:w=aS(mI(a$,z,z+1)):ifw>=57-r aNc<=73-r tH?c$(9-r);:gO6
9?" ";:gO6:dA"x","x","x","o","o","W","W",".",".","."

```

(copy and paste in an emulator to see the result).

And finally, my favourite monument, the Brooklyn Bridge :)
> 6 votes

# Answer
# APL, 59 bytes SBCS

```
{⊖⍉↑(-N)↑¨(L/⍨1,2≤/L←A⍸⍵)↓¨(N←⎕D⍳⍵~A←'abc')↑¨⊂'XXXOOoo...'}

```

Try it on online!

Shorter than the other APL answers so far! I think it can probably be further golfed. Will add explanation soon!

Thanks to dzaima & hyper-neutrino for their advice in the The APL Orchard!
> 5 votes

# Answer
## APL (~~69~~ 66)

```
' XXXOOoo...'[1+⌽⍉⌽↑{z×(z<' abc'⍳⍵)<(1+⍎⍺)≥z←⍳10}/↑2↑¨I⊂⍨⎕D∊⍨I←⌽⍞]

```

Examples:

```
      ' XXXOOoo...'[1+⌽⍉⌽↑{z×(z<' abc'⍳⍵)<(1+⍎⍺)≥z←⍳10}/↑2↑¨I⊂⍨⎕D∊⍨I←⌽⍞]
0804023324554233204080

 .                  .
 .                  .
 o                  o
 o        oo        o
 O O     OOOO     O O
 O O  OO OOOO OO  O O
 X X XXXXXXXXXXXX X X
 X X XXXXXXXXXXXX X X
XXXXXXXXXXXXXXXXXXXXXX

      ' XXXOOoo...'[1+⌽⍉⌽↑{z×(z<' abc'⍳⍵)<(1+⍎⍺)≥z←⍳10}/↑2↑¨I⊂⍨⎕D∊⍨I←⌽⍞]
011a2b3b5c9c9b5b3a2110
      ..
      ..
      ..
      oo
     oooo
     OOOO
    OOOOOO
   XXX  XXX
 XXX      XXX
XXX        XXX

```
> 3 votes

# Answer
# PowerShell, 127 bytes

```
$r=,''*10
$args|% t*y|%{if($_-in97..99){$b=$_-96}else{,' '*$b+'XXXOOoo...'[$b.."$_"]+,' '*(9-"$_")|%{$r[--$i]+=$_}
$b=$i=0}}
$r

```

Try it online!
> 2 votes

# Answer
# Canvas, ~~35~~ 33 bytes

```
±｛⌐╷≡？┤╵“`Fc|C！‟ｍ］ｃ96－ ×１１╋╋｝｝）⤢⇵

```

Try it here!
> 2 votes

# Answer
# PHP, ~~131~~ 114 bytes

```
for($b=10;$b--;print"
")foreach(str_split($argn)as$a)$c=strpos(' abc',$a)?:!print$a<$b|$b<$c?' ':'XXXOOoo...'[$b];

```

Try it online!

```
$ echo 2479742|php -nF land.php
   .
   .
  ...
  ooo
  ooo
 OOOOO
 OOOOO
XXXXXXX
XXXXXXX
XXXXXXX

$ echo 011a2b3b5c9c9b5b3a2110|php -nF land.php
      ..
      ..
      ..
      oo
     oooo
     OOOO
    OOOOOO
   XXX  XXX
 XXX      XXX
XXX        XXX

$ echo a2a0a0a4a0a06a0a0a4a0a0a2a0a0a4a0a06a0a0a4a0a0a2|php -nF land.php

      o           o
      o           o
   O  O  O     O  O  O
   O  O  O     O  O  O
X  X  X  X  X  X  X  X  X
X  X  X  X  X  X  X  X  X
      X           X

```
> 2 votes

# Answer
# Jelly, 33 bytes

```
~kµṪV‘R×ØaiⱮ0xƲ)Ṗz0Ṛị“XXXOOoo...

```

Try it online!

Full program returning a list of lines. If that isn't acceptable, +2 bytes.

Note the trailing space. Included my favourite:

```
.                 .
..               ..
...             ...
oooo           oooo
ooooo         ooooo
OOOOOO       OOOOOO
OOOOOOO     OOOOOOO
XXXXXXXX   XXXXXXXX
XXXXXXXXX XXXXXXXXX
XXXXXXXXXXXXXXXXXXX

```

## How it works

```
~kµṪV‘R×ØaiⱮ0xƲ)Ṗz0Ṛị“XXXOOoo...  - Main link. Takes a string on the left
~                                 - Bitwise NOT. This maps digits d to ~d and non-digits to 0
 k                                - Partition the string after falsey values
                                     This groups the string as we want, with a trailing []
  µ            )                  - Over each element, either [L, x] or [x]:
   Ṫ                              -   Extract x, modifying the element
    V                             -   Evaluate as a digit
     ‘                            -   Increment
      R                           -   Create a range
              Ʋ                   -   Last 4 links as a monad f([L]) or f([]):
        ØaiⱮ                      -     Index in the alphabet
            0x                    -     Get that many zeros
                                       If the element was [x], this yields []
                                       If the element was [L, x], this returns 1, 2 or 3 zeros, depending on L
       ×                          -   Multiple elementwise, zeroing the first 1,2 or 3 elements in the range if L is in the element
                Ṗ                 - Remove the trailing [] element
                 z0               - Transpose, padding with zeros
                   Ṛ              - Reverse
                    ị“XXXOOoo...  - Index into "XXXOOoo... "

```
> 2 votes

# Answer
# Perl 6, 93 bytes

```
{for 9...0 ->\n {say .subst(/(\D)?(.)/,{'XXXOOoo... '.comb[$1>=n>=ord($0//0)-96??n!!10]}):g}}

```

A block that takes in the string and prints to stdout.

Try it online!
> 1 votes

# Answer
# Japt `-R`, 36 bytes

```
óÈ¦nÃ£ÒXÌ î"XXXOOoo..."hSpXÎnD)s9Ãz3

```

Try it

```
óÈ¦nÃ£ÒXÌ î"..."hSpXÎnD)s9Ãz3     :Implicit input of string
ó                                 :Partition at
 È                                :Characters that return true when passed through the following function
  ¦                               :  Test for inequality with
   n                              :  Convert to number
    Ã                             :End function
     £                            :Map each X
      Ò                           :  Bitwise increment
       XÌ                         :  Last character of X
          î                       :  Slice the following to that length
           "..."                  :    Literal string
                h                 :    Replace as many characters as necessary at the start of that string with
                 S                :      Space
                  p               :      Repeat
                   XÎ             :        First character of X
                     n            :        Convert from base
                      D           :        14
                       )          :      End repeat
                        s9        :      Slice off the first 9 characters
                          Ã       :End map
                           z3     :Rotate clockwise by 90 degrees 3 times
                                  :Implicit output, joined by newlines

```
> 1 votes

# Answer
# 05AB1E (legacy), 34 bytes

```
Rvy.ïi"XXXOOoo..."y>£ëðAykÝǝ])ζRí»

```

Uses the legacy version of 05AB1E to save 2 bytes, since `ζ` also works on strings instead of just lists of characters.

Try it online.

**Explanation:**

```
R                  # Reverse the (implicit) input-string
 v                 # Loop `y` over each character:
  y.ïi             #  If `y` is a digit:
      "XXXOOoo..." #   Push string "XXXOOoo..."
        y>£        #   And only leave the first `y`+1 characters as substring
     ë             #  Else (`y` is a letter):
       Ayk         #   Get the index of `y` in the lowercase alphabet
          Ý        #   Create a list in the range [0, alphabet-index]
      ð    ǝ       #   Replace in the string at the top of the stack the characters at
                   #   those indices with a space
 ]                 # Close the if-else statement and loop
  )                # Wrap all strings on the stack into a list
   ζ               # Zip/transpose; swapping rows/columns
    Rí             # Reverse this list, as well as each individual line
      »            # And join the strings by newlines
                   # (after which the result is output implicitly)

```

As for my favorite 'building', let's go with this tree. ;)

```
b2b3b4b5b6b7898b7b6b5b4b3b2

       .
      ...
     .....
    ooooooo
   ooooooooo
  OOOOOOOOOOO
 OOOOOOOOOOOOO
XXXXXXXXXXXXXXX
      XXX
      XXX

```
> 1 votes

# Answer
# APL (Dyalog Extended), 67 bytes

```
{⊖⍉↑(((' '⍴⍨2⊃⊢),'XXXOOoo...'↑⍨1+⊃)∘⌽0,48|⎕UCS)¨'[abc]?\d'⎕S'\0'⊢⍵}

```

Try it online!

Longer than the other answer, but I'll try golfing it later. Proper explanation coming soon.

* `'[abc]?\d'⎕S'\0'⊢⍵` \- Extract single digits or characters followed by digits
* `(((' '⍴⍨2⊃⊢),'XXXOOoo...'↑⍨1+⊃)∘⌽0,48|⎕UCS)¨` \- Train to turn each digit or pair into a horizontal string
* `⊖⍉↑` \- Turn it into a matrix, transpose to make it vertical, and flip it upside-down.
> 1 votes

# Answer
# Pip `-l`, 45 bytes

```
Z:R{sXtRAb:Ab%4\,c"XXXOOoo..."@b}MRaC KXL.CXD

```

Takes input as a command-line argument. Try it here! Or, here's a 46-byte equivalent in Pip Classic: Try it online!

### Explanation

High-level:

```
  R{sXtRAb:Ab%4\,c"XXXOOoo..."@b}              Apply this function
                                 MR            to each match
                                    C KXL.CXD  of this regex
                                   a           in the input string
Z:                                             Transpose the result
                                               Autoprint as lines (-l flag)

```

The regex:

```
   XL       Lowercase letter            [a-z]
  K         Apply Kleene star           [a-z]*
C           Wrap in a capturing group   ([a-z]*)
       XD   Digit                       \d
      C     Wrap in a capturing group   (\d)
     .      Concatenate                 ([a-z]*)(\d)

```

The replacement function takes three arguments: `a` is the full match, `b` is the first capturing group (a letter or empty string), `c` is the second capturing group (a digit).

```
R{sXtRAb:Ab%4\,c"XXXOOoo..."@b}
  s                              Space character
   Xt                            repeated 10 times
         Ab                      ASCII code of the letter (nil if empty string)
           %4                    Mod 4 ("a"->1, "b"->2, "c"->3, ""->nil)
             \,c                 Inclusive range from that number to the digit
                                 (treats a left argument of nil as 0)
       b:                        Assign that value to b
     RA                          and replace those indices in the space string
                "XXXOOoo..."@b   with the equivalent indices in this string
R                                Reverse to put the "top" of the building at the left

```
> 1 votes

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