title: All Binary Combinations to Decimal

text:
# Question
Title: All Binary Combinations to Decimal
**Disclaimer**

This question is not a duplicate of this question. I'm not counting specific digits, as we already have those set in the initial parameters. This question is focusing on the decimal numbers that can be constructed from the binary strings based on the digits provided.

**Challenge**

Given two integers `X` and `Y`, representing the number of zeroes (`0`) and ones (`1`) respectively, calculate all the possible decimal equivalents that can be determined from creating binary strings using only the zeroes and ones provided, and display them as output.

**Example 1:**

Input: `0 1`

Output: `1`

Explanation: Only one `1` to account for, which can only be converted one way.

**Example 2:**

Input: `1 1`

Output: `1,2`

Explanation: `01` converts to 1, `10` converts to 2.

**Example 3:**

Input: `3 2`

Output: `3,5,6,9,10,12,17,18,20,24`

Explanation: Three `0`s and two `1`s make `00011` (3), `00101` (5), `00110` (6), `01001` (9), `01010` (10), `01100` (12), `10001` (17), `10010` (18), `10100` (20), `11000` (24)

**Limitations and Rules**

* I will only expect your code to work where `0 < X + Y <= 16` so the maximum number in the output could only occur from 16 `1`s, i.e. parameters `0` and `16`.
* As a result of the above limitation, the range of numbers we'd expect in the output are from `0` and `65535`.
* I will accept functions or code, so long as the resulting output is provided, whether this be a comma separated list, an array, list outputted to STDOUT, etc. The only criteria I must stress about the output is that it **must** be sorted.
* This is code golf, minimum bytes will receive maximum glory.
* We will not tolerate silly loopholes

# Answer
# Jelly, 8 bytes

```
0,1xŒ!ḄQ

```

Try it online!

### How it works

```
0,1xŒ!ḄQ Main link. Argument: [x, y]

0,1x     Repeat 0 x times and 1 y times.
    Œ!   Compute all permutations of the result.
      Ḅ   Unbinary; convert each permutation from base 2 to integer.
       Q  Unique; deduplicate the results.

```
> 5 votes

# Answer
# Python, 60 bytes

```
lambda x,y:[n for n in range(1<<x+y)if bin(n).count('1')==y]

```

Test it on Ideone.

### How it works

All positive numbers that can be represented in binary with **x** zeroes and **y** ones is clearly smaller than **2x + y**, since the canonical binary representation of the latter has **x + y + 1** digits.

The lambda simply iterates over the integers in **\[0, 2x + y)** and keeps all integers **n** in that range that have **y** ones. Since **n \< 2x + y** is can be represented with **x** (or less) zeroes.
> 7 votes

# Answer
# Mathematica, ~~59~~ 57 bytes

A usual outcome with Mathematica: high-level functions = good, long function names = bad.

```
#+##&~Fold~#&/@Permutations@Join[0&~Array~#,1&~Array~#2]&

```

`Join[0&~Array~#,1&~Array~#2]` creates a list with the correct number of `0`s and `1`s. `Permutations` generates all permutations of that list, without repetitions (as I learned) and in sorted order. `#+##&~Fold~#` (a golfuscated version of `#~FromDigits~2`) converts a list of base-2 digits into the integer they represent.

Previous version, before Martin Ender's comment:

```
#~FromDigits~2&/@Permutations@Join[0&~Array~#,1&~Array~#2]&

```
> 5 votes

# Answer
## CJam (15 14 bytes)

```
{As.*s:~e!2fb}

```

This is an anonymous block (function) which takes input as an array `[number-of-ones number-of-zeros]` and returns output as an array.

Online demo

---

A long way off the mark, but more interesting: this is without permutation builtins or base conversion:

```
{2\f#~1$*:X;[({___~)&_2$+@1$^4/@/|_X<}g;]}

```

It would work nicely as a GolfScript unfold.
> 5 votes

# Answer
# Japt, 16 bytes

```
'0pU +'1pV)á mn2

```

Test it online!

### How it works

```
                  // Implicit: U = first integer, V = second integer
'0pU              // Repeat the string "0" U times.
     +'1pV)       // Concatenate with the string "1" repeated V times.
           á      // Take all unique permutations.
             mn2  // Interpret each item in the resulting array as a binary number.
                  // Implicit: output last expression

```

### Alternate version, 17 bytes

```
2pU+V o f_¤è'1 ¥V
                   // Implicit: U = first integer, V = second integer
2pU+V              // Take 2 to the power of U + V.
      o            // Create the range [0, 2^(U+V)).
        f_         // Filter to only items where
           è'1     //  the number of "1"s in
          ¤        //  its binary representation
               ¥V  //  is equal to V.
                   // Implicit: output last expression

```

I've been trying to further golf both versions, but I just can't find any slack...
> 4 votes

# Answer
# Pyth - 11 bytes

```
{iR2.psmVU2

```

Test Suite.

```
{                Uniquify
 iR2             Map i2, which converts from binary to decimal
  .p             All permutations
   s             Concatenate list
    mV           Vectorized map, which in this case is repeat
     U2          0, 1
     (Q)         Implicit input

```
> 3 votes

# Answer
# Ruby, 63 bytes

A simple implementation. Golfing suggestions welcome.

```
->a,b{(?0*a+?1*b).chars.permutation.map{|b|(b*'').to_i 2}.uniq}

```

**Ungolfing**

```
def f(a,b)
  str = "0"*a+"1"*b                   # make the string of 0s and 1s
  all_perms = str.chars.permutation   # generate all permutations of the 0s and 1s
  result = []
  all_perms.do each |bin|             # map over all of the permutations
    bin = bin * ''                    # join bin together
    result << bin.to_i(2)             # convert to decimal and append
  end
  return result.uniq                  # uniquify the result and return
end

```
> 3 votes

# Answer
# Python 2 - ~~105~~ 99 bytes

+8 bytes cos our output needs to be sorted

```
lambda x,y:sorted(set(int("".join(z),2)for z in __import__('itertools').permutations("0"*x+"1"*y)))

```
> 2 votes

# Answer
## Mathematica, 47 bytes

```
Cases[Range[2^+##]-1,x_/;DigitCount[x,2,1]==#]&

```

An unnamed function taking two arguments: number of `1`s, number of `0`s.

Essentially a port of Dennis's Python solution. We create a range from `0` to `2<sup>x+y</sup>-1` and then keep only those numbers whose amount of `1`-bits equals the first input. The most interesting bit is probably the `2^+##` which uses some sequence magic to avoid the parentheses around the addition of the two arguments.
> 2 votes

# Answer
## MATLAB 57 + 6

```
@(a,b)unique(perms([ones(1,a) zeros(1,b)])*2.^(0:a+b-1)')

```

run using

```
ans(2,3)

```

ungolfed

```
function decimalPerms( nZeros, nOnes )
  a = [ones(1,nOnes) zeros(1,nZeros)];  % make 1 by n array of ones and zeros
  a = perms(a);                         % get permutations of the above
  powOfTwo = 2.^(0:nOnes+nZeros-1)';    % powers of two as vector
  a = a * powOfTwo;                     % matrix multiply to get the possible values
  a = unique(a)                         % select the unique values and print

```
> 2 votes

# Answer
# MATL, 9 bytes

```
y+:<Y@XBu

```

Try it online!

### Explanation

The approach is similar to that in Dennis' Jelly answer.

```
y     % Implicitly take two inputs (say 3, 2). Duplicate the first.
      %   STACK: 3, 2, 3
+     % Add
      %   STACK: 3, 5
:     % Range
      %   STACK: 3, [1 2 3 4 5]
<     % Less  than
      %   STACK: [0 0 0 1 1]
Y@    % All permutations
      %   STACK: [0 0 0 1 1; 0 0 0 1 1; ...; 0 0 1 0 1; ...; 1 1 0 0 0]
XB    % Binary to decimal
      %   STACK: [3 3 ... 5 ... 24]
u     % Unique
      %   STACK: [3 5 ... 24]
      % Implicitly display

```
> 2 votes

# Answer
# JavaScript (Firefox 48), ~~85~~ ~~76~~ ~~74~~ ~~71~~ 70 bytes

Saved 3 bytes thanks to @Neil.

```
(m,n,g=x=>x?g(x>>1)-x%2:n)=>[for(i of Array(1<<m+n).keys())if(!g(i))i]

```

Array comprehensions are awesome. Too bad they haven't made it into official ECMAScript spec yet.

# JavaScript (ES6), ~~109~~ ~~87~~ ~~79~~ ~~78~~ ~~71~~ 70 bytes

```
(m,n,g=x=>x?g(x>>1)-x%2:n)=>[...Array(1<<m+n).keys()].filter(x=>!g(x))

```

Should work in all ES6-compliant browsers now. Saved 7 bytes on this one, also thanks to @Neil.
> 1 votes

# Answer
# Actually, 21 bytes

A port of my Ruby answer. Golfing suggestions welcome. Try it online!

```
│+)'1*@'0*+╨`εj2@¿`M╔

```

**How it works**

```
          Implicit input of a and b.
│+)       Duplicate a and b, add, and rotate to bottom of stack. Stack: [b a a+b]
'1*@      "1" times b and swap with a.
'0*+      "0" times a and add to get "0"*a+"1"*b.
╨`...`M   Take all the (a+b)-length permutations of "0"*a+"1"*b
          and map the following function over them.
  εj        Join the permutation into one string
  2@¿       Convert from binary to decimal
╔         Uniquify the resulting list and implicit return.

```
> 1 votes

# Answer
# Groovy 74 Bytes, 93 Bytes or 123 Bytes

I don't know which one you consider more fully answers the question but...

## 74 Byte Solution

```
{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().unique()}(1,2)

```

For an input of 1,2 you get:

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

```

## 93 Byte Solution

```
{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().collect{it.join()}.unique()}(1,2)

```

For an input of 1,2 you get:

```
[101, 011, 110]

```

## 123 Byte Solution

```
{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().collect{it.join()}.unique().collect{Integer.parseInt(it,2)}}(1,2)

```

For an input of 1,2 you get:

```
[5, 3, 6]

```

Try it out here:

https://groovyconsole.appspot.com/edit/5143619413475328
> 1 votes

# Answer
# Groovy 80 Bytes

based on the answer by @carusocomputing

his 123 Byte solution can be compressed into 80 Bytes:

## 80 Byte Solution

```
{a,b->([0]*a+[1]*b).permutations()*.join().collect{Integer.parseInt(it,2)}}(1,2)

```

For an input of 1,2 you get:

```
[5, 3, 6]

```
> 1 votes

# Answer
# C (gcc), ~~72~~ 68 bytes

```
f(a,b){for(a=1<<a+b;a--;)__builtin_popcount(a)^b||printf("%d\n",a);}

```

Try it online!

Unfortunately there is no popcount() in the standard library, but it is provided as a "builtin function" by GCC. The output is sorted, but in reverse order.

Thanks to @ceilingcat for shaving off 4 bytes!
> 1 votes

# Answer
# Japt, 10 bytes

```
ËçEÃ¬á mÍâ

```

Try it

```
ËçEÃ¬á mÍâ     :Implicit input of array
Ë              :Map each D at 0-based index E
 çE            :  Repeat E D times
   Ã           :End map
    ¬          :Join
     á         :Permutations
       m       :Map
        Í      :  Convert from binary string to integer
         â     :Deduplicate

```
> 1 votes

# Answer
# PHP, 80 or 63 bytes

depending on wether I must use `$argv` or can use `$x` and `$y` instead.

```
for($i=1<<array_sum($argv);$i--;)echo$argv[2]-substr_count(decbin($i),1)?_:$i._;

```

prints all matching numbers in descending order delimited by underscores.
filename must not begin with a digit.

**no builtins, 88 or 71 bytes**

```
for($i=1<<array_sum($argv);$i--;print$c?_:$i._)for($n=$i,$c=$argv[2];$n;$n>>=1)$c-=$n&1;

```

---

add one byte each for only one underscore after every number.

@WallyWest: You were right. Saves 3 bytes for me from `for($i=-1;++$i<...;)`
> 0 votes

# Answer
# Perl 6,  ~~64 62~~  49 bytes

```
{(0 x$^a~1 x$^b).comb.permutations.map({:2(.join)}).sort.squish}

```

```
{[~](0,1 Zx@_).comb.permutations.map({:2(.join)}).sort.squish}

```

```
{(^2**($^x+$^y)).grep:{.base(2).comb('1')==$y}}

```

## Explanation:

```
# bare block lambda with two placeholder parameters ｢$^x｣ and ｢$^y｣
{
  # Range of possible values
  # from 0 up to and excluding 2 to the power of $x+$y
  ( ^ 2 ** ( $^x + $^y ) )

  # find only those which
  .grep:

  # bare block lambda with implicit parameter of ｢$_｣
  {

    # convert to base 2
    # ( implicit method call on ｢$_｣ )
    .base(2)

    # get a list of 1s
    .comb('1')

    # is the number of elements the same
    ==

    # as the second argument to the outer block
    $y
  }
}

