title: Will Jimmy fall off his platform?

text:
# Question
Title: Will Jimmy fall off his platform?
# Backstory

Meet my friend Jimmy:

```
/o\

```

Jimmy is a little character who likes to stand on platforms. Here's Jimmy safely standing on a platform:

```
         /o\
  -------------

```

Now, Jimmy has a good sense of balance, so he can safely stand with one leg off of the platform, like so:

```
   /o\
    -------------------

```

Although if he stands with two or more body parts off of the platform, he will fall. Both of these are examples where Jimmy will fall:

```
/o\                                       /o\
  ----------        ----------------------

```

# The challenge

Your challenge is to write a program to determine, given a string with Jimmy's platform and position, if Jimmy can stand on the platform without falling off.

* Input: Two lines showing Jimmy's position and the position of the platform under him. This can be from two separate inputs, a single input, or an array of some sort.

1. You may take input through any reasonable form, includings functions and standard input. Only resort to hard-coding if your language does not support the other input methods.

* Output: The boolean values true and false, or the integers 1 or 0 to represent true/false respectively.

1. The boolean value is based off of whether Jimmy can stay on the platform or not - true if Jimmy can stay on the platform, or false if he will fall off.

* The platform size is arbitrary and can be changed at will. Your program should account for that.

1. The platform cannot be a length of zero, and the platform must be complete (no holes in the platform).
2. Remember that Jimmy falls off when two of his body parts are hanging off the platform. A body part is one ASCII character of his body.
3. Trailing whitespace at the end of the platform is not required, but your program should account for both situations, where there is whitespace after the platform and where there is not.

# Test cases

```
         /o\               ✔ TRUE
  -------------

/o\                        ✔ TRUE
 ----------

                    /o\    ❌ FALSE
  ------------------

               /o\         ❌ FALSE
  -------

    /o\                    ❌ FALSE
     -

```

# Scoring

This is , so lowest byte count wins.

# Answer
# Jelly, 6 bytes

```
n⁶Sċ2Ẓ

```

Try it online!

Explanation:

```
n⁶Sċ2Ẓ  args: z (e.g. [['/', 'o', '\\'], [' ', '-']] => 0)
        implicit return value: z ([['/', 'o', '\\'], [' ', '-']])
n⁶      dyad-nilad pair ([[1, 1, 1], [0, 1]])
 ⁶       4th command-line argument or space [4th CLA assumed absent] (' ')
n        vectorized inequality ([[1, 1, 1], [0, 1]])
  S     reduction by addition with base case 0 ([1, 2, 1])
   ċ2   dyad-nilad pair (1)
    2    literal (2)
   ċ     number of occurrences of right in left (1)
     Ẓ  primality (0)

```
> 21 votes

# Answer
# JavaScript (ES6), 38 bytes

Takes input as `(a)(b)`. Returns \\$0\\$ or \\$1\\$.

```
a=>b=>b[a.search`o`]=='-'&/--/.test(b)

```

Try it online!

### How?

We look for the position of the middle part `"o"` of Jimmy's body in the first string and test wether there's a dash in the second string at the same position.

```
b[a.search`o`] == '-'

```

The only case where Jimmy would be unsafe in this situation is with a single-dash platform:

```
/o\
 -

```

So we additionally make sure that the platform has a width of at least \\$2\\$:

```
/--/.test(b)

```

---

# JavaScript (ES6), 36 bytes

Alternate version if we assume that there's always either dashes or spaces below Jimmy (i.e. the input is rectangular).

```
a=>b=>b[a.search`o`]!=0&/--/.test(b)

```

Try it online!

Takes advantage of the fact that the coercion to a numeric value is \\$0\\$ for a space and *NaN* for a dash.
> 20 votes

# Answer
## Python 3, ~~88~~ 43 bytes

Input is given in the form of a list containing two strings: the first string is the first line; the second string is the second line.

```
lambda a:sum(1-(" "in i)for i in zip(*a))>1

```

Try it online!