```

```
say {(0..2**($^x+$^y)).grep:{.base(2).comb('1')==$y}}(3,2)
# (3 5 6 9 10 12 17 18 20 24)

```
> 0 votes

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


title: Output an ASCII "splat"

text:
# Question
Title: Output an ASCII "splat"
If you throw an ASCII egg in a given direction, you end up with an **ASCII splat of size *n***. It "starts" with one `o` (the yolk), and continues in a given direction with "lines" consisting of 2 up to *n* `*`'s. The `*`'s are separated by one "space", and the `o` and all the "lines" of `*`'s are separated by "lines" of "space".

The direction of the splat can be any one of eight directions from `o`, for example:

```
1 2 3
4 o 5
6 7 8

```

Here are examples of ASCII splats of size 4 in directions `5`, `2` and `3` respectively. On the left is the actual ASCII splat, and on the right is the same splat but with the "lines" of "space" replaced with actual "lines" (i.e. `-` or `\` or `|` depending on the direction) just to clarify what is meant by a "line" of space.

```
Size 4, direction 5
      *      | | |*
    *        | |*|
  *   *      |*| |*
o   *       o| |*|
  *   *      |*| |*
    *        | |*|
      *      | | |*

Size 4, direction 2
* * * *     * * * *
            -------
 * * *       * * *
            -------
  * *         * *
            -------
   o           o

Size 4, direction 3
*           *
            \
* *         *\*
            \ \
* * *       *\*\*
            \ \ \
o * * *     o\*\*\*

```

## Challenge

Given *n ≥ 1* and one of the 8 possible directions, write a function or program that outputs the ASCII splat of size *n* in the given direction.

## Input and output

Any consistent, reasonable input format is allowed. You don't need to map directions to the integers 1 to 8 in the same way I did - if some other way of specifying the direction is easier, go ahead. But say what you did if it isn't clear.

The output will consist of `o`, `*`, spaces (U+0020) and newlines (U+000A) that produce the ASCII splat. Leading, trailing, otherwise extra whitespace is permitted on any line.

## Rules

This is . Standard rules apply.

### More examples

```
Size 1, any direction
o

Size 3, direction 6
* * o

  * *

    *

Size 5, direction 7
    o

   * *

  * * *

 * * * *

* * * * *

```

# Answer
> 3 votes
# Charcoal, ~~20~~ 18 bytes

```
↘ＥＮ×*⊕ιＭ↗oＵＥ¬﹪η²⟲η

```

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

```
↘ＥＮ×*⊕ι

```

Draw a diagonal triangle of splats.

```
Ｍ↗o

```

Place the egg.

```
ＵＥ¬﹪η²

```

For even rotations, expand the splat horizontally to match the output requirement. This requirement doesn't match Charcoal's usual expectations. Try it online! (verbose) for how it looks without.

```
⟲η

```

Rotate the splat as required, using the following code for directions:

```
321
4o0
567

```

This ~~37~~ 31-byte version avoids extraneous whitespace by only rotating in right angles:

```
¿﹪η²Ｇ↘←θ*«↘Ｅθ×*⊕ι↗»oＵＥ¹﹪η²⟲⊗÷η²

```

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

# Answer
> 2 votes
# Jelly, 37 bytes

```
”*ẋK¥ⱮmṠ©}”oḷ""LḶ⁶ẋƲ;"ṚƊ®¡z⁶K€ZU$A}¡Y

```

Try it online!

Directions:

\\$\left\[\begin{array}c1&2&3\\4&\circ&5\\6&7&8\end{array}\right\]\rightarrow\left\[\begin{array}c-2&1&-3\\4&\circ&2\\\-1&3&-4\end{array}\right\]\\$

# Answer
> 2 votes
# Canvas, 25 bytes

```
Ｈ*×］oｎ╶２％？！／ ＊］ ＊／｝⤢ ＊⁷⇵⟳

```

Try it here!

The directions are as follows:

```
7 6 1
4 ∘ 8
5 2 3

```

# Answer
> 1 votes
# Python 2, 185 bytes

```
lambda n,d:'\n'.join(g([(d/4*(n+~j)*' '+('*o'[[j>n-2,j<1][d/4]]+' *'*j)*i).ljust(2*n-1)for j in range(n)for i in(0,1)][1:],d%4))
g=lambda a,n:n and g(map(''.join,zip(*a))[::-1],n-1)or a

```

Try it online!

The numbering is from 0 to 7, as follows:

```
1 6 0
7 o 5
2 4 3

```

Notes: Most of the work is to generate the basic patterns for (in my numbering system) `0` and `4`. Then the function `g` rotates the array `a` 90 degrees `d%4` times via recursion to generate the other results.

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


title: Draw some mountain peaks

text:
# Question
Title: Draw some mountain peaks
Write a program or function that draws a mountain range, where each subsequent larger mountain peak is "behind" the ones in front, and alternates which side is visible.

This is a mountain range of size `1`

```
/\

```

This is a mountain range of size `2`

```
 /\
/\ \

```

This is a mountain range of size `3`

```
  /\
 / /\
/ /\ \

```

This is a mountain range of size `4`

```
   /\
  /\ \
 / /\ \
/ /\ \ \

```

This is a mountain range of size `5`

```
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \

```

And so on.

### Input

A single positive integer in any convenient format, `n > 0`.

### Output

An ASCII-art representation of the mountain range, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the peaks line up appropriately.

### Rules

* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
## Charcoal, 16 bytes

```
ＮλＦλ«Ｐ↘⁻λι←↙¹‖Ｔ→

```

Try it online!

### How?

`Ｎλ` inputs the size of the largest mountain into `λ`. `Ｆλ«` runs a loop over values of `ι` from `0` through `λ-1`. (The closing `»` is implied at the end of the program.)

Inside the loop, `Ｐ↘⁻λι` calculates `λ-ι` and draws, without moving the cursor afterward, a line of that length going southeast. Based on its direction, this line will consist of `\` characters.  moves one step to the west, and `↙¹` draws a line of length 1 going southwest (made of `/`). Finally, `‖Ｔ→` horizontally reflects the drawing, transforming characters as appropriate: `\` becomes `/` and `/` becomes `\`.

Adding the dump instruction  at the beginning of the loop (try it) allows us to see the progression:

```
    /\
   /
  /
 /
/
    /\
   /\ \
  /    \
 /      \
/        \
    /\
   / /\
  / /\ \
 / /    \
/ /      \
    /\
   /\ \
  / /\ \
 / /\ \ \
/ /    \ \
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \

```
> 15 votes

# Answer
# JavaScript (ES6), 75 bytes

```
for(n=prompt(s="/\\");n--;s=n%2?s+' \\':'/ '+s)console.log(" ".repeat(n)+s)

```

The full program is currently slightly shorter than the recursive function:

```
f=n=>n?" ".repeat(--n)+`/\\
`+f(n).replace(/\S.+/g,x=>n%2?x+" \\":"/ "+x):""

```
> 7 votes

# Answer
## Python 2, 67 bytes

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

```

Prints line by line, accumulating the string `s` by alternately adding a slash to the left or right based on the current parity of `n`. Prefixes with `n` spaces.

An alternative way to update was the same length:

```
s=n%2*'/ '+s+~n%2*' \\'
s=['/ '+s,s+' \\'][n%2]

```

A recursive method was longer (70 bytes).

```
f=lambda n,s='/\\':n*'_'and' '*~-n+s+'\n'+f(n-1,[s+' \\','/ '+s][n%2])

```
> 6 votes

# Answer
## Haskell, 77 bytes

```
0%_=""
n%s=(' '<$[2..n])++s++'\n':(n-1)%(cycle[s++" \\","/ "++s]!!n)
(%"/\\")

```

Usage:

```
putStrLn $ f 5
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \

```

Prints line by line, accumulating the string s by alternately adding a slash to the left or right based on the current parity of n. Prefixes with n-1 spaces.
> 6 votes

# Answer
# Haskell, ~~117 107 105 97~~ 90 bytes

```
b!1=["/\\"]
b!n|m<-(1-b)!(n-1)=map(' ':)m++[[("/ "++),(++" \\")]!!b$last m]
(unlines.(1!))

```

Try it on Ideone. Edit: Saved 8 bytes with an idea from Neil.

Ungolfed version:

```
p b 1 = ["/\\"]
p b n = let m = p (1-b) (n-1)
            k = last m
            r = map (' ':) m
        in if b == 1
           then r ++ [k ++ " \\"]
           else r ++ ["/ " ++ k]
f n = unlines(p 1 n)

```

Recursive approach. The shape for `n` is generated by adding a space in front of each line of the `n-1` shape and taking the last line of `n-1` and add `"/ "` before if `n` is odd or `" \"` after if `n` is even ... or so I thought before noticing that this last step is reversed for all recursive steps when the final `n` is odd. Therefore a flag `b` is passed which alternates each recursive call and determines if the next mountain part is added left or right.
> 5 votes

# Answer
## Batch, 202 bytes

```
@echo off
set/af=%1^&1
set m=/\
set s=
for /l %%i in (2,1,%1)do call set s= %%s%%
for /l %%i in (2,1,%1)do call:l
:l
echo %s%%m%
set s=%s:~1%
set/af^^=1
if %f%==1 (set m=%m% \)else set m=/ %m%

```

Takes input as a command-line parameter. Falls through to execute the last loop.
> 5 votes

# Answer
# Ruby, 61 bytes

A pretty straightforward port of ETHproductions' JavaScript answer.

```
->n{s="/\\"
(puts" "*n+s
s=n%2>0?s+" \\":"/ "+s)until 0>n-=1}

```

See it on repl.it: https://repl.it/EPU5/1

## Ungolfed

```
->n{
  s = "/\\"
  ( puts " "*n+s
    s = n%2 > 0 ? s+" \\" : "/ "+s
  ) until 0 > n -= 1
}

```
> 5 votes

# Answer
# Java 7,130 bytes

```
String f(int n,String s){String l="";for(int i=1;i++<n;l+=" ");return n>1?n%2<1?l+s+"\n"+f(--n,s+" \\"):l+s+"\n"+f(--n,"/ "+s):s;}

```

# Ungolfed

```
class Mountain {
 public static void main(String[] args) {
    System.out.println(f( 5 , "/\\" ) );
  }
 static String f(int n,String s){
    String l = "";
    for (int i = 1; i++ < n; l += " ") ;
      return n > 1? n % 2 < 1?l + s + "\n" + f(--n , s + " \\")
                           :l + s + "\n" + f(--n , "/ " + s)
                            :s;
    }

}

```
> 2 votes

# Answer
# Canvas, 7 bytes

```
Ｈ＼║ｎ↔｝↕

```

Try it here! I guess Canvas is now the ideal language for this challenge.
> 1 votes

# Answer
# C++ 138(function)

Function :-

```
#define c(X) cout<<X;
#define L(X,Y) for(X=0;X<Y;X++)

void M(int h){int l=1,r=1,j,H=h,i;L(i,h){for(j=H;j>0;j--)c(" ")L(j,l)c(" /")L(j, r)c("\\ ")c("\ n")(h%2)?(i%2)?r++:l++:(i%2)?l++:r++;H--;}

```

Full program :-

```
#include<conio.h>
#include<iostream>

using namespace std;

#define c(X) cout<<X;
#define L(X,Y) for(X=0;X<Y;X++)

void M(int h)
{
    int l=1,r=1,j,H=h,i;

    L(i, h)
    {
        for (j = H;j > 0;j--)
            c(" ")
        L(j, l)
            c(" /")
        L(j, r)
            c("\\ ")
        c("\n")

        (h % 2) ? (i % 2) ? r++ : l++ :(i % 2) ? l++ : r++;
        H--;
    }
}

int main()
{
    int h;
    cin >> h;
    M(h);
    _getch();
    return 0;
}

```

**NOTE :** the function `_getch()` may have different prototype names across different compilers.
> 0 votes

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


title: Sums of digits 1 through 7

text:
# Question
Title: Sums of digits 1 through 7
# Challenge

Given a positive integer `N` that is 28 or above, output a list of numbers summing to `N` that uses each digit `1` through `7` exactly once. You can give as a program or function.

The digits can appear by themselves or concatenated, as long as you use each of them once without repeats. For example,`[12, 34, 56, 7]` is valid, as is `[1, 27, 6, 4, 35]` and `[1234, 567]`, but not `[123, 34567]` or `[3, 2, 1476]`. The order that the numbers are listed does not matter.

If `N` cannot be made with 1-7, return or output nothing.

# Other information

* This is code golf, so the shortest code in bytes by Thursday the 15th of October wins.
* Ask any questions in the comments.
* Anything I do not specify in the challenge is up to you.
* Standard loopholes are disallowed.

# Examples

These may clear any confusion up:

Input

```
28

```

Output

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

```

Input

```
100

```

Output

```
[56, 7, 4, 31, 2]

```

Input

```
1234567

```

Output

```
[1234567]

```

Input

```
29

```

Output

Nothing, 29 is invalid.

Input

```
1891

```

Output

```
[1234, 657]

```

Input

```
370

```

Output

```
[15, 342, 7, 6]

```

I'll make more if needed.

Here's a pastebin of all of the possible numbers created with these seven numbers, courtesy of FryAmTheEggman.

# Answer
# Pyth, ~~18~~ 14 bytes

```
hfqSjkTjkS7./Q

```

*Thanks to @isaacg for golfing off 2 bytes and paving the way for 2 more.*

The code will crash if it should produce no output, which causes no output to be produced.

This will work for small-ish inputs if you're patient enough, and for larger ones if given enough time and memory.

To verify that the code works as intended, you can replace the `7` with a `3` for *sums of digits 1 through 3*. Click here for a test suite.

### Example runs

```
$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 28
(1, 2, 3, 4, 5, 6, 7)

real    4m34.634s
user    4m34.751s
sys     0m0.101s
$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 29 2>/dev/null

real    9m5.819s
user    9m6.069s
sys     0m0.093s

```

### How it works

```
           ./Q    Compute all integer partitions of the input.
 f                Filter the integer partitions:
    jkT             Join the integers with empty separator.
   S                Sort the characters of the resulting string.
      jkS7          Join [1, ..., 7] with empty separator.
  q                 Check both results for equality.
                  Keep the partition of `q' returned True.
h                 Retrieve the first element of the filtered list.
                  For a non-empty list, this retrieves the solution.
                  For the empty list, it causes an error and produces no output.

```
> 10 votes

# Answer
## Python 3, 109

```
def f(n,s=set('1234567'),l='0,'):[f(n,s-{x},l+x+c)for c in(',','')for x in s]or n-sum(eval(l))or~print(l[2:])

```

A function that takes a number and outputs a tuple in the like `123,4567,`. Yes, this is a valid tuple.

The idea is to generate all possible strings like `43,126,7,5,` that have the digits `1` through `7` separated by commas, with no two commas consecutive. Evaluate this expression as a tuple, and its sum equals `n`, print it and terminate with error.

To build all such strings, we track the set `s` of chars to use, and try appenping each one either with a comma, which makes the digit end the entry, or without, in which case future digits will concatenate onto it.

Short-circuiting is used to check that `s` is empty because the list-comp is empty, and that `n==sum(eval(l))`, in which case we print `l` and terminate with an error by taking `~` of the `None` returned by printing (thanks to Sp3000 for this.).

I believe that in Python 3.5, two chars can be saved by writing `s={*'1234567'}` (thanks Sp3000).

There's some small annoyances that eat up chars. One is that in the case that `l` looking like `1234567` with no commas, it is parsed as a single number and calling `sum` gives an error. This is handled with the hack of starting `l` with the element `0` and stripping it when printing. This costs 6 chars.

Iterating `c` over the comma and the empty string is annoyingly wordy `for c in(',','')`, since Python 3 doesn't allow this tuple to be naked. I'd like there to be some char `?` that is ignored in numbers to do `',?'` for 4 chars less, but there doesn't seem to be such a char.

---

Old method:

**Python 2, 117**

```
def f(n,s={1,2,3,4,5,6,7},l=[],p=0):
 if{n,p}|s=={0}:print l;1/0
 if p:f(n-p,s,l+[p])
 for x in s:f(n,s-{x},l,p*10+x)

```

Defines a function that takes a number and prints a list.

The idea is to use recursion to try every branch. The variables track are

* The remaining sum `n` needed
* The set of digits `s` remaining to use
* The list `l` of numbers made so far
* The current partially-formed number `p`

When `n==0` and `s` is empty, print `l` and terminate by error.

If the current partially-formed number `p` is non-zero, try adding it to the list and removing it from the remaining sum.

For each digit `x` we can use from `s`, try appending it to `p` and removing it from `s`.
> 5 votes

# Answer
# Pyth, 23

```
#iRThfqQsiR10Ts./M.pS7q

```

Naive brute force, too slow online, takes about a minute on my computer. Uses the common "loop forever until exception" pattern of pyth golfs where accessing the resulted filtered list of combinations causes an error for impossible numbers, like `29`.

Outputs like a pythonic list, e.g.

```
1891
[1234, 657]
100
[1, 2, 34, 56, 7]
370
[12, 345, 6, 7]

```

Here is a paste of all of the 10136 numbers that can be made this way.
> 4 votes

# Answer
# JavaScript (ES6), 165 ~~196~~

**Edit** Shortened a little. Could be shorter using `eval`, but I like it being fast

Brute force, shamefully longer than Pith version, but faster. Test running the snippet below in an EcmaScript 6 compliant browser.

```
f=z=>{for(r=i=1e6;r&&++i<8e6;)for(m=/(.).*\1|[089]/.test(w=i+'')?0:64;r&&m--;t.split`+`.map(v=>r-=v,r=z))for(t=w[j=0],l=1;d=w[++j];l+=l)t+=l&m?'+'+d:d;return r?'':t}

function test() { O.innerHTML=f(+I.value) }

test()

// Less golfed

f=z=>{
  for(r=i=1e6; r&&++i<8e6;)
    for(m=/(.).*\1|[089]/.test(w=i+'')?0:64; r&&m--; t.split`+`.map(v=>r-=v,r=z))
      for(t=w[j=0],l=1;d=w[++j];l+=l)
        t+=l&m?'+'+d:d;
  return r?'':t
}
```

```
<input id=I value=28><button onclick=test()>-></button><span id=O></span>
```
> 3 votes

# Answer
# Python 2.7, ~~178~~ ~~172~~ 169 bytes

```
n=input()
for i in range(8**7):
 for j in len(set('%o0'%i))/8*range(128):
    s=''
    for c in'%o'%i:s+='+'[:j%2*len(s)]+c;j/=2
    if eval(s)==n:print map(int,s.split('+'));1/0

```

Note that the last three lines are supposed to be indented with tabs but I can't figure out how to do so in this editor.

Edit: Flattened one layer of nesting with the help of Sp3000
> 3 votes

# Answer
# Python 2, ~~270~~ 268 bytes

```
from itertools import*;P=permutations
x,d,f=range(1,8),[],input()
r=sum([[int(''.join(str(n)for n in i))for i in list(P(x,j))]for j in x],[])
z=1
while z:
 t=sum([[list(j)for j in P(r,z)]for i in x],[])
 v=filter(lambda i:sum(i)==f,t)
 if v:print v[0];break
 else:z+=1

```

Still working on golfing.

This loops until a match is found.
> 1 votes

# Answer
# Haskell (145 bytes)

```
main=getLine>>=print.head.f[1..7].read
f[]0=[[]]
f b s=[n:j|(n,g)<-m b,j<-f g$s-n]
m b=[(d+10*z,g)|d<-b,(z,g)<-(0,filter(/=d)b):m(filter(/=d)b)]

```

Uses recursion.

Ungolfed (337 bytes):

```
delete d = filter (/= d)
main = getLine >>= print . (`form` [1..7]) . read

form s [] | s == 0    = [[]]
form s ds | s <= 0    = []
form s ds | otherwise = [n:ns | (n, ds') <- makeNumbers ds, ns <- form (s-n) ds']

makeNumbers [] = []
makeNumbers ds  = [(d + 10 * n',ds') | d <- ds, (n',ds') <- (0,delete d ds):makeNumbers (delete d ds)]

```
> 1 votes

# Answer
# Jelly, 12 bytes

```
ŒṗDẎṢ⁼ʋƇ7R¤Ḣ

```

Try it online!

Times out for pretty much all inputs. Outputs `0` if no such list exists. Requiring empty output adds 3 bytes.

This is a 14 byte (17 for empty output) answer which has a more or less constant runtime (~40 seconds).

## How they work

```
ŒṗDẎṢ⁼ʋƇ7R¤Ḣ - Main link. Takes n on the left
Œṗ           - Integer partitions of n
      ʋƇ     - Keep those for which the following is true:
  D          -   Convert to digits
   Ẏ         -   Flatten
    Ṣ        -   Sorted
     ⁼  7R¤  -   Equals [1, 2, 3, 4, 5, 6, 7]
           Ḣ - Take the first list

```

The 14 byte version:

```
7Œ!ŒṖ€ẎḌS=¥Ƈ⁸Ḣ - Main link. Takes n on the left
7              - Yield 7
 Œ!            - Get all permutations of [1, 2, 3, 4, 5, 6, 7]
     €         - Over each:
   ŒṖ          - Yield it's partitions
      Ẏ        - Flatten to a single list of all partitions
       Ḍ       - Convert from digits
          ¥Ƈ   - Keep those for which the following is true:
        S      -   Sum
         =  ⁸  -   Equals n
             Ḣ - Take the first list

```
> 1 votes

# Answer
# Scala, 195 bytes

This isn't the most efficient and it took over 15 minutes to get the output for 29 but it works

```
def g(s: Seq[Int]): Iterator[Seq[Int]]=s.combinations(2).map(c=>g(c.mkString.toInt +: s.filterNot(c.contains))).flatten ++ Seq(s)
def f(i: Int)=(1 to 7).permutations.map(g).flatten.find(_.sum==i)

```

Here is some output

```
scala> f(100)
res2: Option[Seq[Int]] = Some(Vector(46, 35, 12, 7))

scala> f(1891)
res3: Option[Seq[Int]] = Some(Vector(567, 1324))

scala> f(370)
res4: Option[Seq[Int]] = Some(Vector(345, 12, 6, 7))

scala> f(29)
res5: Option[Seq[Int]] = None

```
> 0 votes

# Answer
# Ruby, 105 bytes

Brute force! Checks every subset of lengths between 0 and 7 of the integers between 1 and 7654321 and sees if any of them matches our criteria. You probably don't want to wait for this to terminate.

```
->n{8.times{|i|[*1..7654321].permutation(i){|x|return x if
x.join.chars.sort==[*?1..?7]&&eval(x*?+)==n}}}

```

To run and verify the algorithm you can narrow down the search space by replacing `7654321` with the largest number you know will be in the answer. For instance, 56 for n=100, or 1234 for n=1891. Here's a trial run of the latter:

```
$ ruby -e "p ->n{8.times{|i|[*1..1234].permutation(i){|x|return x if x.join.chars.sort==[*?1..?7]&&eval(x*?+)==n}}}[gets.to_i]" <<< 1891
[657, 1234]

```
> 0 votes

# Answer
# Husk, 15 bytes

```
ḟȯ=ḣ7Oṁdfo=¹ΣṖḣ

```

Try it online!
> 0 votes

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


title: Combination bike lock

text:
# Question
Title: Combination bike lock
## The scenario

After a long day's work slogging in the office and browsing stackexchange.com, I finally walk out the door at 16:58, already weary with the day. Because I am still only an intern, my current mode of transportation is on bicycle. I head over to my trusty Peugeot Reynolds 501, but before I can sail away on it, I need to unlock it. The lock is a standard four digit combination lock (0-9), through the frame and the front wheel. As I try to stay awake, I pull my hand up to enter in the combination.

## The challenge

Because my fingers are so weary, I want to turn the lock to the correct combination with the fewest movements. One movement is defined as a rotation by one position (36 degrees), for example there is one movement from `5737` to `5738`. However, I am able to grasp **up to any three consecutive rings at the same time, and rotate them as one**, which only counts as a single movement. For example there is also **only one movement** from `5737` to `6837` or to `5626`. Moving from `5737` to `6838` is not one movement, as digits number 1,2 and 4 have moved in the same direction, but independently of digit number 3.

Therefore, for a given combination I can see on the bike lock (any 4-digit integer), what is the lowest number of movements I can make to get it unlocked, and yes, I can rotate in either direction at any time. By this I mean that I can turn some digits in one direction and other digits in the other direction: not all of my movements will be anitclockwise or clockwise for each unlock.

Because I am lazy, my unlock code is 0000.

~~This is code golf~~ I can't be bothered writing much code, so the shortest program in number of bytes wins.

Input is from stdin, and your code should output the combinations I can see at each step after each movement, including the 0000 at the end. Each of the combinations output should be separated by a space/newline/comma/period/ampersand.

## Examples

```
Input: 1210
0100
0000

Input: 9871
9870
0980
0090
0000

Input: 5555
4445&3335&2225&1115&0005&0006&0007&0008&0009&0000

Input: 1234
0124 0013 0002 0001 0000

```

I tried posting this on http://bicycles.stackexchange.com, but they didn't like it...

Disclaimer: First golf, so anything that is broken/any missing information let me know! Also I did all the examples by hand, so there may be solutions which involve less movements!

EDIT: For answers which have multiple solution paths with equal number of movements (practically all of them), there is no preferred solution.

# Answer
> 10 votes
# Matlab, ~~412~~ 327 bytes

Golfed (Thanks to @AndrasDeak for golfing `s`!):

```
s=dec2bin('iecbmgdoh'.'-97)-48;s=[s;-s];T=1e4;D=Inf(1,T);P=D;I=NaN(T,4);for i=1:T;I(i,:)=sprintf('%04d',i-1)-'0';end;G=input('');D(G+1)=0;for k=0:12;for n=find(D==k);for i=1:18;m=1+mod(I(n,:)+s(i,:),10)*10.^(3:-1:0)';if D(m)==Inf;D(m)=k+1;P(m)=n-1;end;end;end;end;n=0;X='0000';while n-G;n=P(n+1);X=[I(n+1,:)+48;X];end;disp(X)

```