Another version, tying for 43 bytes (I haven't been able to get it shorter than 43):

```
lambda a,b:b[a.find("/"):][:3].count("-")>1

```

Try it online!

Down by 42 bytes thanks to a tip from Jo King.

Old Version:

```
lambda s:sum((s.split("\n")[1]+" "*len(s))[i]=="-"and s[i]!=" "for i in range(len(s)))>1

```

-2 bytes thanks to Sriotchilism O'Zaic.

This works by taking two separate inputs, then pairing up corresponding letters. It counts the number of pairs where neither character is a space, then returns True if that number is greater than 1.
> 10 votes

# Answer
# Excel, ~~67~~ ~~45~~ 44 bytes

```
=(MID(A2,FIND("o",A1),1)="-")*(TRIM(A2)>"-")

```

Put Jimmy in `A1`, on a platform in `A2`.

2 conditions checked:

* Is Jimmy's torso (`o`) on the platform?
* Is the platform more than just `-`?
> 10 votes

# Answer
# Python 2, ~~42~~ 37 bytes

```
lambda j,p:'--'in p[j.find('/'):][:3]

```

Try it online!

5 bytes thx to negative seven
> 9 votes

# Answer
# Perl 6, 18 bytes

```
{?/''B|Bq/}o&[~^]

```

Try it online!

Takes a two parameters and returns a boolean of whether Jimmy will stay on the platform. This works by XORing the two lines together and checking if either part of Jimmy is still on the platform.

### Explanation:

```
             &[~^]   # String XOR operator
{          }o        # Combined with the anonymous function
 ?/       /          # That checks for the regex match
   ''B              # Unprintable, B, which is "/o" ~^ "--"
       |Bq           # Or B, q, which is "o\" ~^ "--"

```
> 8 votes

# Answer
# Haskell, 34 bytes

```
a#b=[1|(p,'-')<-zip a b,p>' ']>[1]

```

Try it online!

I got this one by combining my below technique with the other haskell answer.

# Haskell, 45 bytes

```
x#'-'|x/=' '=1
x#y=0
(((>1).sum).).zipWith(#)

```

Try it online!

This counts the number of body parts (non-space characters) that are on top of the platform and then checks it is greater than 1. The reason we count body parts on the platform rather than body parts off is that `zipWith` will chop the top line to be the length of the bottom and thus can chop off Jimmy's body parts. This prevents us from having to do something like `cycle" "` to pad the list.
> 7 votes

# Answer
# ///, ~~85 93~~ 87 bytes

```
/~/\/\///\/o\\/(o)~
/
~
~/ (o) /(o)~ (o)-/(o)~- -/--~(o) - ~/) ~/)-~/o~/(-/1~-~/(~/)~

```

Try it online!

Output's a 1 if Jimmy is safe. Otherwise outputs nothing. (Unary 1 and 0.) Because there is no other way to take input in ///, it needs to be hard-coded:

```
/~/\/\///\/o\\/(o)~
/
~
~/ (o) /(o)~ (o)-/(o)~- -/--~(o) - ~/) ~/)-~/o~/(-/1~-~/(~/)~ //<INPUT HERE>

```

For example:

```
/\/o\\/(o)//
/
//
/// (o) /(o)// (o)-/(o)//- -/--//(o) - ///) ///)-///o///(-/1//-///(///)//         /o\
  -------------

```

(Try it online!)

Note the space after the `<INPUT HERE>`.

**Explanation:**

NOTE! The explanation code cannot be run due to the comments. The comments are enclosed in curly braces. Also, the original code uses a golf where `//` is replaced with `~`. This code is omitted from the explanation.

```
/\/o\\/(o)/            {replace Jimmy with a Jimmy with curvy arms, because slashes are hard to manipulate in this language}
/
/
/                      {remove unneeded spaces after Jimmy, but before the floor}

/
//                     {get rid of the line break

/ (o) /(o)/            {remove all the spaces before both Jimmy and the floor}
/ (o)-/(o)/            {for each floor tile, remove it and one space before Jimmy. This detects whether Jimmy lines up with the floor.}
                       {If Jimmy is before the floor, then there will be extra floor.}
                       {If Jimmy is behind the floor, then there will be extra spaces before Jimmy.}
/- -/--/               {Handle the case where there is a hole beneath Jimmy but he is still well-supported}

/(o) - //              {Handle the case where only Jimmy's head is on the floor. The space at the end of the code is necessary for this.}
/) //                  {The rest of the substitutions clean up the result and handle each of the possible results that could exist at this point}
/)-//
/o//
/(-/1/
/-//
/(//
/)//

              /o\
               --
 {there is a space right before this comment. The comment is only here to make the space visible and explain itself.}

```

---

* +8 bytes to fix a bug
* -6 bytes by applying a standard `///` golf trick.
> 6 votes

# Answer
# ///, 57 bytes

```
/|/\/\///\/o\\/J| J/J*|
/|* /|  -/  | /|*-/|--/!|-/|*/|J|

```

Try it online!

Append the input to the end of the program in order to run. Returns the empty string if Jimmy falls off the platform, a string of exclamation points otherwise.

* `/|/\/\//` replaces `|` with `//`, which makes the code both shorter and more readable (`|` is used to demarcate each replacement)
* `/\/o\\/J| J/J*/` replaces Jimmy with `J` for brevity and changes the space to the left of him to `*` to the right of him
* The next replacement gets rid of newlines.
* `/* /| -/ | //` cancels out `*`s and with the space to the left of the platform. If there are two or more spaces left, Jimmy is falling off to the left, and the platform is deleted. This part also removes any whitespace to the right of the platform.
* `/*-/|--/!/` cancels out `*`s and with length of the platform. If there are at least two `-` left, Jimmy isn't falling off to the right, so they are replaced with a `!`.
* `/-/|*/|J//` deletes every remaining character that isn't `!`
> 6 votes

# Answer
# Dyalog APL Extended, ~~11~~ ~~10~~ 8 bytes

```
2≤1⊥∧⌿⍤<

```

Try it online!

Explanation:

```
2≤1⊥∧⌿⍤<  a monadic train
       <  Compare the input with the implicit prototype element - a space.
          Returns a boolean matrix of characters that are greater than 0x20
    ∧⌿⍤   and-reduce that, i.e. places where both Jimmy and a platform is
  1⊥      base 1 decode, aka sum - the amount of body parts over the platform
2≤        is that greater-or-equal to 2?

```

-2 thanks to Adám.
> 5 votes

# Answer
# MathGolf, ~~6~~ 14 bytes

```
`^@╞^αmÆû-oñ╧╙

```

Try it online!

8 bytes had to be added to account for the edge case presented by Nick Kennedy.

Checks if `"-o-"` is a substring of the zipped string of both lines, and the zipped string where the first input line has the first character removed. Takes input as two separate strings, with the only change being that the character is input as `/o\\`, since `\\` is the correct way to input a backslash in a string in MathGolf.

## Explanation

```
`                duplicate the top two items
 ^               zip top two elements on stack
  @              rrot3
   ╞             discard from left of string/array
    ^            zip top two elements on stack
     α           wrap last two elements in array
      mÆ         explicit map using 5 operators
        û-oñ     push "-o" and palindromize to make "-o-"
            ╧    pop a, b, a.contains(b)
                 map block ends here
             ╙   max of list

```
> 4 votes

# Answer
# chevron \- 126 bytes

not an improvement over my old answer (at all), but rewritten after a rewrite of chevron itself.

```
> >^j
0>^i
^i+1>>^i
^j,^i~c>>^h
->+2??^h=/
->-3
> >^q
^q~s>>^s
->+5?^i>^s
^_p>^s
^q^s^s,^i,3~c>>^p
->+2??^s^s^s~^s^p^s
><1
><0

```
> 4 votes

# Answer
# EXCEL, ~~94~~ 71 bytes . ~~VBA (Excel), 87 bytes~~

`A1` = Jimmy , `A2` = platform

-23 bytes. Thank you @Wernisch.

```
=(FIND("-",A2)-FIND("/",A1)<2)*(FIND("\",A1)-LEN(A2)<2)*(TRIM(A2)<>"-")

```

~~?`[(FIND("-",A2)-FIND("/",A1)<2)*(FIND("\",A1)-LEN(A2)<2)]*(len(replace([A2]," ",""))>1)`~~
> 3 votes

# Answer
# 05AB1E (legacy), ~~9~~ ~~8~~ 7 bytes

```
ζðм2ùgp

```

-1 byte thanks to *@Mr.Xcoder* with the approach of `ðм2ù`.

Input as a list of two strings.

Only works in the legacy version of 05AB1E, because `ζ` can transpose a list of strings as well as a 2D list of characters, whereas the `ζ` in the new 05AB1E version only works with the 2D list of characters.

Try it online or verify all test cases.

**Explanation:**

```
ζ        # Zip/transpose; swapping rows/columns, with space as default filler
 ðм      # Remove all spaces from each string
   2ù    # Only leave strings of size 2
     g   # Count how many there are left
      p  # Check if this is a prime (2 or 3)
         # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Ruby, 28 bytes

```
->a,b{!(/--/!~b[a=~/\//,3])}

```

Try it online!
> 3 votes

# Answer
# Excel, 36 bytes

```
=LEN(TRIM(MID(A2,FIND("/",A1),3)))>1

```

Jimmy in `A1`, on a platform in `A2`.

Finds the position of Jimmy, and takes the 3 bytes of the platform and trims off spaces. If the resulting platform length is long enough, Jimmy stands.
> 3 votes

# Answer
# Husk, 5 bytes

```
¬εδ#&

```

Try it online! This function takes the two lines as separate arguments. `δ#&` zips the two strings together and counts the number of pairs in which both characters are truthy, i.e., neither is a space character, and `¬ε` tests that the count is greater than 1.
> 3 votes

# Answer
# , 35 bytes

```
function(x)sum(colSums(x!=" ")>1)>1

```

Try it online!

Based on @EriktheOutgolfer’s excellent Jelly answer so please upvote that one too!

Input is a 2-d matrix of characters.
> 2 votes

# Answer
# Haskell, 59 bytes

```
f a b=sum[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']<2

```

Try it online!

The function is called like so: `f "/o\\ " " -- "`

How it works (for `f "/o\\" " -"`):

`b++cycle" "` \- Adds an infinite number of spaces after `b` to ensure that Jimmy is always above a `-` or  (`" -"``" - ..."`

`zip a$b++cycle" "` \- Zips the two strings together (`[('/',' '), ('o','-'), ('\\',' ')]`)

`(p,q)<-zip a$b++cycle` \- For each pair in the zipped list

`[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']` \- Generates a list of `1`s, whose length is the number of pairs satisfying the conditions:

`elem p"/o\\"` \- The character in the top string is one of Jimmy's body parts. (Satisfied by all three pairs in this example)

`q==' '` \- The character in the bottom string is a space. (Satisfied by `('/', ' ')` and `('\\', ' ')`)

So, the pair has to be one where one of Jimmy's body parts is above a space.

Because in this example, two pairs satisfy both conditions, the list is `[1,1]`

`sum[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']` \- Take the sum of those `1`s (i.e. the length of the list), which in this example is `2`.

`sum[1|(p,q)<-zip a$b++cycle" ",elem p"/o\\",q==' ']<2` \- Check if the number of body parts above a space is less than 2. In this example, it's not, so Jimmy will fall off. :(
> 2 votes

# Answer
# C (gcc), 73 bytes

```
f(s,t,c)char*s,*t;{for(t=strchr(s,c=10);*s%5**t;)c-=*++t%2**s++%8;c=c<0;}

```

Try it online!
> 2 votes

# Answer
# Kotlin, 60 bytes

```
fun String.c(b:String)=zip(b){i,j->i>' '&&j>' '}.count{it}>1

```

Explanation:

```
fun String.c  # Define an extension function on string, so we don't have to provide a first argument (and we also have string method calls for free)
(b:String)    # Pass the second string as argument
=             # Shorthand syntax for fun body
zip(b)        # Essentially a.zip(b). Creates a List<Pair> by joining both arrays.
              # Takes care of trailing whitespace, because it will be the size of the smaller array
{i,j->        # Declare a transformer lambda as second function argument
i>' '&&j>' '} # This essentially translates to: If i!=' ' and j=='-'
.count{it}    # Count the true values
>1

```
> 2 votes

# Answer
# Julia 1.0, ~~42~~ 40 bytes

```
y(a,b)=strip(b[findfirst("/o\\",a)])>"-"

```

Try it online!
> 2 votes

# Answer
# SnakeEx, 13 bytes

```
j:<R>o<T>\-\-

```

SnakeEx does well because it's a 2D pattern-matching language, but not too well because it wasn't designed to be very golfy. Try it here!

### Explanation

```
j:             Define the main snake, j (for Jimmy)
  <R>          Pivot right (i.e. downward, since the snake starts out moving to the right)
     o         Match Jimmy's torso (or is it his head?) and move down
      <T>      Turn either left or right
         \-\-  Match two platform characters

```

This will match if there are two platform characters under Jimmy, or fail to match if there are not. We don't need to consider the case where there are platforms only under his legs, since the platform cannot have holes.
> 2 votes

# Answer
# Japt, 8 bytes

```
Õ·kèS Êz

```

Try it
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~44~~ ~~40~~ 39 bytes

*-4 bytes thanks to Jo King*

```
a=>b=>a.Zip(b,(x,y)=>x>y?y:0).Sum()>109

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 16 bytes

```
 (.*¶).
$1
¶ ?--

```

Try it online! Link includes test suite. Explanation:

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

```

While there is still a space on the first line, and both lines still have more than one character, delete the space and the first character of the next line. Note: This assumes that there is no trailing space after Jimmy. +1 byte needed if trailing space needs to be allowed.

```
¶ ?--

```

Check that there are at least two pieces of platform under Jimmy.
> 1 votes

# Answer
# PowerShell, ~~63..55~~ 53 bytes

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

```
param($j,$f)''+($f|% t*y|?{$j[$i++]-gt32})-match'- -'

```

Try it online!

Takes input as two lines.

Unrolled:

```
param($j,$f)            #Take $jimmy and $floor
''+                     #Implicitly converts next part to string
($f |% ToCharArray      #Convert $f to a char[] and...
    |?{                 #Only take the chars where...
        $j[$i++]-gt32   #The same indexed char in $j's ASCII # is > ' ' i.e. only get /o\
     }
)-match'- -'            #Arrays.ToString are joined with a space and we need 2 -'s

```
> 1 votes

# Answer
# Perl 5 `-pl`, 42 bytes

```
/o/g;$_=(($_=<>)=~/./g)[-1+pos]eq'-'&&/--/

```

Try it online!
> 1 votes

# Answer
# Ruby 2.5.3, 44 bytes

```
->a,b{a.zip(b).map(&:join).grep(/\S-/).size>1}

```

Input taken as two arrays. Definitely not the most golf-friendly approach (see G B's answer), but I like any excuse to use the `zip` function.
> 1 votes

# Answer
# 40 column Commodore BASIC (C64, C16/+4, C128, PET, C64Mini) - non-competing`*` \- 98 tokenized and BASIC bytes used

```
 0a=rN(.)*36:b=rN(.)*39:c=-rN(.)*(b-39):fOi=0tob:a$=a$+"-":nE:?tAa)"/o\
 1?tAc)a$:?-(a>c-2anda<c+b+2)

```

Here is the unobfuscated listing for explanation purposes

```
 0 let a=rnd(0) * 36
 1 let b=rnd(0) * 39
 2 let c=-rnd(0) * (b - 39)
 3 for i=0 to b
 4  let a$=a$+"-"
 5 next i
 6 print tab(a);"/o\"
 7 print tab(c);a$
 8 print -(a>c - 2 and a<c + b + 2)

```

The variable `a` is used for positioning Jimmy (using `PRINT TAB(A)` which is zero-indexed).

The varaible `b` is used for the length of the platform.

And finally the variable `c` is used for the position of the platform.

The loop in lines 3 through to 5 inclusive builds the platform for Jimmy, with line 6 printing Jimmy at his pre-determined position, and 7 for the pre-determined position of the platform. Finally, `1` or `0` is outputted to represent our `TRUE` or `FALSE` value.

Note, the listing includes keyword abbreviations to ensure we break the 80 character limit per line on standard Commodore C64 BASIC.

`* Assumed non-competing because PETSCII is not ASCII. Jimmy looks better in PETSCII though, of course.`
> 1 votes

# Answer
# Bash, 49 bytes

```
[[ "${1:$((`expr index "$0" /`-1)):3}" =~ "--" ]]

```

Jimmy input as command line parameter 0, the platform as parameter 1; Must be aware of Bash's separating and eating whitespace (use single quotes):

```
bash -c '[[ "${1:$((`expr index "$0" /`-1)):3}" =~ "--" ]]' '   /o\' '  -------'

```
> 1 votes

# Answer
# Python 3.7, 71 56 Bytes

```
lambda s:sum(j in'/o\\'and p=='-'for j,p in zip(*s))>1

```

Very simple version and the shortest I could think of using this approach. Input `s` is a list of two strings, the first one for the Jimmy-row, the second one for the platform. Zip the characters which are above one another and then check whether `-` is below a part of Jimmy in at least two instances.

EDIT: Reduced by quite a few Bytes thanks to Blue!
> 1 votes

# Answer
# C (gcc), 103 bytes

```
i,j,l;f(char*s){for(i=0;*s-10;j=*s++-47?j:i)++i;l=strlen(s)>j+1;s+=j;return l&&*s+s[1]+(s[2]?:32)>109;}

```

Try it online!

Would be much shorter (75 bytes), if it could be assumed that there is trailing whitespace after the platform.
> 0 votes

# Answer
# Retina, ~~31~~ 29 bytes

```
^(.)*/.*¶(?<-1>.)*(?(1)!) ?--

```

Try it online!

Saved 2 bytes thanks to Neil!

A simple regex that determines whether at least two pieces of the platform are directly beneath Jimmy. Assumes that the input will contain no `!` characters.
> 0 votes

# Answer
# Japt , 9 bytes

-1 byte if the input can be reversed.

```
VtUao)è-²

```

Try it online
> 0 votes

# Answer
# , 18 bytes

```
0vt/"_dj.d3lVkp0#x

```

Try it online!

Output whitespace only if jimmy fall of the platform. Output something non-whitespace if jimmy stay on the platform.
> 0 votes

# Answer
# Japt `-!`, 7 bytes

```
ÕèSi.)z

```

Try it

```
ÕèSi.)z     :Implicit input of multi-line string
Õ           :Transpose
 è          :Count the occurrences of
  S         :  Space
   i.       :  Prepended with ".", giving the regex /. /g
     )      :End count
      z     :Floor divide by 2
            :Implicit output as Boolean

```
> 0 votes

# Answer
# Pyth, 9 bytes

```
!!tt#rL6C

```

Try it here! <sub><sup>(Note: This is a temporary interpreter, hosted on pythtemp.herokuapp.com; the official pyth.herokuapp.com can't be used for now)</sup></sub>

If swapping truthy-falsy values were allowed, this would become 8 bytes by dropping one of the `!`s (awaiting confirmation). Moreover, if outputting an empty list for the case when Jimmy falls and a non-empty list otherwise would be an option, both `!`s could be dropped.

### How it works

```
!!tt#rL6C – Full program. Receives a list of two strings through STDIN.
        C – Transpose / Zip (switch from rows to columns)
     rL6  – Strip the whitespace on both sides of each column.
   t#     – Filter-keep those that have a tail (i.e. that are length-2).
  t       – Tail. The result will be non-empty iff Jimmy doesn't fall.
!!        – Double negation (to output as a boolean...).

```
> 0 votes

# Answer
# Attache, 38 bytes

```
{2>Sum!`~&Sum[Ord@Grid@_-39]=>1'46'65}

```

Try it online!

## Explanation

We convert the input string to a grid of ASCII codepoints, subtract 39 from each, then take the Sum, columnwise. (`Sum[Ord@Grid@_-32]`). Then, we bind this array to the `~` operator, which in this case counts the number of times the argument occurs in the bound array. We apply this function to each member of the array `1'46'65` with `=>`, which correspond to various body parts not above a platform. We then take the sum of this resulting array with `Sum!`. This is the count of body parts not above the platform. Finally, we check to see that `2` exceeds this sum; if it does, then we return `false`, for Jimmy has fallen. If it does not, we return `true`, for Jimmy is quite safe on his perch.
> 0 votes

# Answer
# Charcoal, 19 bytes

```
η⸿Ｐθ…θ⌕θo≔№ＫＭ-ζ⎚›ζ¹

```

Try it online! Link is to verbose version of code. Outputs `-` if the Jimmy will balance, nothing if he will fall off. Explanation:

```
η

```

Print the platform.

```
⸿

```

Move down a line. (Reversed gravity turned out to be golfier.)

```
Ｐθ

```

Print Jimmy without moving the cursor.

```
…θ⌕θo

```

Print Jimmy's leg leaving the cursor over his body.

```
≔№ＫＭ-ζ

```

Count the number of adjacent `-`s from the platform.

Clear the canvas.

```
›ζ¹

```

Output a `-` if the platform was large enough.
> 0 votes

# Answer
# Brain-Flak, 210 bytes

```
{({}<>)<>}<>{({}[(()()()()()){}]<>)<>}<>({<(<({}[((()()()()()){}()){}])>{()(<{}>)}{}<{({}<>)<>}{}({}[((((()()()()()))){}{}){}{}])>[()()]{()(<{}>)}<<>{({}<>)<>}<>>)>[()]{()(<{}>)}{}}<>)(()[{<({}())>{()<{}>}}]{})

```

Try it online!

String parsing is hard in Brain-Flak. It considers anything on the first line other than space to be Jimmy and anything on the second line other than `-` to be open air. The reason we test for `-` instead of space is that Brain-Flak pads the input indefinitely to the right with nulls (ASCII codepoint 0) which we need to consider open air. This luckily means we don't have to worry about needing trailing whitespace in the input.
> 0 votes

# Answer
# PHP, 90 80 bytes

**Code**

```
<?=substr_count(substr(($v=explode("
",$argv[1]))[1],strpos($v[0],"/"),3),"--");

```

Try it online!

**Mistakenly coded allowwing jimmy with just a leg on the edge**

```
<?=count($v=explode("
",$argv[1]))>1&&substr_count(substr($v[1],strpos($v[0],"/"),3),"-");

```

Try it online!

**Explanation**

```
<?=
substr_count(
substr(($v=explode("\n",$argv[1]))[1],// explode and get Jimmy body
        strpos($v[0],"/"),  // find "/" position (position start)
        3),                 // substring of the platform length
        "--");              // platform has to contain "--" somewhere
//
//

```
> 0 votes

# Answer
# Elm 0.19, 99 bytes

```
f j p=List.sum(List.map2(\a b->if a/=' '&&b/=' 'then 1 else 0)(String.toList j)(String.toList p))>1

```

Port of Maxwell's Python 3 answer. Verify all test cases here.
> 0 votes

# Answer
## Pip, 29 bytes

```
sN(STbALsRL#a)@>(a@?"/")@<3<2

```

The padding with spaces part took a while to figure out.

The second argument ***must*** have atleast one space before it, otherwise the program will error. Add a space to the first argument as well for testing.

### Explanation:

```
sN(STbALsRL#a)@>(a@?"/")@<3>1
  (STbALsRL#a)                pad second line with spaces, convert to a simple string
                (a@?"/")      Find index of jimmy's right hand in first line
              @>              Get substring of second line after index taken in prev step
                        @<3   cut it to the three planks under Jimmy
sN                            Find number of spaces in substring i.e.
                                "---" => 0, " - " => 2
                           <2 find out if Jimmy is standing on thin air(hopefully not)

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog Unicode), 11 chars

```
2>1⊥' '<.=↑

          ↑  ⍝ from nested vector of char vectors to char matrix
    ' '<.=   ⍝ for each column gives 1 if there's a space in the
             ⍝ lower row but not in the upper row, 0 otherwise
2>1⊥         ⍝ is the count of 1s less than 2?

```

Try it online!
> 0 votes

# Answer
# Batch ~~233~~ 198 bytes

```
@Set j=%~1&set p=%~2
@Set v=%p:-=&Set/Az+=1+0%
@Set v=%v: =&Set/Az+=1%
@Cmd/VON/C"For /l %%i in (0 1 !z!)Do @(Echo(!j:~%%i,2!!p:~%%i!|Findstr/c:"/o--" /c:"o\\--">nul&&Exit/b 0)"&&Echo(1||Echo(0

```

Note:

* input is done using args when the program is run from the command line
    + IE: `Jimmy.bat "/o\" " - "`

How:

```
    @Set j=%~1&set p=%~2

```
* Take input for `j`immy and `p`latform

```
    @Set v=%p:-=&Set/Az+=1+0%

```
* Count number of `-` characters - `+0` avoids missing operator error for undefined `z` variable

```
    @Set v=%p: =&Set/Az+=1%

```
* Count number of  characters

```
@Cmd/VON/C"For /l %%i in (0 1 !z!)Do @(Echo(!j:~%%i,2!!p:~%%i!|Findstr/c:"/o--" /c:"o\\--">nul&&Exit/b 0)"&&Echo(1||Echo(0

```
* Iterate over the length of the string in a new cmd instance with delayed expansion, trim jimmys string to 2 characters to test String pairings from the offset of the iterations count and test for a match to "/o--" or "o\\--" using findstr. On match, exit the instance using exit /b 0 to return a 0 errorlevel to indicate success.

```
&&Echo(1||Echo(0

```
* ouput result using `&&` success `||` Fail conditional logic. (findstr returns a positive errorlevel if no match is made)
> 0 votes

# Answer
# ayr, 11 bytes

```
:2>+/</.32=

```

# Explanation

```
       32=   Find spaces
    </.      Flatten to vector, 1 if lower row has a space but the upper does not
  +/         Sum this list
2>           Is less than two?

```
> 0 votes

# Answer
# Burlesque, 22 bytes

```
lnp^'/FiR@3.+si'-CN1.>

```

Try it online!

```
lnp^  # Split into lines and push onto stack
'/Fi  # Find the index of '/' (Jimmy's left leg)
R@3.+ # Index..Index+2
si    # Select these indices from the platforms
'-CN  # Count of -s
1.>   # Greater than 1

```
> 0 votes

# Answer
# Stax, 7 bytes

```
╔≈╔'♀B┬

```

Run and debug it
> 0 votes

# Answer
# Vyxal, 7 bytes

```
ð=†∑2Oæ

```

Try it Online!

## How?

```
ð=†∑2Oæ
ð=†     # For each, is it not a space?
   ∑    # Sum
    2O  # Count the amount of twos
      æ # Is this a prime?

```
> 0 votes

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


title: Mat Printing Matrix

text:
# Question
Title: Mat Printing Matrix
A manufacturing company wants to print a design on mats of varying dimensions, and they hired you to program a robot to make these mats. The design consists of alternating rings of any 2 symbols on a mat. Below are some sample looks:

Column 9 by Row 7

Symbol 1: @

Symbol 2: -

Input: `9 7 @ -`

```
@@@@@@@@@
@-------@
@-@@@@@-@
@-@---@-@
@-@@@@@-@
@-------@
@@@@@@@@@

```

Column 13 by Row 5

Symbol 1: @

Symbol 2: -

Input: `13 5 @ -`

```
@@@@@@@@@@@@@
@-----------@
@-@@@@@@@@@-@
@-----------@
@@@@@@@@@@@@@

```

Column 3 by Row 5

Symbol 1: $

Symbol 2: +

Input: `3 5 $ +`

```
$$$
$+$
$+$
$+$
$$$

```

Column 1 by Row 1

Symbol 1: #

Symbol 2: )

```
#

```

Write a program that takes in the length, breadth, symbol 1 and symbol 2 and prints out the mat design on the screen.

\*The row and column number is always odd

Shortest code wins!

# Answer
# Jelly, 9 bytes

Takes the `length,breadth` as the first argument and the symbols as a second argument.

```
«þ/U«ṚƊịY

```

Try it online!

```
«þ/        -- Minimum table of the left argument
      Ɗ    -- On that table:
   U«Ṛ     --   Minimum of each row reversed and the columns reversed
       ị   -- Index into the symbols (modular indexing)
        Y  -- Join by newlines

```
> 7 votes

# Answer
# Pari/GP, 86 bytes

```
f(a,b,c,d)=[print(concat(r~))|r<-matrix(a,b,i,j,[c,d][vecmin([i-1,j-1,a-i,b-j])%2+1])]

```

Try it online!
> 5 votes

# Answer
# , 85 bytes

```
function(a,b,s,t,m=matrix(t,b,a),r=row(m),c=col(m)){m[!pmin(b-r,a-c,r-1,c-1)%%2]=s;m}

```

Try it online!

Idea of `pmin` inspired by @alephalpha's `vecmin`.
> 4 votes

# Answer
# , 18 17 bytes

```
{~2|<./&(<.&i.-)/

```

Try it online!

*Note: Explanation needs slight update but idea is the same as current solution*

Consider `7 5`:

* `<./&i./` First uses `&i.` to generate both `0 1 2 3 4 5 6` and `0 1 2 3 4`, and the creates a "mininum" function table:

```
0 0 0 0 0
0 1 1 1 1
0 1 2 2 2
0 1 2 3 3
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

```
* `-` Note using `i.` on a negative number counts down, so `i. _3` is `2 1 0`.
* `-<.&(...)]` Is a fork which applies the verb from step to both `7 5` and `_7 _5`, and then takes the min. So min of:

```
 0 0 0 0 0       4 3 2 1 0
 0 1 1 1 1       4 3 2 1 0
 0 1 2 2 2  min  4 3 2 1 0
 0 1 2 3 3       3 3 2 1 0
 0 1 2 3 4       2 2 2 1 0
 0 1 2 3 4       1 1 1 1 0
 0 1 2 3 4       0 0 0 0 0

```

which gives:

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

```
* `2|` Then we mod by 2:

```
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 0 1 0
0 1 0 1 0
0 1 1 1 0
0 0 0 0 0

```
* `{~` And map to chars:

```
-----
-@@@-
-@-@-
-@-@-
-@-@-
-@@@-
-----

```
> 4 votes

# Answer
# ayr `-0`, ~~17~~ 14 bytes

Since the 05Ab1e answer takes the input \[row, column\], I can get -3 bytes. Images and try it link outdated, just replace the code with this snippet.

```
~2||:v:\/@`v:~

```

Try it!

# Explained

`-0` makes `~` and `|:` (descending range) 0-indexed

The program `A (~2||:v:\/@`v:~) B` is equivalent to `A ~ 2 | (v:\/ |: B) v: v:\/ ~ B`

### How to get there:

**Expansion of the train (lowercase = fn, uppercase = var):**

* `B (f A g h i j) C`
* `B (f (A g h i j)) C`
* `B (f (A g (h i j))) C`
* `B f (A g (h i j)) C`
* `B f (A g ((h i j) C))`
* `B f (A g ((h C) i (j C)))`

**Substituting in the symbols:**
`B ~ (2 | ((|: C) v:\/@`v: (~ C)))`

**Focusing on the fork (h i j):**
`v:\/@`v:` could be written as `f \ / @` g`
which is `g @ (f \ /)`
`A g @ f B` is `(f A) g f B`
so `(|: C) v:\/@`v: (~ C)` is `(v:\/ |: C) v: (v:\/ ~ C)`

*Therefore*
`A (~2||:v:\/@`v:~) B` is equivalent to `A ~ 2 | (v:\/ |: B) v: v:\/ ~ B`

### Which leads to the explanation:

A is the string, B is the dims

* `|: ... ~` Take the descending and ascending 0-ranges of each element of B

* `v:\/` Convert these each separately to a minimum matrix of shape B

* `v:` Take the minimum of these two matrices on an element-wise basis
* `2|` Mod 2 each element
* `~` Use the matrix as indices into string A
> 3 votes

# Answer
# Haskell, 64 bytes

```
(x!y)q=[[cycle q!!minimum[k,1+x-k,j,1+y-j]|j<-[1..y]]|k<-[1..x]]

```

Try it online!

Also works with even sized mats and more than two character patterns.
> 2 votes

# Answer
# Charcoal, 20 bytes

```
ＮθＥ⊘⊕Ｎ⭆⊘⊕θ§ζ⌊⟦ιλ⟧‖Ｏ⌈

```

Try it online! Link is to verbose version of code. Takes the two symbols as a single argument. Explanation:

```
Ｎθ

```

Input the width.

```
Ｅ⊘⊕Ｎ⭆⊘⊕θ§ζ⌊⟦ιλ⟧

```

Input the height and loop over the top left quarter of the mat, outputting the symbols cyclically indexed by the minimum of the row and column.

```
‖Ｏ⌈

```

Reflect with overlap to complete the map.

Alternative approach, also 20 bytes:

```
ＮθＥ⮌…⁰Ｎ⭆⮌…⁰θ§ζ⌊⟦ικλμ

```

Try it online! Link is to verbose version of code. Takes the two symbols as a single argument. Explanation:

```
Ｎθ

```

Input the width.

```
Ｅ⮌…⁰Ｎ⭆⮌…⁰θ§ζ⌊⟦ικλμ

```

Input the height and loop over the mat, reversing the ranges of the row and column, outputting the symbols cyclically indexed by the minimum of the row and column and reversed row and column.
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
>;L`â€ßZä€ûûè

```

First input is a pair of \\$\[row,column\]\\$, second input is a pair of \\$\[symbol2,symbol1\]\\$. Output is a matrix of characters.

Try it online (footer  is to pretty-print; feel free to remove it to see the actual output-matrix).

**Explanation:**

```
>; # Increase both values in the first (implicit) input-pair by 1, then halve
   #  e.g. [5,13] → [6,14] → [3,7]
L  # Map both to a list in the range [1,n]
   #  → [[1,2,3],[1,2,3,4,5,6,7]]
`  # Pop and push both separated to the stack
   #  → [1,2,3] and [1,2,3,4,5,6,7]
â  # Get the cartesian product of these two lists
   #  → [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[2,1],[2,2],[2,3],[2,4],[2,5],
   #     [2,6],[2,7],[3,1],[3,2],[3,3],[3,4],[3,5],[3,6],[3,7]]
€ß # Get the minimum of each inner pair
   #  → [1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,2,3,3,3,3,3]
Z  # Push the flattened maximum (without popping the list)
   #  → [1,1,1,1,1,1,1,1,2,2,2,2,2,2,1,2,3,3,3,3,3] and 3
ä  # Split the list into that many equal-sized parts so we have a matrix
   #  → [[1,1,1,1,1,1,1],[1,2,2,2,2,2,2],[1,2,3,3,3,3,3]]
€û # Palindromize each row
   #  → [[1,1,1,1,1,1,1,1,1,1,1,1,1],
   #     [1,2,2,2,2,2,2,2,2,2,2,2,1],
   #     [1,2,3,3,3,3,3,3,3,3,3,2,1]]
û  # Palindromize the entire matrix
   #  → [[1,1,1,1,1,1,1,1,1,1,1,1,1],
   #     [1,2,2,2,2,2,2,2,2,2,2,2,1],
   #     [1,2,3,3,3,3,3,3,3,3,3,2,1],
   #     [1,2,2,2,2,2,2,2,2,2,2,2,1],
   #     [1,1,1,1,1,1,1,1,1,1,1,1,1]]
è  # 0-based modulair index each into the (implicit) second input-string
   #  e.g. "-@" →
   #    [["@","@","@","@","@","@","@","@","@","@","@","@","@"],
   #     ["@","-","-","-","-","-","-","-","-","-","-","-","@"],
   #     ["@","-","@","@","@","@","@","@","@","@","@","-","@"],
   #     ["@","-","-","-","-","-","-","-","-","-","-","-","@"],
   #     ["@","@","@","@","@","@","@","@","@","@","@","@","@"]]
   # (after which the matrix is output implicitly)

```
> 2 votes

# Answer
# Python3, 240 bytes

```
b,a,c,d=input().split()
g=range
a,b=int(a),int(b)
r=[[d]*b for i in g(a)]
x=y=0
while 1:
 for i in g(x,a-x):r[i][y]=r[i][b-1-y]=c
 for j in g(y,b-y):r[x][j]=r[a-1-x][j]=c
 x+=2;y+=2
 if x>=a/2or y>=b/2:break
print('\n'.join(map(''.join,r)))

```

Try it online!
> 1 votes

# Answer
# Charcoal, ~~36~~ 28 bytes

```
ＮθＮηＷ∧›θ⁰›η⁰«Ｂθη§ζⅈ↘≧⁻²θ≧⁻²η

```

-10 bytes thanks to *@Neil* and +2 bytes for a bug-fix.

Try it online (verbose) or try it online (pure).

**Explanation:**

Get the first two inputs as integers:

```
InputNumber(q);InputNumber(h);
ＮθＮη

```

Continue looping while both `q` and `h` are still larger than 0:

```
While(And(Greater(q,0),Greater(h,0)){ ... }
Ｗ∧›θ⁰›η⁰« ...

```

Print a box with dimensions `q` by `h`, with the `X`'th character of the third input-string `z` as border, where `X` is the current x-position of the cursor:

```
 Box(q,h,AtIndex(z,X()));
 Ｂθη§ζⅈ

```

Move the cursor once towards the bottom-right:

```
 Move(:DownRight);
 ↘

```

Decrement both `q` and `h` by 2:

```
 MapAssignRight(Minus,2,q);MapAssignRight(Minus,2,h);
 ≧⁻²θ≧⁻²η

```
> 1 votes

# Answer
# Python 3, 174 bytes

```
w,h,x,y=input().split()
n='\n'
f=lambda x,y,w,h:x*w+n+x+f(y,x,w-2,h-2).replace(n,x+n+x)+x+n+x*w if w*h-w-h+1else[n.join(x*(h-w+1)),x*(w-h+1)][w>h]
print(f(x,y,int(w),int(h)))

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 22 bytes

Prompts for column then row as integers and the symbols as string. Index origin = 0

```
⎕[2|n⌊⌽⍉⌽⍉n←(⍳⎕)∘.⌊⍳⎕]

```

Try it online!Thanks to Dyalog Classic
> 1 votes

# Answer
# Vyxal, 18 bytes

```
›½ɾΠvg:G$ṅ/vf⌊v∞∞İ

```

Try it Online!

## How?

```
›½ɾΠvg:G$ṅ/vf⌊v∞∞İ
›                  # Increment both of the (implicit) first input
 ½                 # Halve both
  ɾ                # Generate a [1, n] range for both
   Π               # Cartesian product of the two
    vg             # Minimum of each
      :G           # Duplicate and get the maximum
        $          # Swap
         ṅ         # Join by nothing
          /        # Split this into that many equal parts
           vf      # Convert each back to a list
             ⌊     # Convert each to an integer
              v∞   # Palindromise each
                ∞  # Palindromise the list
                 İ # Index these into the (implicit) second input

```
> 1 votes

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


# Question
Title: The Solar Eclipse Through a Pinhole Camera
This challenge is a simple ASCII-art challenge inspired by the solar eclipse that happened on August 21, 2017. Given an input `0 <= n <= 4`, output the corresponding stage of the eclipse described below:

```
n=0:
   *****
 **     **
*         *
*         *
**       **
  *******

n=1:
   *****
 **  *****
*   *******
*   *******
**   ******
  *******

n=2:
   *****
 *********
***********
***********
***********
  *******

n=3:
   *****
 *****  **
*******   *
*******   *
******   **
  *******

n=4:
   *****
 **     **
*         *
*         *
**       **
  *******

```

---

# Rules

* You can 0 or 1 index, state what you chose.
* The chars used are space and `*`, you may use any printable char for `*` (other than space).
* Trailing spaces are optional (you may or may not have them).
* This is , lowest byte-count is the winner.

# Answer
> 13 votes
# Python 2, ~~161~~ ~~149~~ ~~142~~ 135 bytes

```
lambda n,u=u' *':u'''   *****
 ****
**
**
****
  *******'''.translate({1:u[0<n<3],2:u[0<n<4],3:u[1<n<4]})

```

Try it online!

-7 thanks to Mr. Xcoder.

# Answer
> 9 votes
# Charcoal, ~~82~~ ~~81~~ ~~55~~ 43 bytes

*-38 bytes thanks to Neil!*

```
Ｎν”{“⟲ＦEd⧴_³⟲”‖Ｏ¿﹪ν⁴«Ｆ﹪ν²Ｇ↗³↑²↖²↙³*↑¤*¿⁼ν¹‖

```

Try it online! Link is to verbose version.

I did for the heck of it. :P ~~I'll probably get out-golfed by 40 bytes.~~ ~~26~~ 38 bytes... Close enough?

# Answer
> 5 votes
# Cinnamon Gum, 70 bytes

Hexdump:

```
0000000: 6c33 5053 5050 d002 012e 20a5 0002 4026  l3PSPP.... ...@&
0000010: 9001 0568 6c20 07a6 0648 4080 b521 8a19  ...hl ...H@..!..
0000020: 30a6 1644 1093 0de3 a098 6184 6206 422d  0..D......a.b.B-
0000030: 6136 c20c 6374 3380 3cb8 5aa0 1436 36ba  a6..ct3.<.Z..66.
0000040: 5f4c 280f 0f00                           _L(...

```

Try it online!

I have been waiting *so long* to find out how to use this language. :P

So, Cinnamon Gum is Bubblegum, but it's more of a "real" language than Bubblegum.

The first byte (`l`) sets the mode to dictionary mode. The rest of the bytes is the following string compressed.

```
0&   *****
 **     **
*         *
*         *
**       **
  *******;1&   *****
 **  *****
*   *******
*   *******
**   ******
  *******;2&   *****
 *********
***********
***********
***********
  *******;3&   *****
 *****  **
*******   *
*******   *
******   **
  *******;4&   *****
 **     **
*         *
*         *
**       **
  *******

```

This essentially makes a lookup table with each text assigned to a number. The program then takes input and outputs the respective text.

# Answer
> 5 votes
## JavaScript (ES6), ~~103~~ 102 bytes

```
f=
n=>`   *****
 **66733**${s=`
*666777333*`}${s}
**6667333**
  *******`.replace(/\d/g,c=>" *"[c*2>>n&1])
```

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

Edit: Saved 1 byte thanks to @darrylyeo.

# Answer
> 5 votes
# VI, 108 bytes

```
D:let@a=@"%2?@":@"%4?"X":"\\d"<CR>
3i <Esc>5a*<Esc>Yphr*$a*<Esc>O**1110333**<Esc>YPi <Esc>3lx3lx"0px4lyl2p$xYp
:%s/<C-r>a/ /g<CR>
:%s/\d/*/g<CR>

```

`<CR>` is the `Enter` stroke, `<C-?>` corresponds to `Control + ?`, and `<Esc>` to `Escape` obviously. Each of these count for 1 byte (see meta). The line breaks in the solution is for readability. Only `<CR>` represents real `Enter` strokes.

## Input

The input file should contain only 1 character, representing `n`.

## Launch

VI should be started like :

```
vi -u NONE input

```

## Explanations

There are 3 parts in the solution. I will describe the 2nd part first (2nd line), since it is the easiest to explain.

### Drawing the sun

The command to draw the sun is :

```
3i <Esc>5a*<Esc>Yphr*$a*<Esc>O**1110333**<Esc>YPi <Esc>3lx3lx"0px4lyl2p$xYp

```

The sun must be drawn with , `*`, `0`, `1` and `3`, like this :

```
   *****
 **11033**
*111000333*
*111000333*
**1110333**
  *******

```

A symmetry would have helped to reduce the bytes size of this part, but it's not that important. I will not explain the full line, but the pattern `*****` is used to easily generate the last line, and the pattern `**1110333**` has been taken as a reference to generate the 3 other lines containing `0`, `1` and `3`.

It is important to use `0`, `1` and `3` for sun parts that can be filled (see next explanations). Drawing this sun takes **55 bytes**, and can probably be golfed with some tricks.

### Filling the sun according to `n`

To correctly fill the sun, the instructions to follow are :

* if `n = 0`, then `0`, `1` and `3` (all digits) should be replaced with
* if `n = 1`, then `1` should be replaced with , the other digits with `*`
* if `n = 2`, then `0`, `1` and `3` (all digits) should be replaced with `*`
* if `n = 3`, then `3` should be replaced with , the other digits with `*`
* if `n = 4`, then `0`, `1` and `3` (all digits) should be replaced with  (like `n = 0`)

From that, we can infer that the substitutions required are :

* replace some digits by  (**first substitution**)
* replace all other digits by `*` (**second substitution**)

Note that "some digits" can mean "no digits" (`n = 2` for example). And "all other digits" can also represent "no digits", if all digits have already been replaced by the first substitution (`n = 0` for example).

The **second substitution** can be easily written in **11 bytes** :

```
:%s/\d/*/g<CR>

```

The **first substitution** depends on `n`, so first we have to calculate what digits are going to be replaced. If replaced characters are stored in register `a`, the substitution command is written in also **11 bytes** :

```
:%s/<C-r>a/ /g<CR>

```

`<C-r>a` is replaced by the content of register `a` when the command is typed.

To calculate the value of `a`, following the previous instructions, the algorithm is (in pseudo-code) :

```
n := read()
if (n % 2 != 0)
then
    a := n
else
    if(n % 4 != 0)
    then
        a := "X"
    else
        a := "\d"

```

`"X"` string is used because when `n = 2`, no digits are replaced by spaces. Any string that is not the sun could be used here, as long as the first substitution does nothing.

This could be written in **31 bytes** :

```
D                                   # yank and delete the first character of the file (n) to register "" (yank by default) : n = @"
 :let@a=                            # define register "a content
        @"%2                        # if (n % 2 != 0)
            ?                       # then
             @"                     #   n
               :                    # else
                @"%4                #   if (n % 4 != 0)
                    ?               #   then
                     "X"            #       "X"
                        :           #   else
                         "\\d"      #       "\\d"
                              <CR>  # calculate "a

```

## Solution

Put all these parts in the right order, and you have the solution :

```
D:let@a=@"%2?@":@"%4?"X":"\\d"<CR>                                              # calculate the digits to replace with spaces
3i <Esc>5a*<Esc>Yphr*$a*<Esc>O**1110333**<Esc>YPi <Esc>3lx3lx"0px4lyl2p$xYp     # draw the sun with spaces, stars, 0, 1 and 3
:%s/<C-r>a/ /g<CR>                                                              # replace the pattern stored in register "a with spaces
:%s/\d/*/g<CR>                                                                  # replace the remaining digits with stars

```

# Answer
> 4 votes
# SOGL V0.12, ~~40~~ 39 bytes

```
"⁽Ρūa╔Ƨ ‘╥▓.4%?52"¹ο1¹‘╬¡╬5.H?:±}.2=?╬8

```

Try it Here!

# Answer
> 3 votes
# PHP, 114+1 bytes

+1 byte for `-R`. Thanks @Neil for the shifting hint.

```
for(;$c="   *****
 **66733**
*666777333*
*666777333*
**6667333**
  *******"[$i++];)echo+$c?" *"[$c*2>>$argn&1]:$c;

```

uses underscore for `*`, 0-indexed. Run as pipe with `-nR` or try it online.

Requires PHP 5.5 or later:
older PHP does not understand literal string indexing (parse error);
PHP 7.1 complains about non-numeric values (replace `+$c` with `$c>0` to fix).

# Answer
> 3 votes
# Java 8, ~~225~~ ~~213~~ ~~211~~ 200 bytes

```
n->{String y="   ",z="***",a=n<2|n>3?y:z,b=n<1|n>2?y:z,c=n%4<1?" ":"*",d=a+(n%4<1?y:z)+b;return y+z+"**\n **"+(n<2|n>3?"  ":"**")+c+(n<1|n>2?"  ":"**")+"**\n*"+d+"*\n*"+d+"*\n**"+a+c+b+"**\n  *"+z+z;}

```

-11 bytes thanks to *@ceilingcat*.

Try it here.

# Answer
> 2 votes
# Python 2, 181 bytes

```
lambda n,s=' ',a='*':"""   *****
 **%s**
*%s*
*%s*
**%s**
  *******"""%[(s*5,s*9,s*9,s*7),(s*2+a*3,s*3+a*6,s*3+a*6,s*3+a*4),(a*5,a*9,a*9,a*7),(a*3+s*2,a*6+s*3,a*6+s*3,a*4+s*3)][n%4]

```

Try it online!

Very naive approach, ~~workin' on golfin'~~ nvm.

# Answer
> 2 votes
# Python 2, ~~170~~ 169 bytes

* -1 byte thanks to @TheIOSCoder: use of exec

```
def f(x,k=0):exec'print"".join(ord(i)*" *"[j%2]for j,i in enumerate(["		","	","	!",""][x%4]))[11*k:][:11];k+=1;'*6

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 46 bytes

```
„* •zÇRéóĀ—ÚÂÐoʒ<]ÜA›¶Ò¿H¶ ∞m•b3äûIèSèJ6äIií}»

```

Try it online!

# Answer
> 0 votes
# Vyxal `j`, 48 bytes

```
‛* »>ṪÞ£Ǔḟṅ↲Ṅ²3@qx⋎
ṡµ⌈İ∆µ^X1»bṅ3/∞?if⌊İṅ6/?1=[R

```

Try it Online!

## How?

```
‛* »>ṪÞ£Ǔḟṅ↲Ṅ²3@qx⋎
ṡµ⌈İ∆µ^X1»bṅ3/∞?if⌊İṅ6/?1=[R
‛*                    # Push string "* "
   »>ṪÞ£Ǔḟṅ↲Ṅ²3@qx⋎\nṡµ⌈İ∆µ^X1»
                      # Push compressed integer 90018261496673587326026870693610373816328976440801592144686583
b                     # Convert it to binary
 ṅ                    # Join by nothing
  3/                  # Split it into 3 equal parts
    ∞                 # Palindromise this list
     ?                # Push the input
      i               # Index it into the list
       f              # Convert to list of characters
        ⌊             # Convert each to an integer
         İ            # Index each into the other string ("* ")
          ṅ           # Join by nothing
           6/         # Split into six equal parts
             ?1=[     # If the input is equal to one:
                 R    # Reverse each

```

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


title: ASCII Art Octagons

text:
# Question
Title: ASCII Art Octagons
Given an input integer `n > 1`, output an ASCII-art octagon with side lengths composed of `n` characters. See examples below:

```
n=2
 ##
#  #
#  #
 ##

n=3
  ###
 #   #
#     #
#     #
#     #
 #   #
  ###

n=4
   ####
  #    #
 #      #
#        #
#        #
#        #
#        #
 #      #
  #    #
   ####

n=5
    #####
   #     #
  #       #
 #         #
#           #
#           #
#           #
#           #
#           #
 #         #
  #       #
   #     #
    #####

and so on.

```

You can print it to STDOUT or return it as a function result.

Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately.

### Rules and I/O

* Input and output can be given by any convenient method.
* You can use any printable ASCII character instead of the `#` (except space), but the "background" character must be space (ASCII 32).
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# 05AB1E, 3 bytes

```
7ÝΛ

```

Try it online!

**Explanation**

```
      # implicit input as length
      # implicit input as string to print
7Ý    # range [0...7] as directions
  Λ   # canvas print

```

See this answer to understand the 05AB1E canvas.
> 23 votes

# Answer
# JavaScript (ES6), ~~114~~ ~~106~~ ~~105~~ ~~104~~ 103 bytes

```
n=>(g=x=>v=x*2>w?w-x:x,F=x=>~y?`#
`[~x?(h=g(x--))*g(y)>0&h+v!=n|n>h+v:(y--,x=w,2)]+F(x):'')(y=w=--n*3)

```

Try it online!

### How?

This builds the output character by character.

Given the input \\$n\\$, we compute:

$$n'=n-1\\w=3n'$$

For each character at \\$(x,y)\\$, we compute \\$(h,v)\\$:

$$h=w/2-\left|x-w/2\right|\\v=w/2-\left|y-w/2\right|$$

The cells belonging to the octagon satisfy one of the following conditions:

* (\\$h=0\\$ OR \\$v=0\\$) AND \\$h+v\ge n'\\$ (in red below)
* \\$h+v=n'\\$ (in orange below)

For example, with \\$n=4\\$ (and \\$n'=3\\$):

$$\begin{matrix}(0,0)&(1,0)&(2,0)&\color{red}{(3,0)}&\color{red}{(4,0)}&\color{red}{(4,0)}&\color{red}{(3,0)}&(2,0)&(1,0)&(0,0)\\ (0,1)&(1,1)&\color{orange}{(2,1)}&(3,1)&(4,1)&(4,1)&(3,1)&\color{orange}{(2,1)}&(1,1)&(0,1)\\ (0,2)&\color{orange}{(1,2)}&(2,2)&(3,2)&(4,2)&(4,2)&(3,2)&(2,2)&\color{orange}{(1,2)}&(0,2)\\ \color{red}{(0,3)}&(1,3)&(2,3)&(3,3)&(4,3)&(4,3)&(3,3)&(2,3)&(1,3)&\color{red}{(0,3)}\\ \color{red}{(0,4)}&(1,4)&(2,4)&(3,4)&(4,4)&(4,4)&(3,4)&(2,4)&(1,4)&\color{red}{(0,4)}\\ \color{red}{(0,4)}&(1,4)&(2,4)&(3,4)&(4,4)&(4,4)&(3,4)&(2,4)&(1,4)&\color{red}{(0,4)}\\ \color{red}{(0,3)}&(1,3)&(2,3)&(3,3)&(4,3)&(4,3)&(3,3)&(2,3)&(1,3)&\color{red}{(0,3)}\\ (0,2)&\color{orange}{(1,2)}&(2,2)&(3,2)&(4,2)&(4,2)&(3,2)&(2,2)&\color{orange}{(1,2)}&(0,2)\\ (0,1)&(1,1)&\color{orange}{(2,1)}&(3,1)&(4,1)&(4,1)&(3,1)&\color{orange}{(2,1)}&(1,1)&(0,1)\\ (0,0)&(1,0)&(2,0)&\color{red}{(3,0)}&\color{red}{(4,0)}&\color{red}{(4,0)}&\color{red}{(3,0)}&(2,0)&(1,0)&(0,0)\end{matrix} $$
> 11 votes

# Answer
# Charcoal, 5 bytes

```
ＧＨ*Ｎ#

```

My first answer with Charcoal!

Explanation:

```
ＧＨ*Ｎ#      //Full program
ＧＨ          //Draw a hollow polygon
   *         //with 8 sides
    Ｎ       //of side length from input
      #      //using '#' character

```

Try it online!
> 7 votes

# Answer
# Canvas, ~~15~~ ~~14~~ 12 bytes

```
／⁸⇵╷+×＋：⤢ｎ╬┼

```

Try it here!

Explanation:

```
/             a diagonal of length n
 ⁸            the input,
  ⇵           ceiling divided by 2, (storing the remainder)
   ╷          minus one
    #×        repeat "#" that many times
      +       append that to the diagonal
       :⤢n    overlap that with its transpose
          ╬┼  quad-palindromize with the overlap being the remainder stored earlier

```

Alternative 12-byter.
> 5 votes

# Answer
# , ~~122~~ ~~117~~ 115 bytes

```
function(n){n=n-1
m=matrix(0,y<-3*n+1,y)
v=t(h<-(w=3*n/2)-abs(row(m)-1-w))
m[h*v&h+v-n|h+v<n]=' '
write(m,1,y,,"")}

```

Try it online!

Ports the logic from Arnauld's answer, specifically this revision in case there are further improvements. Another 2 bytes saved thanks to Arnauld's suggestion of inverting the logic!
> 4 votes

# Answer
# Python 2, 96 bytes

```
a=b=n=input()
while a>2-n-n:a-=1;b-=a/~-n+1;s=(-~b*' '+'#').ljust(n);print s+s[-1]*(n-2)+s[::-1]

```

Try it online!
> 3 votes

# Answer
# Python 2, 81 bytes

```
a=d=n=input()-1
while a<=n:print' '*a+'#'+' #'[a==n]*(3*n-a+~a)+'#';d-=1;a-=d/n+1

```

Try it online!

---

**Python 2, 75 bytes**

```
a=d=n=input()-1
while a<=n:print' '*a+`' `'[a==n]*(3*n-a+~a)`;d-=1;a-=d/n+1

```

Try it online!

If mixing output characters is OK.
> 3 votes

# Answer
# Powershell, 91 bytes

```
param($n)($s=' '*--$n+'#'*$n+'#')
--$n..0+,0*$n+0..$n|%{' '*$_+"#$(' '*(3*$n-2*$_+2))#"}
$s

```
> 3 votes

# Answer
# PowerShell, ~~107~~ 97 bytes

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

```

Try it online!

If there was a cheap way to reverse the first half, this answer would feel a lot better. It builds the left half, then the core (which is either x `#'s` or spaces), then mirrors the left's logic to make the right. Fun fact, you don't need to copy over trailing white-space.

Unrolled and explained:

```
param($n)
($z=$n-1)..1 + ,0*$n + 1..$z |%{  #Range that repeats 0 n times in the middle
" "*$_ + "#" +($x=" "*($z-$_)) +  #Left side
(" ","#")[!($_-$z)]*($n-2) +      #Core that swaps when it's the first or last row
"$x#"}                            #Right side which is left but backwards

```
> 2 votes

# Answer
# C (clang), `-DP=printf(` `-DF=for(i` ~~\+ 179 = 199~~ 180 bytes

```
i;*m="%*s%*s\n";g(n){P"%*s",n,H;F;--i;)P H;P"\n");}f(n){g(n);F;--i;)P m,i,(H,3*n-i+~i,H;F-2;i--;)P"#%*s\n",3*n-3,H;F;--i;)P m,n-i,(H,n+i+i-1,H;g(n);}

```

Try it online!

Ungolfed:

```
f(n){
	int i;
	printf("%*d",n,0);
	for(i=0;i<n-1;i++){
		printf("0");
	}
	printf("\n");
	for(i=1;i<n;i++){
		printf("%*d%*d\n",n-i,0,n+i+i-1,0);
	}
	for(i=0;i<n-2;i++){
		printf("0%*d\n",n+n+n-3,0);
	}
	for(i=n-1;i>0;i--){
		printf("%*d%*d\n",n-i,0,n+i+i-1,0);
	}
	printf("%*d",n,0);
	for(i=0;i<n-1;i++){
		printf("0");
	}
}

```

-19 bytes thanks to @ceilingcat
> 2 votes

# Answer
# APL (Dyalog Unicode), 46 bytesSBCS

```
(' '@~5 6∊⍨1⊥⊢∘,)⌺3 3⊢<(⍉⌽⌊⊢)⍣2∘(∘.+⍨∘⍳¯2+3×⊢)

```

This solution was provided by Adám - thanks!

Try it online!

## My (almost) original solution:

# APL (Dyalog Unicode), 61 bytesSBCS

```
(((⊃∘' #'¨1+5∘=+6∘=)⊢)1⊥⊢∘,)⌺3 3⊢<(((⊖⌊⊢)⌽⌊⊢)(∘.+⍨(⍳¯2+3×⊢)))

```

Try it online!

Thanks to Adám for his help!

The idea is to find the "diamond" that lies partly in the square and apply an edge-detect filter to "outline" the octagone.
> 2 votes

# Answer
# Python 2, 130 bytes

```
def f(n):
 a=[' '*~-n+n*'#']
 b=[' '*(n-i-2)+'#'+' '*(n+2*i) +'#'for i in range(n-2)]
 return a+b+['#%*s'%(3*n-3,'#')]*n+b[::-1]+a

```

Try it online!

On mobile, so not incredibly golfed.
> 1 votes

# Answer
## Batch, 260 bytes

```
@echo off
set s=
for /l %%i in (1,1,%1)do call set s= %%s%%
echo %s% %s: =#%
call:c %1,-1,3
for /l %%i in (1,1,%1)do echo   #%s:~2%%s%%s:~2%#
call:c 3,1,%1
echo %s% %s: =#%
exit/b
:c
for /l %%i in (%*)do call echo %%s:~,%%i%%#%%s:~%%i%%%s%%%s:~%%i%%#

```

Outputs two leading spaces on each line. Explanation: Batch has no string repetition operator, limited string slicing capability and requires separate statements to perform arithmetic. It was therefore golfiest to make up a string of the input length in spaces (Batch can at least translate these to `#`s for the top and bottom lines) and then slice from or to a specific position ranging from 3 to the length to generate the diagonals (this is what the last line of the script achieves).
> 1 votes

# Answer
# Ruby, 96 bytes

```
->n{[*(n-=2).step(z=n*3+2,2),*[z]*n,*z.step(n,-2)].map{|x|([?#]*2*('# '[x<=>n]*x)).center(z+2)}}

```

Try it online!

Not very golfed yet. Might golf if I find the time.
> 1 votes

# Answer
# Red, 171 bytes

```
func[n][c:(a: n - 1)* 2 + n
b: collect[loop c[keep pad/left copy"^/"c + 1]]s: 1x1 s/1: n
foreach i[1x0 1 0x1 -1x1 -1x0 -1 0x-1 1x-1][loop a[b/(s/2)/(s/1): #"#"s: s + i]]b]

```

Try it online!

## Explanation:

```
Red[]
f: func [ n ] [
    a: n - 1                                         ; size - 1
    c: a * 2 + n                                     ; total size of widht / height
    b: collect [                                     ; create a block
        loop c [                                     ; composed of size - 1 rows
            keep pad/left copy "^/" c + 1            ; of empty lines of size c (and a newline)
        ]
    ]
    s: a * 1x0 + 1                                   ; starting coordinate
    foreach i [ 1x0 1 0x1 -1x1 -1x0 -1 0x-1 1x-1 ] [ ; for each offset for the 8 directions
        loop a [                                     ; repeat n - 1 times
            b/(s/2)/(s/1): #"#"                      ; set the array at current coordinate to "#"
            s: s + i                                 ; next coordinate
        ]
    ]
    b                                                ; return the block
]

```
> 1 votes

# Answer
# **Perl 5, ~~201~~ ~~197~~ ~~188~~ ~~187~~ 186 bytes:**

```
$a=<>;$b=3*$a-4;$c='$"x($e-$_)."#".$"x$f."#\n"';$e=($b-$a)/2+1;$d=$"x$e."#"x$a.$/;$f=$a;print$d,(map{(eval$c,$f+=2)[0]}1..$a-2),("#".$"x$b."#\n")x$a,(map{$f-=2;eval$c}reverse 1..$a-2),$d

```

Try it online!

Reads the size of the octagon from first line of `STDIN`.
> 1 votes

# Answer
# C (gcc), ~~158~~ ~~153~~ 150 bytes

```
O,c,t,g;o(n){for(O=2*~-n,t=c=O+n;t--;puts(""))for(g=c;g--;)putchar(33-(!t|t>c-2?g<n-1|g>O:t<n-1|t>O?t+O-g&&t-O-g&&~c+g+t+n+n&&c-g-t+n-3+n:g&&g<c-1));}

```

Try it online!
> 1 votes

# Answer
# **Perl 5, 176 bytes**

```
$f=$a=<>;$b=3*$a-4;$c='$"x($e-$_)."#".$"x$f."#\n"';$e=$a-1;$d=$"x$e."#"x$a.$/;print$d,(map{(eval$c,$f+=2)[0]}1..$a-2),("#".$"x$b."#\n")x$a,(map{$f-=2;eval$c}reverse 1..$a-2),$d

```

Based on Nathan Mills' answer above (which I have insufficient rep to comment on!).

`$e` can be simplified to `$a-1` saving 6 bytes; `$f` can be chain assigned; saving two bytes; Not sure where the other two come from!

While `$e` can be replaced with `$a-1` in the two places it occurs, the extra brackets needed means this only breaks even.

**Ungolfed:**

```
$f = $a = <>;
$b = 3 * $a - 4;
$c = '$"x($e-$_)."#".$"x$f."#\n"';
$e = $a - 1;
$d = $" x $e . "#" x $a . $/;
print $d, ( map { ( eval $c, $f += 2 )[0] } 1 .. $a - 2 ),
  ( "#" . $" x $b . "#\n" ) x $a,
  ( map { $f -= 2; eval $c } reverse 1 .. $a - 2 ), $d

```
> 1 votes

# Answer
# Perl 6, ~~76~~ 73 bytes

*-3 bytes thanks to Jo King*

```
{(' 'x$_-1~\*x$_,{S/.\S(.)+/* {' 'x$0}*/}...*)[^$_,$_ xx$_-2,[R,] ^$_;*]}

```

Try it online!

Returns a list of lines.
> 1 votes

# Answer
# Vyxal `RM`, 4 bytes

```
S7ø∧

```

Try it Online!

new canvas builtin go brr
> 1 votes

# Answer
# Python 3, 224 bytes

```
n=int(input())
z=" "*(n-1)+"#"*n+" "*(n-1)
print(z)
for i in range(n-2):print(" "*(n-i-2)+"#"+" "*(i*2+n)+"#")
print((("#"+" "*(n*3-4)+"#\n")*n)[:-1])
for i in range(n-3,-1,-1):print(" "*(n-i-2)+"#"+" "*(i*2+n)+"#")
print(z)

```

Try it online!
> 0 votes

# Answer
# Perl 5, ~~170~~ ~~168~~ 166 bytes

```
$a=<>-1;$\="#\n";print$x=$_=$"x$a."#"x$a;if(s/^( *)  #*/$1 #  $1 /){print}while (s/ #/#  /){print}$z=$_;for(1..$a){print$_=$z}while(s/#  (\s{$a})/ #$1/){print}print$x

```

This works by the magic of regex. The "if" is only needed to deal with the pathological case of n=2, which otherwise outputs something like:

```
 ##
 ##
#  #
 ##

```

probably this can be coded away.

I think there may be a lot more to gain by creating a string up to the mid-point then reversing it. Of course we then need to insert/delete an extra space if n is odd (or use thin-space :p).

**Ungolfed**

```
$a = <> -1;                          # Subtracting one is very useful!
$\ = "#\n";                          # Every line ends with a '#' let perl provide.
$x=$_ = " " x $a. "#" x $a;          # The horiz line (one short)
print;                               # print it plus the extra #
if(s/^( *)  #*/$1 #  $1 /){print}    # create a hole and remove a leading space(if n=2 this fails)
while (s/ #/#  /){                   # make the hole bigger
    print;                           # and print (with a trailing #)
}
$z=$_;                               # store $_ for later use
for (1 .. $a) {                      # nice that we don't have to do 2..$a but not golf-nice
  $_ =$z;                            # restore $_ (we could use $z but since we have
  print;                             # to restore somewhere, doing  it here saves us bytes)
}
while (s/#  (\s{$a})/ #$1/){         # now move the # to the right and reduce the trailing spaces
  print;
}
print $x;                            # and finish...

```

I think this can probably be golfed a bit more, quite apart from significant changes like pushing onto `$@` and printing that at the end.

\[Golfed spaces around `..` and moved print before assigns in two cases, saving on semicolons.\]
> 0 votes

# Answer
# J, ~~59~~ ~~45~~ 41 bytes

```
h=.|.,],~,:@{.#~_2+#
' #'{~h@|.@|:@h@=@i.

```

Try it online!

Will add explanation tonight.
> 0 votes

# Answer
# Perl 5, 98 bytes

```
$_=2x$_.1x$_.$/;s/2//;s/.$/ #/,y/1/ /while$a.=$_,$b=$_.$b,s/2[#1]/# /;$_=$a.$_ x("@F"-2).$b;y/2/ /

```

TIO
> 0 votes

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


# Question
Title: Write an interpreter for my new programming language
I have a new programming language called Brussels-Sprout. Brussels-Sprout functions in an array of 256 boolean values, all initialized to zero, has one instruction pointer, and one "bit index".

After each (non-branching) instruction is executed, the instruction pointer is incremented by one. If the instruction pointer goes off the right side of the instruction array, the program terminates. Going off the left side is undefined behavior.

If the bit index is outside the bounds of the array, it should be reset to 0.

Brussels-Sprout uses the following keywords, which are always lowercase:

`chew` \- Invert the value in the array at the bit index. (flip the bit at the bit index)

`swallow` \- Increment the bit index.

`vomit` \- Decrement the bit index.

`complain` \- Output the bit at the bit index to stdout, or equivalent output log.

`feedtodog` \- If the bit at the bit index is 0, skip the next instruction. Otherwise, increment instruction pointer by 1.

`playwithfood` \- If the bit at the bit index is 1, jump backwards 2 instructions. Otherwise, increment instruction pointer by 1.

If an instruction not on this list is executed, undefined behavior occurs.

I'm sure that this sounds like a very certain other turing-tarpit programming language. But since this programming language operates in boolean values and not bytes, I think it is different.

Test cases:

```
chew complain -> 1
swallow chew swallow chew swallow vomit complain playwithfood -> 11
chew complain swallow chew complain swallow chew complain swallow complain -> 1110
chew feedtodog undefinedbehaviour complain -> 1

```

Your challenge is to write an interpreter for Brussels-Sprout. This is code golf, so shortest program wins!

# Answer
> 3 votes
# Python ~~3~~ 2, ~~200~~ ~~187~~ ~~149~~ ~~146~~ 136 bytes

*-9bytes thanks to Cyoce*

```
def f(n,a=[0]*256,x=0,z=0):
 while 1:y=a[z];exec'a[z]^=~1 z+=1 z-=1 print-y/2 if~y:x+=1 if~~y:x-=3'.split()["wlipdy".find(n[x][3])];x+=1

```

Input as list, exits by error. Bonus feature: you can specify start array, start IP, and start DP in that very exact order.

# Answer
> 1 votes
# SpecBAS (modern Sinclair BASIC interpreter) 202 Bytes

```
1 INPUT a$:DIM b(256)BASE 0,i$(),a$(SPLIT a$," "):DO 6:READ b,i$(b):LOOP:b=0,i=1:DO:c=b(b):EXECUTE i$(CODE a$(i,4)-99):b&=255,i+=1:LOOP:DATA 20,"b(b)=1-c",9,"b+=1",6,"b-=1",13,"?c;",1,"i+=c",22,"i-=3*c"

```

Or to make it a little clearer:

```
1 INPUT a$:
  DIM b(256) BASE 0,i$(),a$(SPLIT a$," "):
  DO 6:
    READ b,i$(b):
  LOOP:
  b=0,i=1:
  DO:
    c=b(b):
    EXECUTE i$(CODE a$(i,4)-99):
    b&=255,i+=1:
  LOOP:
  DATA 20,"b(b)=1-c",9,"b+=1",6,"b-=1",13,"?c;",1,"i+=c",22,"i-=3*c"

```

Uses some features that weren't available in the 80s, so there's that. Also shameless rips off some of the techniques in other entries. Sorry about that!

Input is from the user at runtime. Execution ends with an error "Subscript wrong".

# Answer
> 0 votes
# Java 8

## 1. Relaxed version (~~301~~ ~~283~~ ~~280~~ ~~277~~ 275 bytes)

Golfed as this:

```
class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){Runnable[]r=new Runnable[26];r[20]=()->b[i]=-~x;r[9]=()->i++;r[6]=()->i--;r[13]=()->System.out.print(x);r[1]=()->j+=x;r[22]=()->j-=3*x;for(;;){x=b[i];r[z[j].charAt(3)-99].run();i*=~(i>>8)&1;j++;}}}

```

Somewhat ungolfed version (whitespaces and comments added):

```
class C {
    // Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
    // i is the bit index and j is the instruction pointer.
    // x is just to avoid refering to b[i] in order to save 3 bytes.
    // b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
    static int i, j, x, b[] = new int[256];

    public static void main(String[] z) {

        // An array of lambdas. The index is the ascii code of 4th letter of the command name subtracted from 99.
        // Thanks for CatsAreFluffy for telling about the 4th letter trick.
        Runnable[] r = new Runnable[26];
        r[20] = () -> b[i] = -~x; // chew
        r[9] = () -> i++; // swallow
        r[6] = () -> i--; // vomit
        r[13] = () -> System.out.print(x); // complain
        r[1] = () -> j += x; // feedtodog. It is 1 or 0 instead of 2 and 1 due to the j++ down there.
        r[22] = () -> j -= 3 * x; // playwithfood. It is -3 or 0 instead of -2 and +1 due to the j++ down there.

        // This is the interpreter itself. Runs forever (or until an exception is raised).
        for (;;) {
            x = b[i];

            // Fetch an instruction and runs it. May throw an exception or execute some arbitrary instruction if the instruction name is unknown or was mistyped.
            r[z[j].charAt(3) - 99].run();

            // Resets the bit index if out of range.
            i *= ~(i >> 8) & 1;

            // Next instruction. No special treatment for branching needed because they already considers this.
            j++;
        }
    }
}

```

We surely should have testcases. I am not sure if there is some bug hiding out there.

Anyway I run it with that (input is given as command line arguments):

```
chew complain swallow chew complain swallow chew complain swallow complain

```

And here is the output:

```
1110
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at C.main(C.java:1)

```

The `ArrayIndexOutOfBoundsException` is the standard way to finish the program, it is not a bug!

BTW, this answer abuses the fact that the 4th char of each command is different than each other (thanks CatsAreFluffy). This means that `whew` is interpreted as `chew` and that `yellow` is interpreted as `swallow`.

## 2. Strict version (~~354~~ ~~337~~ ~~334~~ ~~331~~ 329 bytes)

If strict conformance to command names are required (and just looking for the 4th letter in command's name is not enough), then I have this alternative similar answer with 329 bytes:

```
import java.util.*;class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){List o=Arrays.asList("chew","swallow","vomit","complain","feedtodog","playwithfood");Runnable[]r={()->b[i]=-~x,()->i++,()->i--,()->System.out.print(x),()->j+=x,()->j-=3*x};for(;;){x=b[i];r[o.indexOf(z[j])].run();i*=~(i>>8)&1;j++;}}}

```

Somewhat ungolfed version (whitespaces and comments added):

```
// Needed for java.util.List and java.util.Arrays.
import java.util.*;

class C {
    // Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
    // i is the bit index and j is the instruction pointer.
    // x is just to avoid refering to b[i] in order to save 3 bytes.
    // b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
    static int i, j, x, b[] = new int[256];

    public static void main(String[] z) {

        // Declared as a list so we can use the indexOf method further down. Screw up the generics.
        List o = Arrays.asList("chew", "swallow", "vomit", "complain", "feedtodog", "playwithfood");

        // An array of lambdas.
        Runnable[] r = {
            () -> b[i] = -~x, // chew
            () -> i++, // swallow
            () -> i--, // vomit
            () -> System.out.print(x), // complain
            () -> j += x, // feedtodog. It is 1 and 0 instead of 2 and 1 due to the j++ down there.
            () -> j -= 3 * x // playwithfood. It is -3 and 0 instead of -2 and +1 due to the j++ down there.
        };

        // This is the interpreter itself. Runs forever (or until an exception is raised).
        for (;;) {
            x = b[i];

            // Fetch an instruction and runs it. Throws an exception on unknown or mistyped instructions.
            r[o.indexOf(z[j])].run();

            // Resets the bit index if out of range.
            i *= ~(i >> 8) & 1;

            // Next instruction. No special treatment for branching needed because the branching instructions already considers this.
            j++;
        }
    }
}

```

# Answer
> 0 votes
# Ruby 2, 151 bytes

Saw this because of another golf challenge and was amused enough by it to write it up in Ruby, and was happy to see it got very close to the Python answer (Ruby usually doesn't golf compress quite as well as Python).

```
b=[n=i=0]*256
r=''
(x=b[i=b[i]?i:0]
eval({?w=>'b[i]=1-x',?l=>'i+=1',?i=>'i-=1',?p=>'r<<x.to_s',?d=>'n+=-x',?y=>'n+=x*-3'}[c[n][3]])
n+=1)while(c[n])
r

```

You can put this in a function def that takes 'c' as a list of the commands, and it returns 'r' as the last line which is the result string.

Runs the testcases properly (if the second one is updated to actually output 110 instead of 11 as it currently incorrectly claims is the right answer - see my comment above).

---
Tags: code-golf, interpreter
---


title: Creating a Crossed Square

text:
# Question
Title: Creating a Crossed Square
## Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```
Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******

```

In the above example the '\*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

**Input**

An integer of 1 or more, it is guaranteed to be odd.

**Output**

A square that is made up of a character of your choice with a cross through the middle.

* The cross must be diagonal
* The square may be output via the function or written to output
* Trailing newlines are okay
* Can output as a graphic, diagram or image if you wish too

**Examples**

```
Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******

```

**Specs**

* Functions or full programs are allowed
* You can get input by your preferred means
* Standard loopholes are disallowed
* Programs must work without any additional statements i.e. `using`s in `C#`, they must be included in the entry
* You can output from a function or print the result

This is code golf so the shortest solution wins.

# Answer
> 9 votes
# MATL, ~~20~~ ~~19~~ 17 bytes

```
2-:XdtP!+~TTYa1YG

```

You can try it experimentally in MATL online. You may need to refresh the page if it doesn't work.

Sample run:

## ASCII version: 19 bytes

```
2-:XdtP!+~TTYa~42*c

```

Try it online!

# Answer
> 16 votes
# VBA Excel, 168 bytes

**Instruction:**

I find Excel with the help of VBA is an effective and a sufficient tool for this challenge. Set the worksheet of Excel like following

Yes, we use the small, classic square-shaped pixels like the old times by using the cells in a worksheet as the pixels. *Ha-ha...*

Here I use cell A1 as the input and I change its font color to red. Why red? Because red is three-letter-color so it fits for golfing. Write and run the following code in the Immediate Window:

```
N=[A1]:Range("A1",Cells(N,N)).Interior.Color=vbRed:Range("B2",Cells(N-1,N-1)).Clear:For i=1To N:Cells(i,i).Interior.Color=vbRed:Cells(i,N+1-i).Interior.Color=vbRed:Next

```

Ungolfed the code:

```
Sub A()
    N = [A1]
    Range("A1", Cells(N, N)).Interior.Color = vbRed
    Range("B2", Cells(N - 1, N - 1)).Clear

    For i = 1 To N
        Cells(i, i).Interior.Color = vbRed
        Cells(i, N + 1 - i).Interior.Color = vbRed
    Next
End Sub

```

**Step-by-step Explanation:**

```
N = [A1]: Range("A1", Cells(N, N)).Interior.Color = vbRed

```

```
Range("B2", Cells(N - 1, N - 1)).Clear

```

Looping through the diagonal of range cells: `Cells(i, i).Interior.Color = vbRed`

Final step and output: `Cells(i, N + 1 - i).Interior.Color = vbRed`

# Answer
> 8 votes
## JavaScript (ES6), 96 bytes

```
f=
n=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>i&&j&&n-i&&n-j&&i-j&&n-i-j?' ':'*').join``).join`
`
;
```

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

# Answer
> 7 votes
# Java 7, ~~131~~ ~~130~~ ~~128~~ ~~125~~ ~~124~~ 122 bytes

```
String c(int n){String r="";for(int i=n,j;n-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j<2|i==j|i==n-++j?"*":" ");return r;}

```

3 bytes saved thanks to *@LeakyNun*;
1 byte saved thanks to *@OliverGrégoire* in my answer for the *Draw a hollow square of # with given width* challenge;
2 bytes saved thanks to *@cliffroot*.

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(int n){
    String r = "";
    for(int i = n, j; n-- > 0; r += "\n"){
      for(j = 0; j < n;
            r += i < 1      // Responsible for the first horizontal line
               | j < 1      // Responsible for the first vertical line
               | n-i < 2    // Responsible for the last horizontal line
               | n-j < 2    // Responsible for the last vertical line
               | i == j     // Responsible for the top-left to bottom-right diagonal line
               | i == n-++j // Responsible for the top-right to bottom-left diagonal line (and increasing j)
             ? "*"
             : " ");
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println(c(3));
    System.out.println(c(5));
    System.out.println(c(7));
  }
}

```

**Output:**

```
*

***
***
***

*****
** **
* * *
** **
*****

*******
**   **
* * * *
*  *  *
* * * *
**   **
*******

```

# Answer
> 7 votes
# Python, ~~114 110 96~~ 90 bytes

Totally changed:

```
lambda n:[bin(sum(2**p for p in[range(n),{0,n-1,r,n-1-r}][0<r<n-1]))[2:]for r in range(n)]

```

Returns a list of strings, characters using `1` and `0`.
-6 bytes thanks to TheBikingViking

Test it at **ideone**

---

Previous Python 2 @110

```
def f(n):g=range(n);n-=1;print'\n'.join(''.join((c in(r,n-r,0,n)or r in(0,n))and'#'or' 'for c in g)for r in g)

```

Test it on **ideone**

# Answer
> 7 votes
## Python 2, 65 bytes

```
i=n=2**input()/2
while i:print bin((n>i>1or~-n)|n|i|n/i)[2:];i/=2

```

Uses Jonathan Allan's idea of outputting binary numbers like:

```
11111
11011
10101
11011
11111

```

The rows are created with bit arithmetic and displayed in binary. Each part it or'ed into the rest. The part are are produced by powers of 2 `n` (fixed) and `i` (falling) via

1. Left side `1`
2. Right side `n`
3. Diagonals `i` and `n/i`
4. Top and bottom by `n-1` when `i==1` or `i==n`.

Actually, (1) and (4) are combined by producing `1` when `1<i<n` and `n-1` otherwise.

# Answer
> 6 votes
# Matlab, ~~68 66 64~~ 58 bytes

Since graphical output is allowed too:

```
k=input('');[x,y]=ndgrid(abs(-k:k));spy(~(max(x,y)<k&x-y))

```

Which outputs e.g.

The ascii only versions would be:

This is using the indexing `0,1,2,3,...`

```
k=input('');[x,y]=ndgrid(abs(-k:k));[(max(x,y)==k|~(x-y))*42,'']

```

Alternatively with the indexing `1,3,7,...`:

```
n=input('');k=1:n;m=eye(n);m([k,end-k+1])=1;[(m|flip(m'))*42,'']

```

# Answer
> 6 votes
# C#, ~~112~~ 101 bytes

Thanks to TheLethalCoder for reminding me that these anonymous lambda statement-nor-expression things are allowed in C#.

```
n=>{var r="";for(int y=n--,x;y-->0;r+="*\n")for(x=0;x<n;r+=y%n*x<1|y==x|y==n-x++?"*":" ");return r;};

```

Who said C# isn't a fun golfing language?

# Answer
> 5 votes
# Logo, 155 bytes

## Graphical solution, implemented as a function

I retooled my answer for Alphabet Triangle and changed the angles around a bit. As before, `r` draws a line of characters. This time, the `b` function draws a box by drawing one straight edge and one diagonal, rotating, and repeating four times. This causes the diagonals to be drawn twice (on top of each other), but it was less code than handling it separately. This answer also properly handles even numbers. I had to add special handling for an input of `1` to prevent it from going forward.

I implemented it as a function, `b` which takes the size as an argument:

```
pu
to r:n:b:l repeat:n[rt:b label "A lt:b if repcount>1[fd:l]] end
to b:s
repeat 4[rt 90
r:s 90-heading 20 rt 135
r:s 90-heading 20*sqrt 2 rt 45]
end

```

Try it out on Calormen.com's Logo interpreter. To call it, append a line and call `b` in the following format:

```
b 7

```

... or try the sampler platter, which draws four samples in sizes 5, 7, 9, and 11, rotating 90 degrees in between:

```
repeat 4[
  b repcount*2+3
  rt 90
]

```

# Answer
> 4 votes
# R, 102 bytes

```
    n=scan();for(i in 1:n){for(j in 1:n){z=" ";if(i%in%c(1,n,n-j+1)|j%in%c(1,i,n))z="*";cat(z)};cat("\n")}

```

Note that it is more efficient to express the condition using %in% than i==1|j==1|...

# Answer
> 4 votes
# Haskell, ~~102~~ ~~100~~ ~~96~~ ~~91~~ 87 bytes

```
c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|elem y[1,s,x]||elem x[1,s,s-y+1]='*'|1>0=' '

```
* Saved 2 bytes, thanks to flawr.
* Saved 4 more bytes by using list comprehensions.
* 5 bytes saved combining flawr's improvement with `any`
* 4 bytes saved by replacing `any` with `elem`

**Ungolfed version:**

```
cross :: Int -> String
cross s = unlines $ map line [1..s]
    where line y = map (pos y) [1..s]
          pos y x | x == y = '*'
                  | x == s - y + 1 = '*'
                  | y `elem` [1, s] = '*'
                  | x `elem` [1, s] = '*'
                  | otherwise = ' '

```

I'm sure this can still be improved, but this is what I've come up with for now.

**Old version:**

```
c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|any(==y)[1,s,x]||any(==x)[1,s,s-y+1]='*'|1>0=' '

```

# Answer
> 3 votes
# C, ~~140~~ ~~121~~ 114 bytes

**19 bytes thanks to Quentin.**

7 bytes saved by switching from a double-nested loop to one loop.

```
main(a){scanf("%d",&a);for(int i=0;i<a*a;i++,i%a||puts(""))putchar(i/a&&i/a^a-1&&i%a&&-~i%a&&i%-~a&&i%~-a?32:42);}

```

Golfing suggestions welcome.

# Answer
> 3 votes
# Java, 130 bytes

```
s->{for(int i=0;i<s;i++)for(int j=0;j<s;j++)System.out.print((s-1-i==j||i==j||i==0||j==0||i==s-1||j==s-1)?j==s-1?"*\n":"*":" ");};

```

# Test Program

```
Consumer<Integer> consumer = s -> {
        for (int i = 0; i < s; i++) {
            for (int j = 0; j < s; j++) {
                System.out.print((s - 1 - i == j || i == j || i == 0 || j == 0 || i == s - 1 || j == s - 1) ? j == s - 1 ? "*\n" : "*" : " ");
            }
        }
    };

    consumer.accept(20);

```

# Answer
> 3 votes
## PowerShell (133)

```
filter s($x){1..$x|%{$o="";$r=$_;1..$x|%{if($_-eq1-or$r-eq1-or$_-eq$x-or$r-eq$x-or$r-eq$_-or$r-1-eq$x-$_){$o+="*"}else{$o+="_"}};$o}}

```

Clunky, but it works well enough.

```
s(11)
***********
**_______**
*_*_____*_*
*__*___*__*
*___*_*___*
*____*____*
*___*_*___*
*__*___*__*
*_*_____*_*
**_______**
***********

```

Golfing suggestions definitely welcome, it's been too long since I've PowerShell'd.

# Answer
> 3 votes
# S.I.L.O.S, 212 bytes

```
readIO
a = i
lbla
a - 1
t = a
t + 1
t % i
t * a
b = i
lblb
b - 1
u = b
u + 1
u % i
u * b
u * t
v = a
v - b
u * v
v = a
v + b
v + 1
v % i
u * v
u |
if u c
print #
GOTO d
lblc
print .
lbld
if b b
printLine
if a a

```

Try it online!

# Answer
> 3 votes
## GNU sed, ~~117~~ 114 + 1(r flag) = 115 bytes

```
p;/^0$/Q;/^000$/{p;q}
h;s/./ /3g;s/  $/00/
:f;/ 00 /!{G;h;s/\n.*//p;t;:}
s/^(0 *)0  ?( *)0/\1 0\20 /
tf;s/00/0/p;g

```

Since sed has no native support for numbers, the input is given in unary based on this consensus. The second half of the square is the first half that was stored in reverse order in hold space.

**Run:**

```
sed -rf crossed_square.sed <<< "00000"

```

**Output:**

```
00000
00 00
0 0 0
00 00
00000

```

# Answer
> 3 votes
# Python, 89 bytes

This was a throwback! I used python's turtle module.

```
from turtle import*
n=input()
for i in[(n,n),(n,0),(0,n),(0,0),(n,0),(0,n),(n,n)]:goto(i)

```

Here's the result when n=200:

# Answer
> 2 votes
# Scala, 141 137 bytes

```
val s=args(0).toInt-1;val t=0 to s;print(t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString)

```

Run:

`$ scala cross.scala 10`

Technically I could remove the print stuff and go to something like

```
def c(n:Int)={val (s,t)=(n-1,0 to n-1);t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString}

```

This would make it 135 or 121 bytes depending on whether you count the function syntax stuff.

Readable version:

```
def cross(n: Int) = {
   // Declares both s and t as variables with tuple expansion
   // s is the zero-based size and t is a range from 0 to s
   val (s,t) = (n-1, 0 to n-1)

   // Maps all rows by mapping the columns to a star or a space
   t.map { x =>
      t.map { y =>
        if (x == 0 || x == s || y == 0 || y == s || x == y || x == s-y) "*"
        else " "
      }.mkString+"\n" // Concatenate the stars and spaces and add a newline
   }.mkString         // Concatenate the created strings
 }

```

# Answer
> 2 votes
# Pyth, ~~27~~ 25 bytes

```
jmsm?|qFKaLJ/Q2,dk}JKN\ Q

```

Try it online!

Probably golfable.

# Answer
> 2 votes
## Python 2, 83 bytes

```
i=n=input()
while i:l=['* '[1<i<n]]*n;i-=1;l[0]=l[~0]=l[i]=l[~i]='*';print`l`[2::5]

```

Modifies a list of the row's characters to put a `*` into the first, last, i'th, and i'th-to-last place. The first and last row start as all `*`, and the rest as all spaces. Works for evens too. A `lambda` expression is probably shorter than modification, but I like this method.

# Answer
> 2 votes
## Pyke, ~~28~~ ~~24~~ 23 bytes

```
]Ua]jshqjXq|0[j{|)Qt[)P

```

Try it here!

# Answer
> 2 votes
# Mathematica, 81 bytes

```
""<>#&/@Table[If[i^2==j^2||i^2==#^2||j^2==#^2,"*"," "],{i,-#,#},{j,-#,#}]&[(#-1)/2]&

```

Creates a coordinate system with the origin in the center, and computes where the `*`s should go. Outputs an array of strings, one per row.

# Answer
> 2 votes
# Javascript (289 270 bytes)

```
function s(a){b=[];for(i=0;i<a;i++)if(b.push([]),0==i||i==a-1)for(j=0;j<a;j++)b[i].push("*");else for(j=0;j<a;j++)0==j||j==a-1?b[i].push("*"):j==i||a-1-j==i?b[i].push("*"):b[i].push(" ");c="";for(i=0;i<b.length;i++){for(j=0;j<b[i].length;j++)c+=b[i][j];c+="\n"}return c}

```

Ungolfed:

```
function square(size){
str=[];

for(i=0;i<size;i++){
    str.push([]);
    if(i==0||i==size-1){
        for(j=0;j<size;j++){
            str[i].push("*");
        }
    }else{
        for(j=0;j<size;j++){
            if(j==0||j==size-1){
                str[i].push("*");
            }else if(j==i||size-1-j==i){
                str[i].push("*");
            }else{
                str[i].push(" ");
            }
        }
    }
}

out="";
for(i=0;i<str.length;i++){
    for(j=0;j<str[i].length;j++){
        out+=str[i][j];
    }
    out+="\n";
}
return out;
}

```

EDIT: Saved 19 bytes thanks to Philipp Flenker.

# Answer
> 2 votes
# Charcoal, 8 bytes (noncompeting; language postdates challenge)

```
ＧＨ+↘↑↙Ｎ*

```

Try it online! Link is to verbose version of code. Explanation: When used as a parameter to the `PolygonHollow` command, `+` draws a box, and the arrows then create the diagonals. There are some other shortcut characters but they would need to be redefined to be useful e.g. `Y` is equivalent to `↖↗↓` but if it was eqivalent to `↗↓↖` then `Y+` would suffice.

# Answer
> 2 votes
# 05AB1E, 7 bytes

```
0•V¾²•Λ

```

Try it online or verify all test cases.

**Explanation:**

```
0        # Push 0
 •V¾²•   # Push compressed integer 2064147
      Λ  # Use the Canvas builtin with the given three options:
         #  Length of the lines: the (implicit) input-integer
         #  Character/string to display: the "0"
         #  Directions: [2,0,6,4,1,4,7]
         # (after which the result is output implicitly immediately)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•V¾²•` is `2064147`.

The Canvas Builtin uses three arguments to draw a shape:

* Length of the lines we want to draw: which is the input in this case
* Character/string to draw: the `0` (could be any other digit as well)
* The direction to draw in: the `[2,0,6,4,1,4,7]`, where each digit represents a certain direction:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

So the `[2,0,6,4,1,4,7]` in this case translates to the directions \\$\[→,↑,←,↓,↗,↓,↖\]\\$.

Here a step-by-step explanation of how it draws for example input `7` with these steps:

Step 1: Draw 7 characters (`"0000000"`) in direction `2→`:

```
0000000

```

Step 2: Draw 7-1 characters (`"000000"`) in direction `0↑`:

```
      0
      0
      0
      0
      0
      0
0000000

```

Step 3: Draw 7-1 characters (`"000000"`) in direction `6←`:

```
0000000
      0
      0
      0
      0
      0
0000000

```

Step 4: Draw 7-1 characters (`"000000"`) in direction `4↓`:

```
0000000
0     0
0     0
0     0
0     0
0     0
0000000

```

Step 5: Draw 7-1 characters (`"000000"`) in direction `1↗`:

```
0000000
0    00
0   0 0
0  0  0
0 0   0
00    0
0000000

```

Step 6: Draw 7-1 characters (`"000000"`) in direction `4↓`:

```
0000000
0    00
0   0 0
0  0  0
0 0   0
00    0
0000000

```

Step 7: Draw 7-1 characters (`"000000"`) in direction `7↖`:

```
0000000
00   00
0 0 0 0
0  0  0
0 0 0 0
00   00
0000000

```

After which the result is output implicitly immediately afterwards.

See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.

# Answer
> 1 votes
# Perl, 83 +1 = 84 bytes

Run with the `-n` flag.

```
$\="*
*";print$c="*"x($_+1);for$b(1..$_){@a=($")x$_;@a[$b-1,-$b]=(a,a);print@a}say$c

```

The literal newline saves 1 byte over `\n` or `$/`.

Readable:

```
$\="*\n*";
print$c="*"x($_+1);
for$b(1..$_){
    @a=($")x$_;
    @a[$b-1,-$b]=(a,a);
    print@a
}
say$c

```

The code prints the top line and saves it in `$c`, then prints a bunch of spaces with the appropriate slots replaced with `a`s, then prints the top line again.

The assignment to the `$\` variable tells the interpreter to print the contents (an asterisk, a newline, and another asterisk) after every `print`, but this does NOT occur after a `say`.

# Answer
> 1 votes
# SmileBASIC, 46 bytes

```
INPUT I
GBOX I,I,1,1GLINE 1,I,I,1GLINE 1,1,I,I

```

(No, SB does NOT use 1-indexed graphics...)

# Answer
> 1 votes
**SHELL** ( **135 Bytes**):

```
 C(){ j=$(($1-1));for i in $(seq 0 $j);do dc<<<2o10i`echo $((1|2**$i|2**($j-$i)|2**$j|(($i==0||$i==$j))*(2**$j-1)))`p;done|tr 01 ' X';}

```

tests:

```
 C 1
 X

 C 3
 XXX
 XXX
 XXX

 C 5
 XXXXX
 XX XX
 X X X
 XX XX
 XXXXX

 C 7
 XXXXXXX
 XX   XX
 X X X X
 X  X  X
 X X X X
 XX   XX
 XXXXXXX

 C 9
 XXXXXXXXX
 XX     XX
 X X   X X
 X  X X  X
 X   X   X
 X  X X  X
 X X   X X
 XX     XX
 XXXXXXXXX

```

# Answer
> 1 votes
# Kotlin, ~~123~~ 116 bytes

change if with \n to println

```
{s:Int->val n=s-1
for(r in 0..n){for(c in 0..n)print(if(n-r==c||r==c||r<1||c<1||r==n||c==n)"#"
else " ")
println()}}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 8 bytes

```
×» Ḣ¡»ø∧

```

Try it Online!

Port of 05AB1E. Uses canvas builtin.

## How?

```
×» Ḣ¡»ø∧
×        # Push asterisk
 » Ḣ¡»   # Push compressed integer 2064147 (translates to directions [→,↑,←,↓,↗,↓,↖])
      ø∧ # Canvas builtin with implicit input as the length, 2064147 as the directions, and asterisk as the character

```

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