This codes uses some dynamic programming for finding the shortest 'path' from the given number to `0000` using only the possible steps. The challenge is basically a shortest path prioblem (alternatively you could perhaps consider the steps as a commutatuve group.) but the difficulty was coming up with an *efficient* implementation. The basic structures are two 10000-element arrays, one for storing the number of steps to get to that index, the other one to store a pointer to the previous 'node' in our graph. It simultaneously calculates the 'paths' to all other possible numbers.

Examples:

```
9871
0981
0091
0001
0000

1210
0100
0000

Examples by @noisyass:

7478
8578
9678
0788
0899
0900
0000

3737
2627
1517
0407
0307
0207
0107
0007
0008
0009
0000

Own Example (longest sequence, shared with 6284)

4826
3826
2826
1826
0826
0926
0026
0015
0004
0003
0002
0001
0000

```

Full Code (inlcuding some comments):

```
%steps
s=[eye(4);1,1,0,0;0,1,1,0;0,0,1,1;1,1,1,0;0,1,1,1];
s=[s;-s];

D=NaN(1,10000);%D(n+1) = number of steps to get to n
P=NaN(1,10000);%P(n+1) was last one before n

I=NaN(10000,4);%integer representation as array
for i=0:9999;
    I(i+1,:)=sprintf('%04d',i)-'0';
end

G=9871; % define the current number (for the golfed version replaced with input('');
D(G+1)=0;
B=10.^(3:-1:0); %base for each digit

for k=0:100; %upper bound on number of steps;
    L=find(D==k)-1;
    for n=L; %iterate all new steps
        for i=1:18; %search all new steps
            m=sum(mod(I(n+1,:)+s(i,:),10) .* [1000,100,10,1]);
            if isnan(D(m+1))
                D(m+1) = k+1;
                P(m+1)=n;
            end
        end
    end
end
n=0;%we start here
X=[];
while n~=G
    X=[I(n+1,:)+'0';X];
    n=P(n+1);
end
disp([I(G+1,:)+'0';X,''])

```

# Answer
> 6 votes
# APL (Dyalog Extended), ~~82~~ 73 bytes

```
{p/⍨⍵≡¨⊃¨⊢p←({⍵/⍨⍧⊃¨⍵}⊢,⍥,(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)⍣≡⊂⊂4⍴0}⊆

```

`p←({⍵/⍨⍧⊃¨⍵}⊢,⍥,(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)⍣≡⊂⊂4⍴0`

p is all the possible paths

`({⍵/⍨⍧⊃¨⍵}⊢,⍥,(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)`

This is a train that generates the next possible paths from one list of paths

`(,∘-⍨↓⍉⊤5~⍨12 14,⍨⍳8)`

List of possible changes, 0 0 0 0, 0 0 0 1, 0 0 0 -1, etc

`∘.{10|⍵,⍨⊂⍺+⊃⍵}`

Outer product with the dfn `{10|⍵,⍨⊂⍺+⊃⍵}`

`{10|⍵,⍨⊂⍺+⊃⍵}`

`⊃⍵` unenclose ⍵ + `⊂⍺` enclose ⍺

`⍵,⍨` concatenated with ⍵ `10|` mod 10

`⊢,⍥,stuff` concatenate the output with the new paths

`{⍵/⍨⍧⊃¨⍵}` make it unique

`(train)⍣≡⊂⊂4⍴0` apply the train with a fixpoint `⍣≡` to `⊂⊂4⍴0` to generate all paths

`{p/⍨⍵≡¨⊃¨⊢p}`

`⊢p←...` the  shouldn't be needed here, but that's a bug costing me 1 byte

`⊃¨p` get the first items from each in p

`⍵≡¨` find where ⍵ is equal to them

`p/⍨` replicate

Try it online!

Old answer:

`{p⌷⍨⍸⍵≡¨⍥⊆⊃¨p←({⍵/⍨≠⊃¨⍵}⊢,⍥,((+,-)↓⍉2⊥⍣¯1⊢⎕A⍳'ABCDFGHLN')∘.{10|⍵,⍨⊂⍺+⊃⍵}⊢)⍣≡⊂⊂4⍴0}`

# Answer
> 4 votes
## Batch - 288 bytes

~~Even if you said they have to be consecutive (the rings), I assume by logic (following the example) that I can skip the middle one, as from `1234` to `0224`.~~

```
set/p x=
set a=%x:~0,1%&set b=%x:~1,1%&set c=%x:~2,1%&set d=%x:~3,1%
:l
@echo %x%&if %a%==0 (if %d% NEQ 0 set/a d=d-1) else set/a a=a-1
@if %b% NEQ 0 set/a b=b-1
@if %c% NEQ 0 set/a c=c-1
@if %x% NEQ 0000 set x=%a%%b%%c%%d%&goto l

```

~~This is my Batch solution: 236 bytes.~~

---

### Edit: corrected solution

```
set/p x=
set a=%x:~0,1%&set b=%x:~1,1%&set c=%x:~2,1%&set d=%x:~3,1%
:l
@echo %x%&set k=1&if %a%==0 (if %d% NEQ 0 set/a d=d-1&set k=0) else set/a a=a-1&set k=1
@if %b% NEQ 0 if %k%==1 set/a b=b-1&set k=0
@if %c% NEQ 0 if %k%==0 set/a c=c-1
@if %x% NEQ 0000 set x=%a%%b%%c%%d%&goto l

```

The new solution (fixed according to the underlying comments) is 288 bytes heavy.

# Answer
> 2 votes
# Haskell - 310 bytes

```
import Data.Char
import Data.List
r=replicate
h=head
a x=map(:x)[map(`mod`10)$zipWith(+)(h x)((r n 0)++(r(4-j)q)++(r(j-n)0))|j<-[1..3],n<-[0..j],q<-[1,-1]]
x!y=h x==h y
x#[]=(nubBy(!)$x>>=a)#(filter(![(r 4 0)])x)
x#y=unlines.tail.reverse.map(intToDigit<$>)$h y
main=do x<-getLine;putStrLn$[[digitToInt<$>x]]#[]

```

This works by repeatedly building a new list of combinations by applying each possible turn to each combination already reached until one of them is the right combination. Duplicates are removed from the list on each iteration to keep memory usage from growing exponentially.

As a brute force solution, this is very inefficient and can take several minutes to run.

I don't have much experience with Haskell, so some thing could probably be done better.

# Answer
> 2 votes
# 05AB1E `--no-lazy`, ~~41~~ ~~39~~ 37 bytes

Lazy evaluation seems to break it, with it enabled, this doesn't terminate.

```
[TS4ã¦ŽΣmbÏD(«N>ãεISšÅ»+}T%¤O1‹i¦J»,q

```

Try it online!

This is really slow, doesn't finish for `1234` and `5555` on TIO.

The general structure of the program is

```
[           infinite loop, N in 0, 1, ...
 ...        generate list of all possible movements
    ...     take all combinations of N+1 movements and convert them to a sequence of positions
       ...  if the current position list ends with 0000, print and terminate

```

In more detail:

```
TS4ã¦ŽΣmbÏD(«     # generate a list of all possible movements
T                 # push 10
 S                # split into digits ["1", "0"]
  4ã              # take ["1", "0"] to the 4th cartesian power
                  # this generates all 4-digit combinations of 0 and 1
    ¦             # remove the first element ("1111")
     ŽΣm          # push compressed integer 20958
        b         # convert to binary
         Ï        # keep the 4-digit combinations at indices where
                  #   the binary representation of 20958 has a 1
          D       # duplicate the list
           (      # negate each number in the copy
            «     # concatenate both lists

```

Try `T4ãʒγ€ÙO}¦€SD(«` online!

```
N>ãεISšÅ»+}T%     # try all possible combinations of movements
 N                # push the iteration counter (starts at 0)
  >               # increment the value
   ã              # take the movement list to the N+1 cartesian power
    ε             # map over each list of N+1 moves
     IS           # push the digits of the input
       š          # prepend it to the move list
        Å»+}      # cumulative left-reduce by addition
                  # this generates all positions of the lock
                  # that are a result of the movements in the list
            T%    # modulo 10

¤O1‹i¦J»,q        # verify and print position sequence
¤                 # get the last position
 O                # sum it
  1‹              # is this less than 1? (equal to 0)
    i             # if this is the case:
     ¦            #   remove the first element (initial position)
      J»          #   join each position and positions by newlines
        ,         #   print the result
         q        #   exit

```

# Answer
> 0 votes
# , 93 bytes

Doesn't even try to be efficient, will run out of memory for 5555 on TIO. :-)

```
(0({s#])((,-)|:#:7 59 217 584),/@((],10|(+{:))"1 2/)^:(]0=1#.s=:(4#0)&e."%.)^:_,:^:2)@(".@,.)

```

Try it online!

* `(".@,.)` convert '0123' into a list like `0 1 2 3`
* `,:^:2` list of list of steps `[[0 1 2 3]]`
* `^:(]0=1#.s=:(4#0)&e."%.)^:_` until the there is a path of moves with `0 0 0 0` in it:
* `((,-)|:#:7 59 217 584)` the possible moves
* `,/@((],10|(+{:))"1 2/)` for each possible move and each path: create a new path with the last move + the possible move, mod 10 appended.
* `0({s#])` filter out the paths that caused the loop to stop, and take the first.

---
Tags: code-golf, path-finding
---


title: Generate a RecursionError

text:
# Question
Title: Generate a RecursionError
Write the shortest possible code cause an error due to recursion too deep

Example error in

```
RecursionError: maximum recursion depth exceeded

```

Example error in

```
Segmentation fault

```

My Python version (15 bytes):

```
def f():f()
f()

```

# Answer
# APL (Dyalog Unicode), 3 bytes (SBCS)

```
F
F

```

A 1-byte header separated by a line break byte from by a 1-byte body which calls the function itself. This type of function doesn't have tail call optimisation, so this fails when memory runs out.

Anonymous lambdas do have tail recursion, but we can prevent that:

```
{-∇⍵}1

```

Try it online!

`{``}1` call an anonymous lambda with an argument of 1:

the argument

recurse on that

`-` negate the result

We never actually reach the negation before running out of memory, but it is needed to avoid the optimisation.
> 0 votes

# Answer
## Python 3, 15 bytes

```
exec('()'*9999)

```

Try it online!

An alternative that doesn't use functions. Unfortunately `RecursionError` does not exist in Python 2 so we can't cut the brackets in `exec`.

## Python 3.8, 18 bytes

```
exec(s:='exec(s)')

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~20~~ 18 bytes

```
def f(x):x(x)
f(f)

```

Try it online!
> 1 votes

---
Tags: code-golf, recursion, error-message
---


title: KoTH: Political Simulator

text:
# Question
Title: KoTH: Political Simulator
It's election time, and your job is to beat your competitor in a head-on rivalry! You are both trying to win over a city of 256 people in a 16x16 grid. Right now, the city hasn't been divided into voting regions yet, but that's where your gerrymandering skills come in! You can also campaign in arbitrary areas of the city to gain support.

## General

All bots (JS functions) will be run against all other bots once per game. In each game, the city will start out with all voters being neutral. The game will keep track of a number for each voter, determining who they support. From a particular bot's perspective, a positive number means that voter will vote for them, while a negative number is a vote for the opponent. Zero is neutral.

The city is divided into 16 blocks, which are all 4x4 squares. Voting regions are made up of one or more blocks. There are initially 16 of them, with each block having its own region.

Both bots start with $100, and can move once per turn. These moves are run effectively simultaneously, so there is no first turn advantage. Moves fall into four categories:

* **Campaigning:** This will cause every person in a specific area to increase their support for the candidate who is campaigning. The amount it changes depends on their neighbors.
* **Polling:** This will get each person's support for the candidate in a specific area.
* **Bribing:** This will cause a particular person to increase their support for the candidate.
* **Region Merging/Unmerging:** This will reshape voting regions.

At the end of each turn, after both candidates have moved, both will recieve $10.

## Details

The following moves are allowed. If an invalid move is given (insufficient money or invalid coordinates), the bot's turn will be skipped.

All coordinates should be within `0 <= n < 16`, and for the second pair in rectangular bounding areas `0 <= n <= 16` (as these are **exclusive**).

* **`campaign([x, y], [x, y])`:** Campaign within the boundary determined by the two coordinate pairs
    + Costs $1 per person affected
    + Each person within the area will change their support according to the following rules:
        - For all neighbors orthogonally (including diagonals) adjacent, add 0.1 support for whichever candidate the majority support (weighted), or 0.2 if their total support is at least 2 for that candidate
        - Add 0.25 for the candidate who is campaigning
* **`poll([x, y], [x, y])`:** Poll within the boundary determined by the two coordinate pairs
    + Costs $0.25 per person polled, rounded up
    + On the next turn, the following information is given about each person in the area (after the opponent's move):
        - Their support for the polling candidate, where positive numbers indicate a vote for them, and negative numbers being a vote for the opponent
* **`bribe([x, y])`:** Bribe the person at the location determined by the coordinate pair
    + Costs at least $5
        - For every time a person within the voting block (**not** the voting region) has been bribed, add $1
    + Add up to 3.5 support for the bribing candidate
        - For every time a person within the voting block has been bribed, the support added is decreased by 0.15
        - Eventually, this can cause bribing someone in a voting block to *reduce* their support for the candidate
* **`merge([x, y], [x, y])`:** Merge the voting regions determined by the two coordinate pairs
    + Costs $25 for every block in the newly formed region (one block is free)
    + Requires the regions which contain the two people specified to be touching
        - Note that the coordinates correspond to people, not blocks. To reference a block, just multiply its coordinates by 4
* **`unmerge([x, y])`:** Unmerge the voting region determined by the coordinate pair
    + Costs $25 for every block in the region
    + Every block in the region becomes its own region

If both bots attempt a merge or unmerge on the same turn (even if they won't interfere), both turns will be skipped and neither will pay anything. Moves will be processed in the following order (the order of the rest don't matter):

1. Bribes
2. Support from neighbors in campaigning
3. Support from candidates in campigning

## Winning

At the end of each turn, after both candidates have moved, all regions will have their votes added. Each person will either vote for one candidate or be neutral, regardless of by how much (i.e., a score of +0.05 or +30 would be identical here). If the following conditons are met, an election will be held and the winner chosen:

* All regions are made up of less than half neutral voters
* The number of regions voting for each candidate are not tied

## I/O

All bots should be submitted in the form of Javascript functions. The following information will be provided as arguments to the function:

* An array of voting regions, represented as objects with the following properties:
    + `blocks`: An array of voting blocks, represented as the coordinates `[x, y]` of the top-left person (such as `[4, 0]` or `[12, 12]`)
    + `number_neutral`: The number of people in the region who are neutral
    + `number_you`: The number of people in the region voting for the bot
    + `number_opponent`: The number of people in the region voting for the bot's opponent
    + `absolute_average`: The average absolute value of people's support for a candidate
        - Higher numbers indicate campaigning or bribing will typically be less effective
        - Exactly 0 would mean every person in the region is neutral
* The amount of money the bot has
* An object containing the results of the last move (empty unless it was a poll)
    + An array `people` will contain objects representing each person polled:
        - `position`: The person's coordinates, formatted as `[x, y]`
        - `region`: The numbered ID of the region the person is in (the region's index in the first argument)
        - `support`: A number indicating whether the person is neutral (0), voting for the bot (positive), or voting for the bot's opponent (negative)
    + An object `amounts` containing the following properties:
        - `number_neutral`: The number of people in the region who are neutral
        - `number_you`: The number of people in the region voting for the bot
        - `number_opponent`: The number of people in the region voting for the bot's opponent
        - `absolute_average`: The average absolute value of people's support for a candidate
* An object that can be used for storage between turns (but not between rounds/games)

To move, the result one of the functions above should be returned. For example:

```
{
    "Example": (regions, money, result, storage) => {
        storage.block = ((storage.block || 0) + 1) % 16;

        return campaign(
            [(storage.block / 4 | 0) * 4, (storage.block % 4) * 4],
            [(storage.block / 4 | 0) * 4 + 4, (storage.block % 4) * 4 + 4]
        );
    }
}

```

## Rules

* Bots should take a reasonable amount of time to run
* Bots should play fairly, no manipulating the controller or other submissions in ways not allowed here
* Every bot will be run against every other bot once, with the winner being the bot which wins most often
    + In the event of a tie, the earlier bot wins
* Invalid return values or bots that error will assume no move for the turn
* Bots must be deterministic

Challenge idea and original sandbox proposal by HyperNeutrino.

**Controller:** https://radvylf.github.io/political-simulator
**Chatroom:** Here
**Due Date:** Thursday, November 5th, 2020, UTC Noon (8:00 AM EST)

# Answer
> 3 votes
# Abotcus

Turns out you don't need so many fancy features to be just as good as or better than Randgrab! Abotcus grabs an area at the start, then afterwards applies a straightforward formula to weight each block and picks the block with the best weight. If it looks like there's some unnecessary stuff in there, it's because I expected to add a lot more fancy features... but I just didn't need to ¯\\\_(ツ)\_/¯

<pre><code>(regions, money, result, storage) => {

    if(money == 100) {return campaign([9,1],[15,15])}

    var map = [[,,,],[,,,],[,,,],[,,,]];
    var weights = [[,,,],[,,,],[,,,],[,,,]];
    var blocks = [];

    for(var r of regions) {
        for(var b of r.blocks) {
            map[b[1]/4][b[0]/4] = b;
            weights[b[1]/4][b[0]/4] = weight(r.number_you, r.number_opponent, r.number_neutral, r.absolute_average)/r.blocks.length;
            blocks.push([b, weights[b[1]/4][b[0]/4]]);
        }
    }

    blocks.sort((a,b) => {
        return b[1]-a[1];
    });

    var start_block = blocks[0][0];

    console.log(blocks);

    if(money >= 16) {
        return campaign(start_block, [start_block[0]+4, start_block[1]+4]);
    } else {
        return campaign(start_block, [start_block[0]+3, start_block[1]+3]);
    }

    function weight(own, opp, neut, avg) {
        var tot = own+opp+neut;
        var cat = 0;
        if(opp > tot/2) {
            cat = 1;
        } else if(own > tot/2) {
            cat = 5;
        }
        return 1/(1+avg+cat);
    }
}
```
</code></pre>

# Answer
> 6 votes
# Landgrab

Brief description of strategy:

1. On the first turn, do a large campaign in the center using up all the initial money.
2. Otherwise, if there is a region with more than 2 neutral voters, campaign in the region with the most neutral voters.
3. Otherwise, if there is a region in which me and my opponent have the same number of voters, campaign in that region.
4. Otherwise, campaign in the region with the most neutral voters.

This relies on the fact that it's much easier to claim neutral voters than voters who are already going to vote for your opponent. It doesn't know about gerrymandering, so might not do very well if someone messes with voting regions, but it's a start.

```
(regions, money, result, storage) => {
   if(money == 100) { return campaign([2, 2], [12, 12]); }
   var best = regions[0];
   var tied;
   for (var i = 0; i < regions.length; i++) {
      if(regions[i].number_neutral > best.number_neutral) {
         best = regions[i];
      }
      if(regions[i].number_neutral == 0 && regions[i].number_you == regions[i].number_opponent) {
        tied = regions[i];
      }
   }
   var b;
   if (tied && best.number_neutral > 2) {
     b = tied.blocks[money % tied.blocks.length];
   } else {
     b = best.blocks[money % best.blocks.length];
   }
   if (money >= 16) {
        return campaign(b, [b[0] + 4, b[1] + 4])
   } else if (money % 2 == 0) {
        return campaign(b, [b[0] + 3, b[1] + 3])
   } else {
        return campaign([b[0] + 1, b[1] + 1], [b[0] + 4, b[1] + 4])
   }
}

```

# Answer
> 4 votes
# Leftist Policy

### v1.1

Grabs the left side of the map, then gerrymanders the right side. Having accomplished that, it will slowly campaign the right side to avoid deadlock.

```
(regions, money, result, storage) => {
        storage.phase = storage.phase || 0;
        storage.merge = storage.merge || 0;

        if (storage.phase == 0){
            storage.phase+=2;
            return campaign([1,2],[5,14]);
        }

        if (storage.phase <= 6) {
            var result = campaign([storage.phase,1],[storage.phase+1,15]);
            if(money >= 14) storage.phase++;
            return result;

        }

        if(storage.phase == 7){

            if(storage.merge < 4){
                var result;
                if(money >= 25){
                    result = merge([9,(storage.merge*4)+1],[15,(storage.merge)*4+1])
                    storage.merge++;
                    storage.phase = 1
                }
                return result;
            }
            else if(regions.filter(r => r.blocks[0][0] <= 5)
                           .filter(r => r.number_you > r.number_opponent + r.number_neutral).length >= regions.length / 2){
                area = (storage.merge % 4)*4;
                if(money >= 18){
                    storage.merge++;
                    storage.phase = 1;
                    return campaign([9,area],[15,area+3]);
                }
            }
            else{

                storage.phase = 1;
                var result = campaign([storage.phase,1],[storage.phase+1,15]);
                if(money >= 14) storage.phase++;
                return result;
            }
        }
    }

```

Currently only beats the example bot. The strategy is just too slow to win much.

# Answer
> 4 votes
# Randgrab

Started as an evolution of Landgrab to increase randomness, then slowly added more and more features until it currently beats all other contestants (Landgrab, Leftist Policy 1.1, and Greedy campaign 9).

Features include:

* Grabbing less land at the start to save money
* Grabbing adjacent areas at once if we have enough money
* De-priortize areas where we already have enough lead to win and the opponent hasn't campaigned yet
* Prioritize areas where the vote is closest (the "swing states," if you will)
* More randomness, including choosing at random any one of the four corners to claim when doing a 3x3
* A pretty chaotic (but still deterministic!) `r` variable which controls all randomness

Weaknesses include:

* Not prioritizing undecided states highly enough
* Not taking advantage of any non-campaign functions
* Can be thrown off by region changes, although this has been partially corrected for
* Can be thrown off by claims which don't align to borders well

```
(regions, money, result, storage) => {
    if(money == 100) {return campaign([4, 4], [12, 12]);}
    var r = money + money * regions.length;
    regions.forEach(reg => r += reg.blocks[0][0] * reg.number_neutral + reg.blocks[0][1] * reg.number_you + money * reg.number_opponent + reg.blocks.length * reg.absolute_average);
    r = Math.floor(r);
    var tied = [];
    var best = [regions[r % regions.length]];
    var closest = [regions[(2*r) % regions.length]];
    for (var i = 0; i < regions.length; i++) {
        if(regions[i].number_neutral > best[0].number_neutral && !(regions[i].number_you > 8 && regions[i].number_opponent == 0)) {
            best = [regions[i]];
        } else if(regions[i].number_neutral == best[0].number_neutral && !(regions[i].number_you > 5 && regions[i].number_opponent == 0)) {
            best.push(regions[i]);
        }
        if(regions[i].number_neutral == 0 && regions[i].number_you == regions[i].number_opponent) {
            tied.push(regions[i]);
        }
        if(regions[i].number_opponent > regions[i].number_you && regions[i].absolute_average < closest[0].absolute_average) {
            closest = [regions[i]];
        } else if(regions[i].number_opponent > regions[i].number_you && regions[i].absolute_average == closest[0].absolute_average) {
            closest.push(regions[i]);
        }
    }
    var b;
    var choice;
    if (tied.length > 0 && best[0].number_neutral > 4) {
        choice = tied;
    } else {
        choice = (best[0].number_neutral > 2 ? best : closest);
    }
    console.log(choice);
    bt = choice[r % choice.length];
    b = bt.blocks[r % bt.blocks.length];
    var x = Math.floor(r/2) % 2;
    var y = Math.floor(r/4) % 2;
    if (money >= 18 && choice) {
        for(var i = 0; i < choice.length; i++) {
            for(var j = 0; j < choice[i].blocks.length; j++) {
                var c = choice[i].blocks[j];
                if(c[0] == b[0]-4 && c[1] == b[1]) {
                    return campaign([c[0]+1, c[1]], [b[0]+3, b[1]+3]);
                } else if(c[0] == b[0]+4 && c[1] == b[1]) {
                    return campaign([b[0]+1, b[1]], [c[0]+3, c[1]+3]);
                } else if(c[0] == b[0] && c[1] == b[1]-4) {
                    return campaign([c[0], c[1]+1], [b[0]+3, b[1]+3]);
                } else if(c[0] == b[0] && c[1] == b[1]+4) {
                    return campaign([b[0], b[1]+1], [c[0]+3, c[1]+3]);
                }
            }
        }
    }
    if (money >= 16) {
        return campaign(b, [b[0] + 4, b[1] + 4]);
    } else {
        return campaign([b[0] + x, b[1] + y], [b[0] + 3 + x, b[1] + 3 + y]);
    }
}

```

# Answer
> 3 votes
# Greedy campaign 9 per each region

* Each turn, we have at least $10. This make it possible to campaign a 3x3 area.
* Since we only need 9 gird in each region. We just campaign top 3x3 but give up the ones on right or bottom.
* Every turn, we choice campaign position greedy: The more region support us in next turn, The better.

```
(regions, money, result, storage) => {
  const turn = storage.turn = storage.turn + 1 || 1;
  const gh = money < 21 ? 1 : 2;
  const h = 4 * gh - 1;
  const gw = 77 <= money ? 3 : 49 <= money ? 2 : 1;
  const w = 4 * gw - 1;
  const candidate = [];
  for (let i = 0; i <= 4 - gw; i++) {
    for (let j = 0; j <= 4 - gh; j++) {
      let s = gw * gh;
      for (let k = 0; k < gw; k++) {
        for (let l = 0; l < gh; l++) {
          let bx = i + k, by = j + l;
          let region = regions.find(r => r.blocks.some(block => block == [bx * 4, by * 4] + ''));
          let { number_neutral: n, number_opponent: o, number_you: y } = region;
          if (y <= o) {
            if (n + y > o) s += 1;
            if (n + y == o) s += 0.5;
            if (n + y < o) s += 0.5 ** (o - y - n / 2);
          } else {
            if (n + o > y) s += 0.5;
            if (n + o < y) s += -(0.5 ** (y - o - n / 2));
            if (n + o == y) s += 0.25;
          }
        }
      }
      candidate.push({ s, x: i, y: j });
    }
  }
  const ts = Math.max(...candidate.map(c => c.s));
  const best = candidate.filter(c => c.s === ts);
  const { x: tx, y: ty } = best[turn % best.length];
  return campaign([tx * 4, ty * 4], [tx * 4 + w, ty * 4 + h]);
}

```

# Answer
> 2 votes
# Liberal Agenda

The spiritual successor of Leftist Policy. Campaigns the whole left side turn one, then gerrymanders both of the top right blocks together, then goes back to protecting the left side. Once it's extremely confident it has the left covered, it moves on to the right.

```
    (regions, money, result, storage) => {
        storage.merge = (storage.merge||0)
        if(money >= 100){
            return campaign([1,1],[7,15])
        }
        else {
            var map = [];
            regions.forEach(reg => {
                reg.blocks.forEach(b => {
                    map.push({
                        "pos": b,
                        "abs_avg":reg.absolute_average,
                        "num_you":reg.number_you / reg.blocks.length,
                        "num_opp":reg.number_opponent / reg.blocks.length,
                        "num_neu":reg.number_neutral / reg.blocks.length,
                        "won": (reg.number_neutral>=reg.number_you+reg.number_opponent) ? 0 : reg.number_you/ reg.blocks.length - reg.number_opponent / reg.blocks.length
                    });
                });
            });
            map = map.sort((a,b)=>a.abs_avg-b.abs_avg).sort((a,b)=>a.won - b.won);
            var leftmap = map.filter(b=>b.pos[0]<8)
            if(money >= 25){
                if(storage.merge == 0){
                    storage.merge++
                    return merge([8,0],[12,0])
                }
                return campaign([leftmap[0].pos[0],leftmap[0].pos[1]],[leftmap[0].pos[0]+4,leftmap[0].pos[1] + 4])
            }

            if(leftmap.every(b=> b.abs_avg > 3)) return campTarget3by3(map[0].pos).filter(b=>b.won<1)
            return campTarget3by3(leftmap[0].pos)
        }

        function campTarget3by3(pos){
            var a1,a2,b1,b2
            if(pos[0]==0){
                a1 = 1
                b1 = 4
            }
            else {
                a1 = pos[0]
                b1 = pos[0] + 3
            }
            if(pos[1]==0){
                a2 = 1
                b2 = 4
            }
            else {
                a2 = pos[1]
                b2 = pos[1] + 3
            }

            return campaign([a1,a2],[b1,b2])
        }
    }

```

Ironically, it's the only thing Leftist Policy can beat!

---
Tags: grid, king-of-the-hill, javascript
---


title: Double up some diamonds

text:
# Question
Title: Double up some diamonds
# Problem

Given a positive integer `n` where `n < 100`

Output a diamond pattern as follows:

Input `n=1`

```
/\/\
\/\/

```

Input `n=2`:

```
 /\      /\
//\\/\/\//\\
\\//\/\/\\//
 \/      \/

```

Input `n=3`:

```
  /\                /\
 //\\  /\      /\  //\\
///\\\//\\/\/\//\\///\\\
\\\///\\//\/\/\\//\\\///
 \\//  \/      \/  \\//
  \/                \/

```

Input `n=4`:

```
   /\                              /\
  //\\    /\                /\    //\\
 ///\\\  //\\  /\      /\  //\\  ///\\\
////\\\\///\\\//\\/\/\//\\///\\\////\\\\
\\\\////\\\///\\//\/\/\\//\\\///\\\\////
 \\\///  \\//  \/      \/  \\//  \\\///
  \\//    \/                \/    \\//
   \/                              \/

```

And so on.

# Rules

* Program and function allowed.
* Trailing whitespace allowed.
* Leading whitespace on lines with no `/` or `\` allowed.
* Trailing and leading newlines allowed.
* **Shortest code in bytes win**

This is probably pretty related

# Answer
> 12 votes
# SOGL V0.12, 24 bytes

```
ā.∫ā;∫ \*+}ø┼↔±╬¡;øΚ┼}╬³

```

Try it Here!

Explanation:

```
ā                         push an empty array (the main canvas)
 .∫                  }    iterate over the input, pushing 1-indexed iteration
   ā;                       push an empty array below the iteration
     ∫    }                 iterate over the iteration counter
       \*                     push current iteration amount of slashes
         +                    append those to the 2nd array
           ø┼               append nothing (so it'd space the array to a square)
             ↔±             reverse horizontally (swapping slashes)
               ╬¡           quad-palindromize with 0 overlap and swapping characters as required
                 ;          get the canvas ontop
                  øΚ        prepend to it an empty line (so the now bigger romb would be one up)
                    ┼       append horizontally the canvas to the current romb
                      ╬³  palindromize horizontally with no overlap and swapping characters

```

# Answer
> 7 votes
# Charcoal, ~~30~~ 27 bytes

```
Ｆ⁺¹Ｎ«Ｆι«Ｆ⁴«↙⁻ικ↑⟲Ｔ»←»Ｍι←»‖Ｍ

```

Try it online! Link is to verbose version of code. Explanation: Charcoal's drawing primitives can't quite draw a diamond, because the diagonal movements stay on squares of the same parity. Edit: The new solution is to draw one side of a diamond and then rotate the entire canvas ready to draw the next side, allowing a diamond to be drawn in a loop. This loop is then contained in a loop to draw all the inner diamonds for each diamond. The outermost loop draws all diamonds adjacent to each other. Finally the image is mirrored.

Note that Charcoal has since been extended and another byte could be saved by using `Increment`.

# Answer
> 6 votes
# 05AB1E, ~~47~~ ~~43~~ ~~41~~ ~~35~~ ~~34~~ ~~33~~ 32 bytes

```
'/×ηηvy∞.C.Bø€∞¹NαGð.ø}})øíJ.B»∞

```

Try it online!

(-4 bytes thanks to @Emigna who suggested 3 improvements)

---

This explanation was for the earlier version, there have been a few iterations since then.

```
>                                          # [2]
 '/×                                       # ['//']
    η                                      # ['/','//']
     €η                                    # [['/'], ['/', '//']]
       vy                    }             # {For each element...}
         ∞                                 # Mirror horizontally.
          ¶¡                               # Split mirror on newlines.
            N£                             # Shave each diamond down a layer.
              .C                           # Horizontal center.
                .B                         # Pad for the transpose.
                  ø                        # Transpose.
                   €∞                      # Mirror each (vertically).
                     ¹NαFð.ø}              # Pad each list for transpose (verticaly).
                              )            # Wrap back to list...
                               €.B         # Pad each horizontally.
                                  ¦        # Remove the random numbers?
                                   ø       # Back to horizontal...
                                    €R     # Reverse to get correct order.
                                      J    # Join, no spaces.
                                       »   # Join newlines.
                                        ∞  # Final horizontal mirror.

```

# Answer
> 6 votes
# APL (Dyalog), ~~70~~ ~~69~~ 66 bytes

```
B←{'/\ '['\/'⍳⍺⍺⍵]}
C←⊢,⌽B
C(⊢⍪⊖B)⊃,/{C⊖A↑⊖' /'[⍵≤∘.+⍨⍳⍵+1]}¨⌽⍳A←⎕

```

Try it online!

Assumes `⎕IO←0`, which is standard on many systems, so the program is 0-indexed.

This is a tradfn that takes input via STDIN.

### Explanation

(slightly outdated)

Note that  is the left argument,  is the right argument and `⍺⍺` is the left operator.

`B` is a function that helps in mirroring the diamonds. It takes the string as the right argument and the reverse function as the left (so `B` is an operator).

```
B←{'/\ '['\/'⍳⍺⍺⍵]}
              ⍺⍺⍵            Apply ⍺⍺ on ⍵
         '\/'⍳               Find the index of the reflected string in '\/' (if the character is not found in `'\/'`, then return an index out of the bounds of the string, ie `2` if the character is a space)
   '/\ '[        ]           Use these indexes on '/\ ' to reflect the '/\' characters

```

And now we go to the main part of the program.

```
A←⎕              Assign the input to variable A
⍳                Create a range 0 .. A-1
⌽                Reverse it so that it becomes A-1 .. 0
¨                For each element do (the right argument is the element):
 ⍳⍵+1             Create a range 0 .. ⍵
 ∘.+⍨             Create an addition table using the range to result in a matrix like so:
                   0+0 0+1 0+2 .. 0+⍵
                   1+0 1+1 1+2 .. 1+⍵
                   2+0 2+1 2+2 .. 2+⍵
                   ...
                   ⍵+0 ⍵+1 ⍵+2 .. ⍵+⍵
 ⍵≤              The elements of the matrix that are greater than or equal to the ⍵,
                 this creates a triangle matrix that looks like this:
                   0 0 .. 0 1
                   0 0 .. 1 1
                   ..
                   1 1 .. 1 1
 ' /'[...]       Index it in ' /' to get a character matrix
                 (ie replace 0s with spaces and 1s with '/'s)
 ⊖               Flip this vertically
 A↑              Pad the top spaces

```

This is necessary to ensure that all the triangles created for every element in the range `⌽⍳A` have the same height so that they can be later concatenated with each other.

```
 ⊖               Flip the matrix vertically again to go back to the original state
 (⊢,  )          Concatenate it with
    ⌽B           itself, but flipped horizontally
,/              Concatenate all triangles formed by the range operator
⊃               The resulting matrix is nested, so this operator "un-nests" it

```

Now the top left part of the pattern is complete. All that's remaining is to flip it vertically and then horizontally.

```
(⊢⍪⊖B)          Concatenate the resulting matrix with itself but flipped vertically
                (the vertically flipped matrix is concatenated below of the original matrix)
                Now the left part of the pattern is complete
(⊢,⌽B)         Concatenate the resulting matrix with itself flipped horizontally

```

And that's it! The output is a character matrix with `/\`s and padded with spaces.

# Answer
> 5 votes
# CJam, ~~65~~ 63 bytes

```
q~_,:)_W%\+f{_2*S*a@2$-*\_,f{)'/*\Se[_W%'/'\er+}_W%Wf%+1$++}zN*

```

Try it online!

### Explanation

In this explanation, I will refer to the input number as `n`.

```
q~        e# Read and eval the input (push n to the stack).
_,        e# Copy it an get the range [0 .. n-1].
:)        e# Increment each element to get [1 .. n].
_W%       e# Copy it and reverse it.
\+        e# Prepend the reverse to the original range, resulting in [n n-1 .. 1 1 .. n-1 n].
f{        e# Map over each number x in the range using n as an extra parameter:
 _2*S*a   e#  Push a string containing n*2 spaces, and wrap it in an array.
 @2$-     e#  Push n-x.
 *        e#  Repeat the space string from before n-x times.
 \        e#  Bring x back to the top.
 _,       e#  Copy it and get the range [0 .. x-1].
 f{       e#  Map over each number y in this range, using x as an extra parameter:
  )       e#   Increment y.
  '/*     e#   Repeat '/' y times.
  \Se[    e#   Pad the resulting string to length x by adding spaces to the left.
  _W%     e#   Copy the result and reverse it.
  '/'\er  e#   Replace '/' with '\' in that.
  +       e#   Concatenate to the other string. This forms one row of one diamond.
 }        e#  (end map, now we have the top half of a diamond of size x)
 _W%      e#  Copy the half-diamond and reverse it.
 Wf%      e#  Reverse each row.
 +        e#  Concatenate to the top half. Now we have a full diamond of size x.
 1$++     e#  Put the spaces from before at the beginning and end. This is to pad the top
          e#  and bottom of the smaller diamonds.
}         e# (end map)
z         e# Transpose.
N*        e# Join with newlines. Implicit output.

```

# Answer
> 3 votes
# Python 2, ~~152~~ ~~147~~ ~~143~~ 140 bytes

<sup>-1 byte thanks to musicman523</sup>

```
n=input()
r=range(n)
r+=r[::-1]
for x,i in enumerate(r):a,b='/\\\/'[i<x::2];s=' '*(n+~i);print''.join((s+a*n)[:n-j]+(b*-~i+s)[j:]for j in r)

```

Try it online!

This works by chopping the inner columns of the largest diamond to make the smaller ones, using `[0,..,n,n,..,0]` to control the amount of columns to remove.

# Answer
> 3 votes
# Pyth, ~~35~~ 32 bytes

```
j.tsm+Jm.[yQS*"\/"k\ Sd_M_Js__BS

```

Test suite

Done to see how my and @LeakyNun's approaches would differ.

# Answer
> 3 votes
# Dyalog APL, 46

```
{⊃,/⍵∘{'/ \'[2+((-⍪⊖)⌽,-)(-⍺)↑∘.≥⍨⍳⍵]}¨(⌽,⊢)⍳⍵}

```

# Answer
> 2 votes
# Pyth, 49 bytes

```
LC.tb)L+_b.rb"\/"js_,J'MsMCyMy_Mm'Myd._._*\/Q__MJ

```

Try it online!

# Answer
> 1 votes
# , 38 bytes

```
Àá/Àá\ò2ÙlX$xòÍî
òYGpVæHÄÓ¯¨¯*Ü*©Ü/ ±

```

Try it online!

# Answer
> 1 votes
# Canvas, 13 bytes

```
ＨＨ／ｎ｝！╬＋｝⤢ｒ！║

```

Try it here!

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


# Question
Title: Sieve of Sundaram (for finding prime numbers)
# The Challenge

Implement the Sundaram sieve for finding prime numbers below `n`. Take an input integer, `n`, and output the prime numbers below `n`. You can assume that `n` will always be less than or equal to one million.

---

# Sieve

1. Start with a list of the integers from `1` to `n`.
2. Remove all numbers that are in the form `i + j + 2ij` where:

* `i` and `j` are less than `n`. `j` is always greater than or equal to `i`, which is greater than or equal to `1`.
    * `i + j + 2ij` is less than or equal to `n`
3. Multiply the remaining numbers by `2`, and add `1`.

This will yield all the prime numbers (except `2`, which should be included in your output) less than `2n + 2`.

---

Here is an animation of the sieve being used to find primes below `202`.

---

# Output

Your output should be every prime integer `≤ n` (in ascending order) followed by a newline:

```
2
3
5

```

Where `n` is `5`.

---

# Examples

```
> 10
2
3
5
7

> 30
2
3
5
7
11
13
17
19
23
29

```

Inputs are denoted by `>`.

# Answer
> 7 votes
# Pyth, 23 bytes

```
2j@JSQmhyd-Jm+sdy*Fd^J2

```

Demonstration

Really just implements the algorithm as given.

# Answer
> 3 votes
# Haskell, ~~93~~ 90 bytes

```
import Data.List
g n=unlines[show$2*x+1|r<-[[1..n]],x<-2:(r\\[i+j+2*i*j|j<-r,i<-r]),2*x<n]

```

How it works: `[i+j+2*i*j|j<-r,i<-r]` are all `i+j+2ij` which are removed (`\\`) from `[1..n]`. Scale to `2x+1` and turn them into a string (`show`). Join with NL (`unlines`).

# Answer
> 1 votes
# Scala, ~~115 124 122 115~~ 114 bytes

```
n=>{println(2);for{m<-1 to n;if !(for{j<-1 to n;i<-1 to j}yield i+j+2*i*j).contains(m);o=2*m+1;if o<=n}println(o)}

```

An anonymous function; takes n as an argument and prints the result to stdout.

# Answer
> 1 votes
# JavaScript (ES7), ~~107~~ 105 bytes

Array comprehensions are awesome! But I wonder why JS has no range syntax (e.g. `[1..n]`)...

```
n=>{for(a=[i=1];i<n;a[i++]=i);for(i=0;i++<n;)for(j=0;j<n;a[i+j+++2*i*j]=0);return[for(i of a)if(i)i*2+1]}

```

This was tested successfully in Firefox 40. Breakdown:

```
n=>{
  for(a=[i=1];i<n;a[i++]=i); // fill a list with 1..n
  for(i=0;i++<n;)            // for each integer i in 0..n
    for(j=0;j<n;)            //   for each integer j in 0..n
      a[i+j+++2*i*j-1]=0;    //     set the corresponding item of the list to 0
  return[for(i of a)         // filter the list by:
          if(i)              //   item != 0 AND item != undefined
           i*2+1]            // and return each result * 2 + 1
}

```

Alternative, ES6-friendly solution (111 bytes):

```
n=>{for(a=[i=1];i<n;a[i++]=i);for(i=0;i++<n;)for(j=0;j<n;a[i+j+++2*i*j]=0);return a.filter(x=>x).map(x=>x*2+1)}

```

Suggestions welcome!

# Answer
> 0 votes
# MATLAB, 98

```
n=1:input('');m=n;for p=m for i=1:p j=i:p;for k=i+j+2*i*j n(n==k)=[];end;end;end;disp(2*n'+1);

```

And in a readable form

```
n=1:input(''); %Ask for the input number (e.g. 100) and form a range
m=n; %Back up the range as we will be editing 'n', but need 'm' as a loop list
for p=m %For each number between 1 and n inclusive
    for i=1:p %'i' is all numbers greater than or equal to 1 up to p
        j=i:p; %'j' is all numbers greater than or equal to i up to p
        for k=i+j+2*i*j %Calculate the numbers to remove, and loop through them
            n(n==k)=[]; %Remove that value from the 'n' array
        end
    end
end
disp([2;2*n'+1]); %An display the list including the number 2 seperated by a new line.

```

# Answer
> 0 votes
# Java8 : ~~168~~ 165 bytes

```
N->{int[]A=new int[N*N];int i=1,j;N=N/2;for(;i<N;i++)for(j=i;j<N;)A[i+j+2*i*j++]=1;System.out.println(N>1?2:\"\");for(i=1;i<N;i++)if(A[i]<1)System.out.println(2*i+1);}

```

For more bigger number data type with wide range can be used. We do not need to iterate for whole `N` indexes `N/2` is sufficient.

To understand properly following is the equivalent method.

```
static void findPrimeSundar(int N){
    int[] A = new int[N*N];
    int i=1,j;
    N=N/2;
    for(;i<N;i++)
      for(j=i;j<N;)
        A[i+j+2*i*j++]=1;
    System.out.println(N>1?2:"");
    for(i=1;i<N;i++)
        if(A[i]<1)System.out.println(2*i+ 1);
}

```

# Answer
> 0 votes
# CJam, 35 bytes

```
2li:V,:)__2m*{_:+\:*2*+}%m2f*:)&+N*

```

Try it online

This seems somewhat lengthy relative to isaacg's Pyth solution, but it's... what I have.

Explanation:

```
2       Push a 2, will be part of final output.
li      Get input and convert to integer n.
:V      Save in variable V for later use.
,       Generate list [0 ... n-1].
:)      Increment list elements to get list [1 ... n].
__      Create two copies, one for sieve, and for clamping results.
2m*     Cartesian power, generating all i,k pairs.
{       Loop over all i,j pairs.
  _     Copy pair.
  :+    Calculate sum i + j.
  \     Swap copy of pair to top.
  :*    Calculate product i * j.
  2*    Multiply by 2, to get 2 * i * j.
  +     Add both values, to get i + j + 2 * i * j.
}%      End loop over all i,j pairs.
m       Sieve operation, remove the calculated values from the list of all values.
2f*     Multiply the remaining values by 2...
:)      ... and add 1 to the. We now have the list of all primes up to 2 * n + 2.
&       Intersect with [1 ... n] list, because output is only values <= n.
+       Concatenate with the 2 we pushed at the start.
N*      Join with newlines.

```

# Answer
> 0 votes
## Perl 6, 96 bytes

If I strictly follow the description the shortest I managed to get is 96 bytes.

```
->\n {$_=@=1..n;for 1..n {for $^i..n {.[$i+$^j+2*$i*$j-1]=0}};2,|.[0..n].map(* *2+1).grep(3..n)}

```

```
->\n {
  $_=@=1..n; # initialize array
  for 1..n { # $i
    for $^i..n { # $j
      .[$i+$^j+2*$i*$j-1]=0 # remove value
    }
  };
  2,|.[0..n].map(* *2+1).grep(3..n)
}

```

---

If I could do the `2n + 1` on initialization of the array, pre-inserting `2`, and limiting that to only the values less than or equal to `n`; it can be reduced to 84 bytes.

```
->\n {$_=@=2,{++$*2+1}...^*>n;for 1..n {for $^i..n {.[$i+$^j+2*$i*$j]=$}};.grep(?*)}

```

If I also ignore that `j` is supposed to be at least `i`, I can reduce it to 82 bytes.

```
->\n {$_=@=2,{++$*2+1}...^*>n;for 1..n X 1..n ->(\i,\j){.[i+j+2*i*j]=$};.grep(?*)}

```

---

Example usage:

```
my $code = ->\n {...} # insert one of the lambdas from above

say $code(30).join(',');
# 2,3,5,7,11,13,17,19,23,29

my &code = $code;
say code 11;
# (2 3 5 7 11)

```

# Answer
> 0 votes
# PHP, 126 Bytes

```
$r=range(1,$n=$argn/2-1);for(;++$i**2<=$n;)for($j=$i;$n>=$d=$j+$i+2*$i*$j++;)unset($r[$d-1]);foreach($r as$v)echo 1+2*$v."\n";

```

Online Version

# Answer
> 0 votes
# Julia 0.6, 65 bytes

```
n->[2;(p=setdiff(1:n,[i+j+2i*j for i=1:n for j=i:n])*2+1)[p.<=n]]

```

Try it online!

Not a great challenge in terms of golfing, but I just had to do it for the name. :)

# Answer
> 0 votes
# Husk, 24 bytes

```
¶↑≤¹:2m+1mDṠ-om§+oDΠΣπ2ḣ

```

Try it online!

Ok, I'm not sure why increment  isn't working properly here. Once that works, this will be 23 (tied with Pyth).

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


title: Show tree rings age

text:
# Question
Title: Show tree rings age
## Introduction

Yesterday I saw a birthday puzzle. Congrats!!

Also this week I watched an episode of the TV show *Bones* where a dead body was found buried under a tree. To calculate the time of death, they counted the tree rings.

Tree rings form because trees grow slower during the winter and faster during the summer. Thus you can calculate the tree's age by counting the rings. Also you can see natural events like rainy or dry seasons.

## Challenge

Given an integer `n >= 1` as input, write a full program to output the tree age rings.

Because rings can change of shape use three diferent characters ('0', '\*', '+') to show climate cycles.

Age 1

```
0

```

Age 2

```
***
*0*
***

```

Age 3

```
+++++
+***+
+*0*+
+***+
+++++

```

Age 4

```
0000000
0+++++0
0+***+0
0+*0*+0
0+***+0
0+++++0
0000000

```

Size of the tree is a square of sides `2*n - 1`

## Winning

Shortest code in bytes wins.

# Answer
# Pyke, 13 bytes

```
0QV"0*+"o@A.X

```

Based on this excellent Pyke answer on another challenge, so make sure to upvote that one as well!

Try it online.

**Explanation:**

```
0              # Start with a "0" in the center
 QV            # Loop the input amount of times:
   "0*+"       #  Push string "0*+"
        o      #  Push index++ (0 by default; and increases by 1 after pushing)
         @     #  And use it to index it into the string (0-based with automatic wraparound)
          A    #  Deep apply the following command:
           .X  #   Surround the string with this character around it
               # (after which the result is output implicitly)

```
> 2 votes

# Answer
# BBC Basic, 93 bytes

```
1I.r:r=r-1:F.i=-r TOr:F.j=-r TOr:p=ABS(i):q=ABS(j):IFp<q TH.p=q
2V.48-(p MOD3)*6MOD7:N.:P.:N.

```

The abbreviated keywords help out a lot here. In line 2, I'm using the `VDU` command (equivalent to C's `putchar()`) to print each character. This is a lot more efficient than `P.MID$("0*+",p MOD3+1,1)`.

Here it is running in BeebEm3 on a Mac:
> 12 votes

# Answer
# K5, ~~27~~ ~~30~~ ~~26~~ ~~25~~ 22 bytes

```
"0"{4(|+y,)/x}/"0*+"3!1_!

```

This approach iteratively "wraps" a core (beginning with `"0"`) on all four sides using some other character (`{4(|+y,)/x}`). The sequence of seasonal wrappings is determined by a modulo 3 (`3!`) sequence. It's a bit fiddly to get the base case to line up just right.

## edit:

```
"0*+"3!u|\:u:t,1_|t:|!

```

This alternative builds the entire rectangular array at once from the provided exclusive range (`!`) reversed and joined with itself after dropping an item (`t,1_|t:|`). We then take the cartesian product maximum (`u|\:u:`), take the entire matrix modulo 3 (`3!`) and index into the array of characters.

In action:

```
  "0*+"3!u|\:u:t,1_|t:|!1
,,"0"

  "0*+"3!u|\:u:t,1_|t:|!3
("+++++"
 "+***+"
 "+*0*+"
 "+***+"
 "+++++")

  "0*+"3!u|\:u:t,1_|t:|!5
("*********"
 "*0000000*"
 "*0+++++0*"
 "*0+***+0*"
 "*0+*0*+0*"
 "*0+***+0*"
 "*0+++++0*"
 "*0000000*"
 "*********")

```
> 7 votes

# Answer
# CJam, 25 bytes

```
q~,_1>W%\+_ff{e>"0*+"=}N*

```

Test it here.

## Explanation

```
q~,       e# Read input N, turn into range [0 1 ... N-1]
_1>       e# Duplicate and cut off the zero.
W%        e# Reverse.
\+        e# Prepend to original range to give [N-1 ... 1 0 1 ... N-1]
_         e# Duplicate
ff{       e# Nested map for each pair of elements in that array.
  e>      e# Take the maximum, i.e. chessboard distance from the centre.
  "0*+"=  e# Select the right character using cyclic indexing into this string.
}
N*        e# Join the lines with line feeds.

```
> 7 votes

# Answer
## Python 2, 83 bytes

```
I=n=input()
while I+n-1:I-=1;i=abs(I);w=("O*+"*n)[i:n];print w[::-1]+w[0]*2*i+w[1:]

```

Prints line by line. Each line is chopped into three parts:

* The left cycling part, including the first repeated char.
* The repeating center part
* The right cycling part.

For `n=4`:

```
0    000000
0+    ++++    0
0+*    **    +0
0+*0        *+0
0+*    **    +0
0+    ++++    0
0    000000

```

We generate the left part in reverse as `w`, clone its last character `2*i` times, then add on the original version without the first character.
> 6 votes

# Answer
## Matlab, 63 bytes

```
n=input('')-1;x='0*+';t=abs(-n:n);x(mod(bsxfun(@max,t,t'),3)+1)

```

Example:

```
>> n=input('')-1;x='0*+';t=abs(-n:n);x(mod(bsxfun(@max,t,t'),3)+1)
5
ans =
*********
*0000000*
*0+++++0*
*0+***+0*
*0+*0*+0*
*0+***+0*
*0+++++0*
*0000000*
*********

```
> 5 votes

# Answer
## Python 2, 83 bytes

```
n=input()
R=range(1-n,n)
for i in R:print''.join('0*+'[max(i,-i,j,-j)%3]for j in R)

```

If we think of the tree as a coordinate grid, the symbol at `(i,j)` is determined by `max(abs(i),abs(j))%3`, or equivalently `max(i,-i,j,-j)%3`. For each row `i`, we join and print the symbols in that row.
> 5 votes

# Answer
# Pyth, 23 bytes

```
VK+_StQUQsm@"0*+"eS,dNK

```

Try it online: Demonstration

### Explanation:

```
VK+_StQUQsm@"0*+"eS,dNK   implicit: Q = input number
    StQ                   the list [1, 2, ..., Q-1]
   _                      reverse it [Q-1, ..., 2, 1]
       UQ                 the list [0, 1, ..., Q-1]
  +                       combine them [Q-1, ..., 1, 0, 1, ..., Q-1]
 K                        and store in K
VK                        for each N in K:
          m           K      map each element d in K to:
                 eS,dN          the maximum of d and N
           @"0*+"               and pick the corresponded char (modulo 3)
         s                   join the chars to a string and print

```
> 5 votes

# Answer
# MATLAB, ~~80~~ ~~78~~ 73 bytes

## Thanks Luis Mendo for helping me shave 5 bytes!

```
A=eye(2*input('')-1);a='0*+';a(mod(bwdist(A.*rot90(A),'chessboard'),3)+1)

```

# Example

```
>> A=eye(2*input('')-1);a='0*+';a(mod(bwdist(A.*rot90(A),'chessboard'),3)+1)

5

ans =

*********
*0000000*
*0+++++0*
*0+***+0*
*0+*0*+0*
*0+***+0*
*0+++++0*
*0000000*
*********

```

# Ungolfed and Code Explanation

```
%// Accepts an integer n from the user and creates a 2*n - 1 x 2*n - 1 identity matrix
A=eye(2*input('')-1);

%// Creates an array of three characters to print each level of the ring
a='0*+';

%// By taking the identity matrix and element-wise multiplying with its 90 degree rotated
%// version of itself, this creates a zero matrix except for the centre most
%// value, which is 1
%// This takes the distance transform via the chessboard / Chebyshev distance
%// from the centre element
%// This mirrors what "level" each square would be at
%// 1: https://en.wikipedia.org/wiki/Distance_transform
%// 2: https://en.wikipedia.org/wiki/Chebyshev_distance
b = bwdist(A.*rot90(A),'chessboard');

%// Because each level cycles through each of the characters in the
%// character array a, we need to perform a mod operation so that
%// all of the values cycle from 1 to 3
%// This changes the distance transform output so that we range
%// from 1 to 3 instead
c = mod(b,3) + 1;

%// The values in the matrix c correspond exactly to the locations
%// we need to sample from the array a and we display our result
a(c)

```

# Minor Note

`bwdist` is a function that's part of the image processing toolbox, and can only be run in MATLAB. Octave (IIRC) does not have `bwdist` implemented yet so this can't be run in Octave.
> 3 votes

# Answer
# Charcoal, 15 14 bytes

```
ＦＮ«Ｂ⊕⊗ι§0*+ιＭ↖

```

Try it online!

## explanation

```
ＦＮ                 #start a for loop, iterating n (input) times
   «                 #the loop contains 2 expressions so a body is opened
    Ｂ               #draw a box
      ⊕⊗ι          #size of box is 2*i+1
           §0*+ι     #character of the box is "0*+" index i
                Ｍ↖  #move up left 1
                     #the result is printed implicitly

```

## 15 bytes

```
ＦＮ«Ｂ⊕×²ι§0*+ιＭ↖

```

Improved version by Psuedo Nym replaced `×²` with , the in-built doubled operator.
> 3 votes

# Answer
# Python 2, 134 bytes

```
def l(x,c=1):
 p="\n\x1b[%d"%c;d=p+";%dH"%c
 if x:s=x*2-1;d+=(p+"G").join(["0*+"[(x+1)%3]*s]*s)+l(x-1,c+1)
 return d
print l(input())

```
> 2 votes

# Answer
# Perl 5, 57 bytes

Using the approach from @xnor's answer, please upvote them!

```
//,say map{qw(0 * +)[max(abs,abs$')%3]}@;for@;=- --$_..$_

```

Try it online!
> 2 votes

# Answer
# Sed, ~~277~~ 252 characters

(251 character code + 1 character command line option.)

Expects input in unary format.

```
:m
s/1/0/
s/1/*/
s/1/+/
tm
h
s/^/:/
:r
s/(.*):(.)/\2\1:/
tr
s/://
G
s/\n.//
h
:
/^(.)\1*$/ba
s/(.)(.)(\2*)\1/\1:\2\3:\1/
:c
s/(:_*)[^_](.*:)/\1_\2/
tc
:u
s/(.)(:\1*)_/\1\2\1/
tu
s/://g
H
b
:a
g
s/[^\n]+/:/
:f
s/(.*):(\n[^\n]+)/\2\1:/
tf
s/://
G
s/\n//

```

Sample run:

```
bash-4.3$ sed -rf treering.sed <<< 1
0

bash-4.3$ sed -rf treering.sed <<< 11
***
*0*
***

bash-4.3$ sed -rf treering.sed <<< 111
+++++
+***+
+*0*+
+***+
+++++

bash-4.3$ sed -rf treering.sed <<< 1111
0000000
0+++++0
0+***+0
0+*0*+0
0+***+0
0+++++0
0000000

```
> 1 votes

# Answer
# Matlab 92

```
input('')-1;x=ones(2*n+1,1)*abs(-n:n);z=mod(max(x,x'),3);z(z>1)=2;z(z<1)=7;disp([z+41,''])

```
> 1 votes

# Answer
# PowerShell, 68 bytes

```
$f={($l=($c='+0*'[$_--%3])+"$c$c"*$_)
if($_){&$f $_|%{"$c$_$c"}
$l}}

```

Try it online!

Unrolled:

```
$f={
    $_--
    $char='+0*'[$_%3]
    $line=$char+"$char$char"*$_
    Write-Output $line
    if($_){
        &$f $_|ForEach-Object{
            Write-Output "$char$_$char"
        }
        Write-Output $line
    }
}

```
> 1 votes

# Answer
# Canvas, 15 bytes

```
Ｈ0*+＠¹２×╷：＊；２２╋

```

Try it here!

Can probably be shortened further.

## Explanation

```
H0*+@¹2×|:*;22╋
H               push an empty art object, start a loop using input
 0*+            string "0*+"
    @           get the nth element, circularly <-----------+
     ¹          loop iteration                              |
      2×        double it                                   |
        |       decrement it                                |
         :      duplicate it                                |
          *     use that to box the character from here ----+
           ;    swap the box with the previous iteration
            22╋ overlap at (2,2)

```
> 1 votes

# Answer
# Japt `-h`, 20 bytes

```
Ñ ÆP=Õû"0*+"gX=z)XÑÄ

```

Try it or run all test cases

```
Ñ ÆP=Õû"0*+"gX=z)XÑÄ     :Implicit input of integer U
Ñ                        :U*2
  Æ                      :Map each X in the range [0,U*2)
   P=                    :  Reassign to P (initially the empty string)
     Õ                   :  Transpose P
      û                  :  Centre pad with
       "0*+"             :    Literal string
            g            :    Get character at 0-based index
             X=          :      Reassign to X
               z         :      X floor divided by 2
                )        :    End get
                 XÑÄ     :    To length X*2+1

```
> 1 votes

# Answer
# JavaScript (ES6), 114

Using alert for output - bad proportional font and the result is ugly. In the snippet below the alert is redirect to the snipped body, giving a better result. The newline inside backticks is significant and counted.

Test running the snippet in Firefox.

```
/* Redefine alert for testing purpose */ alert=x=>O.innerHTML=x;

[...'*+0'.repeat(n=prompt()-1)].map((c,i)=>i<n?b=[z=c.repeat(i-~i),...b,z].map(r=>c+r+c):0,b=[0]);alert(b.join`
`)
```

```
<pre id=O></pre>
```
> 0 votes

# Answer
# Ruby, 85 characters

```
puts (m=0..(n=gets.to_i-1)*2).map{|i|m.map{|j|"0*+"[[(i-n).abs,(j-n).abs].max%3]}*""}

```

Sample run:

```
bash-4.3$ ruby -e 'puts (m=0..(n=gets.to_i-1)*2).map{|i|m.map{|j|"0*+"[[(i-n).abs,(j-n).abs].max%3]}*""}' <<< 4
0000000
0+++++0
0+***+0
0+*0*+0
0+***+0
0+++++0
0000000

```
> 0 votes

# Answer
# Moonscript - 104 bytes

```
m=io.read!
n=2*m-1
for y=1,n
 io.write ({'0','*','+'})[(math.max y-m,x-m,m-y,m-x)%3+1]for x=1,n
 print!

```
> 0 votes

# Answer
# C, 138 bytes

```
j,k,l;t(i){l=2*i;char*c=calloc(l,l);memset(c,10,l*(l-2));for(;k<i;++k)for(j=k;j<l-1-k;)memset(c+j++*l+k,"+0*"[(i-k)%3],l-2*k-1);puts(c);}

```

Function `t` taking one integer parameter - the age.

Ungolfed (with `main` function to easily run the above one):

```
#include "stdlib.h" /* calloc - only necessary for 64-bit system */
j,k,l;t(i)
{
    l=2*i;
    char*c=calloc(l,l);
    memset(c,10,l*(l-2)); /* fill with '\n' */
    for(;k<i;++k)for(j=k;j<l-1-k;)memset(c+j++*l+k,"+0*"[(i-k)%3],l-2*k-1);
    puts(c);
}

main(int c,char**v)
{
    t(atoi(v[1]));
}

```

The `stdlib.h` may be necessary on some systems, because without it the return type of the undeclared function `calloc` would default to `int`. Because `int` and `char*` are not necessarily of same size, an invalid pointer could be written into `c`. In most 32-bit systems both `char*` and `int` have same size, but this is not true for 64-bit systems.
> 0 votes

# Answer
# 05AB1E, 23 bytes

```
0¸sG…0*+Nè©δ.ø®N·>×.ø}»

```

Try it online or verify a few more test cases.

**Explanation:**

```
0¸                     # Start with a 0 wrapped in a list as the center: [0]
  sG                   # Loop `N` in the range [1, input):
    …0*+               #  Push string "0*+"
        Nè             #  Use `N` to index into this string
                       #  (0-based with automatic wraparound)
          ©            #  Store this character in variable `®` (without popping)
           δ.ø         #  Surround each line with this character
               N·>     #  Push 2 * `N` + 1
              ®   ×    #  Repeat the character `®` that many times as string
                   .ø  #  And surround the list with this string
   }»                  # After the loop: join all strings by newlines
                       # (after which the resulting string is output implicitly as result)

```
> 0 votes

# Answer
# PowerShell, 118 bytes

```
param($n)((--$n..0+1..$n|%{-join(($z=($x='0*+'*$n)[$n..$_])+"$($x[$_])"*2*$_+($z[($n-$_-1)..0],'')[$n-eq$_])}),0)[!$n]

```

Try it online!

:(
> 0 votes

# Answer
# , 22 bytes

```
'0*+'{~3|>./~&:|@i:@<:

```

Try it online!
> 0 votes

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