title: Is given number a concat of two squares

text:
# Question
Title: Is given number a concat of two squares
Given a positive integer, determine if it can be represented as a concatenation of two square numbers. Concatenated numbers may not begin with 0 (except for 0). Any leading zeros in input should be ignored.

Examples

```
11 -> true // because 1 and 1 are squares
90 -> true // because 9 and 0 are squares
1001 -> true // because 100 and 1 are squares
144100 -> true // because 144 and 100 are squares
151296561 -> true // because 15129 and 6561 are squares
164 -> true // because 1 and 64 are squares (also 16 and 4)
101 -> false // can't be 1+01 as a number may not begin with 0
016 -> false // leading 0 is ignored and 16 doesn't count
9 -> false // need two squares
914 -> false // need two squares (there are three)

```

Task

Given a positive integer return a value indicating if it is a concatenation of two squares.

This is code-golf the goal is to minimize the size of the source code as measured in bytes.

# Answer
> 9 votes
# Brachylog, 7 bytes

```
~cĊ~^₂ᵐ

```

Try it online!

### Explanation

```
~cĊ       Deconcatenate into a couple of 2 elements Ċ
  Ċ~^₂ᵐ   Each element of Ċ must be the square of a number

```

# Answer
> 8 votes
# , 42 bytes

```
function(x)x%in%outer(y<-(0:x)^2,y,paste0)

```

Try it online!

Same horribly-inefficient approach as my Husk answer.

's `%in%` function to search for an element in a vector conveniently appears to cast its arguments to the same type (here the numeric input `x` and the character vector of `paste`d-together squares), which was a nice surprise to me.

*Note:* After reading Fatalize's comment, I realise that this answer is also *very* close to pajonk's answer to the "Sum of two squares" challenge. Note though that that answer wasn't the shortest in , so a small change to the challenge does seem to favour a completely different approach, which is also nice.

# Answer
> 7 votes
# Python 3.6 (with IO), 73 bytes

```
n=input();l=range(int(n));print(n in[f"{i*i}{j*j}"for i in l for j in l])

```

You could also use,

```
n=input();l=range(int(n));print({n}&{f"{i*i}{j*j}"for i in l for j in l})

```

But unfortunately it doesnt output booleon values rather it outputs, `{n}` for `True` and `set()` for `False`

Try on Online

slightly longer answer (By 2 bytes)

```
n=int(input());print(str(n)in[f"{(k//n)**2}{(k%n)**2}"for k in range(n*n)])

```

and without a loop

```
n=int(input());m=k=0;exec('m+=f"{(k//n)**2}{(k%n)**2}"==str(n);k+=1;'*n**2);print(m>0)

```

# Answer
> 5 votes
# Julia, ~~130~~ ~~122~~ ~~98~~ 91 bytes

```
!x=√parse(Int,x)%1
f(a,s="$a",l=length(s))=0∈1:~-l.|>i->s[l-i]<'1'||!s[i+1:end]+!s[1:i]

```

Try it online!

Thanks to Sunda R we can save 8 bytes!

Thanks to MarcMush we can save ~~32~~ 39 bytes!

# Answer
> 4 votes
# JavaScript (Node.js), ~~56~~ 53 bytes

2 byte from tsh

```
x=>(g=_=>x--&&x*x+'|'+g(),x+g).match(`^(${g()}){2}_`)

```

Try it online!

RegEx with many choices

# Answer
> 4 votes
# Husk, 12 bytes

```
€s¹Σ´Ṫ+mos□ŀ

```

Try it online!

Outputs nonzero for 'concats of two squares', zero for numbers that aren't.

Builds a list of 'concat of two squares' numbers, and then checks if the input is present. So not very efficient for large inputs...

```
€s¹Σ´Ṫ+
       mos    # get strings of
          □ŀ  # all squares up to input,
    ´Ṫ        # combine all combinations
      +       # by concatenation,
   Σ          # flatten the list-of-lists
€s¹           # and look for the input as a string

```

# Answer
> 4 votes
# Julia 1.0, ~~47~~ ~~44~~ 37 bytes

```
~n="$(n^2)"
!a="$a"∈.~(r=0:a)'.*.~r

```

Try it online!

# Answer
> 3 votes
# Burlesque, 29 bytes

```
Jsuf{?sXXsm}0_+)up2CB)++jup~[

```

Try it online!

```
J   # Duplicate
su  # Substrings of
f{  # Filter for
 ?s # Sqrt
 XX # [floor, ceil]
 sm # Same (i.e. is int)
}   # -- Is square
0_+ # Append 0 to list
)up # Unparse each to str
2CB # Combinations of pairs
)++ # Mapped Concat
j   # Reorder stack
up  # Unparse input
~[  # Is in list

```

# Answer
> 3 votes
# C (gcc), ~~127~~ 125 bytes

```
i;r;q(n){for(r=i=n;i;--i)r=r&&i*i-n;i=!r;}t;h;m;f(n){for(t=h=0,m=1;n>9;n/=10,m*=10)n%10|m<2?h+=n%10*m,t|=q(n/10)*q(h):0;n=t;}

```

Try it online!

*Saved 2 bytes thanks to ceilingcat!!!*

# Answer
> 3 votes
# Haskell, ~~54~~ 51 bytes

```
f n|l<-show.(^2)<$>[0..n]=elem(show n)$(++)<$>l<*>l

```

Try it online!

* Thanks to @ovs for saving 3 Bytes.

So much inefficient approach:
*l* is all numbers up to input squared and to string.
We search trough the powerset of *l* if there is a pair that form the input

# Answer
> 3 votes
# Python 2, 68 bytes

Inefficient and somewhat boring approach.

```
lambda n:`n`in('%d'*2%(a*a,b*b)for a in range(1,n)for b in range(n))

```

Try it online!

---

# Python 2, 77 bytes

Much more efficient and interesting.

```
f=lambda n,m=0,d=1:n and((m*10<d!=10)==n**.5%1+m**.5%1)|f(n/10,m+n%10*d,d*10)

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-ap`, ~~69~~ 64 bytes

```
$_=grep{1<grep/^0$|^[^0]/&sqrt!~/\./,unpack$_."A*","@F"+0}A1..A9

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-nE`, ~~78~~ 61 bytes

```
say int=~/^((.+)(?(?{$+eq(0|$+)&(0|sqrt$+)**2==$+})|^))(?1)$/

```

Try it online!

A whopping -17 bytes thanks to @kjs.

**Explanation**:

```
say int                      # convert input to number to remove leading 0s
        =~                   # and match it against the regex
           /^(               # match from the beginning of input
           (.+)              # match 1 or more digits
           (?                # evaluate a condition here
             (?{             # the condition is the result of this code
               $+            # the digits matched so far are in $+
               eq            # string equality check
               (0|$+)        # int($+) - golfy way of writing it
                             # if they're equal, no leading 0s here
               &
               (0|sqrt$+)    # again, golfy form of int(sqrt($+))
               **2==$+}      # square that and compare to original number
               )             # if no leading zeroes and number is a square
                             # do nothing and move on
             |               # else
             ^               # add an impossible pattern here so regex match fails
             )
             )
             (?1)            # now do the same match again, for the second square
             $               # and that should be the end of input
             /x;

```

The trick is in exploiting regex "backtracking" mechanism. Any time the part of the string we're looking at doesn't match the conditions we want, we make the match fail deliberately so that the regex engine chooses a different subset of the input string for the /(.+)/, and automatically tries the match again.

# Answer
> 2 votes
# Retina 0.8.2, 55 bytes

```
^0+

\B
$'¶$`;
A`;0.
\d+
$*
m`(^1|11\1)+;(1(?(2)1\2))*$

```

Try it online! Link includes faster test cases (a `^` after the `m`` would speed it up enough to be able to check `151296561` on TIO). Outputs the count of square concatenations, so for example `144100` can be split up as `144` and `100` or alternatively as `1` and `44100`, so the output would be `2` in that case. Explanation:

```
^0+

```

Delete leading zeros.

```
\B
$'¶$`;

```

Try splitting between every pair of digits.

```
A`;0.

```

Delete numbers with leading zeros.

```
\d+
$*

```

Convert to unary.

```
m`(^1|11\1)+;(1(?(2)1\2))*$

```

Match two square numbers. `(1(?(2)1\2))*` is a generalised match for a square number; `(^1|11\1)+` is a simplified special case for a non-zero square to be matched at the start (of a line).

# Answer
> 2 votes
# Julia 1.0, ~~38~~ 47 bytes

```
~a=string.(a.^2);!a=any(~(0:a)'.*~(0:a).=="$a")

```

Try it online!

Based on MarcMush’s answer (tnx for pointing out the error when squaring)

# Answer
> 1 votes
# Python 3.8 (pre-release), 92 bytes

```
f=lambda n,x=1:x<len(n)and all(e[0]!='0'and int(e)**.5%1==0for e in[n[:x],n[x:]])or f(n,x+1)

```

Try it online!

-28 for @ophact's tip

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
ÝāsânJIå

```

Based on my 05AB1E answer for the *Sum of two squares* challenge.

Try it online or verify (almost) all test cases (`151296561` is omitted since it'll timeout).

**Explanation:**

```
Ý         # Push a list in the range [0, (implicit) input]
 ā        # Push a list in the range [1,length] (without popping the list)
  s       # Swap so the [0,input] list is at the top
   â      # Cartesian product: create all possible pairs using these two lists
    n     # Square each inner integer
     J    # Join each pair together
      Iå  # Check if the input is in this list
          # (after which the result is output implicitly)

```

We can't just use the range \\$\[0,input\]\\$ twice, since it would create a false positive with for example `"09"` and input `9`. We also can't just use the range \\$\[1,input\]\\$ twice, since it would fail with for example input `90`. Hence the use of the range \\$\[1,input+1\]\\$ with \\$\[0,input\]\\$ for the creation of pairs with the cartesian product instead.

# Answer
> 1 votes
# Vyxal, 37 bytes

Probably can be golfed a *lot*, but this is too long for me. So basically for every `i` in input `n`, it checks if both `n[:i]` and `n[i:]` are squares.
I think the time complexity is \\$O(2\*\mathrm{len}(n)) \\$

```
Lʁƛ?fnȯṅ:h⌊[⌊|3]∆²→?fẎṅ:h⌊[⌊|3]∆²←∧;a

```

Explanation:

```
Lʁƛ?fnȯṅ:h⌊[⌊|3]∆²→?fẎṅ:h⌊[⌊|3]∆²←∧;a
Lʁ                                     Exclusive 0 range of length(n)
  ƛ                                    Map through range
   ?f                                  Push stringified n
     nȯṅ                               Slice from loop index to end
        :h⌊[⌊|3]                        Duplicate slice, if int(head) = 0, push 3 (non-square) else int(slice)
               ∆²→                     Set var to "is a perfect square?"
                  ?f                   Push stringified n
                    Ẏṅ                 Slice from 0 to loop index
                      h⌊[⌊|3]           Duplicate slice, if int(head) = 0, push 3 (non-square) else int(slice)
                            ∆²         Is it a perfect square?
                              ←        Get var
                               ∧       Are both are squares?
                                ;a     End map, check if any element is true.

```

Try it Online!

# Answer
> 1 votes
# MATL, 33 bytes

```
Vf3L)"GV@:&),tUV=A3MtX^kU=*w]*?T.

```

Try it out

Outputs 1 for truthy, nothing for falsey.

```
V           % take in number (ignoring initial 0s) and convert to string
f           % get list of its indices (starting from 1)
3L)         % remove the last index
"           % for 1 to end-1
  GV        % get input as string again, say S
  @         % get the current loop index i
  :         % form range 1:i
  &)        % split S[1:i] and S[i+1:end]
  ,         % for each split part
    t       % duplicate it
    U       % convert to numeric
    V       % and back to string - this gets rid of initial 0s
    =A      % condition 1: did that give the same string back?
    3M      % get the numeric form N of the current part again
    tX^kU   % floor(sqrt(N))^2
    =       % condition 2: did that get the number back
            %   i.e. is it a square number
    *       % AND those conditions
    w       % swap the other part in to be checked
  ]         % end
  *?        % if both parts satisfied the conditions
    T       % save True to output
    .       % break
            % (implicit) end
            % (implicit) end
            % (implicit) convert to string and display

```

# Answer
> 1 votes
# Vyxal, 10 bytes

```
›₌ɾʁẊ²vṅ⌊c

```

Try it Online!

An 05AB1E port.

## Explained

```
›₌ɾʁẊ²vṅ⌊c
›          # Increment the input
 ₌ɾʁ       # The range [1, input + 1] and the range [0, input + 1)
    Ẋ      # Cartesian product of those ranges
     ²     # Square each number in each pair
      vṅ⌊  # Integer version of each pair concatenated into a single string
         c # Does that contain the original input?

```

# Answer
> 1 votes
# Charcoal, 20 bytes

```
⊙…¹Ｉθ⊙…⁰Ｉθ⁼θ⪫Ｘ⟦ιλ⟧²ω

```

Try it online! Link is to verbose version of code. Takes input as a string and outputs a Charcoal boolean, i.e. `-` for a concatenation of two squares, nothing if not. Explanation:

```
 …                      Range from
  ¹                     Literal integer `1`
    θ                   To input
   Ｉ                    Cast to integer
⊙                       Does any satisfy
      …                 Range from
       ⁰                Literal integer `0`
         θ              To input
        Ｉ               Cast to integer
     ⊙                  Does any satisfy
           θ            Input as a string
          ⁼             Equals
              ⟦ιλ⟧      List of loop variables
             Ｘ          Vectorised to power
                  ²     Literal integer 2
            ⪫      ω    Joined

```

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


title: Smallest maximal rectangle in a skyline

text:
# Question
Title: Smallest maximal rectangle in a skyline
A skyline is an array of positive integers where each integer represents how tall a building is. For example, if we had the array `[1,3,4,2,5,3,3]` this would be the skyline in ascii art:

```
    #
  # #
 ## ###
 ######
#######

```

A maximal rectangle is a rectangle that cannot be extended in any direction while being contained in the skyline. For example, the following is a maximal rectangle:

```
    #
  # #
 ## ###
 AAAAAA
#AAAAAA

```

While the following is not:

```
    #
  # #
 ## #BB
 ####BB
#####BB

```

Since you can extend it to the left like so:

```
    #
  # #
 ## CCC
 ###CCC
####CCC

```

This would be a maximal rectangle.

Your task is to take a skyline as input (list of positive integers) and return the area of the smallest maximal rectangle. You can assume the length of the input is at least 1.

# Testcases

```
[1] -> 1
[1,1] -> 2
[2,2,2] -> 6
[3,2,3] -> 3
[3,2,1] -> 3
[6,3,1,5] -> 4
[1,5,5,5] -> 4
[5,5,5,1] -> 4
[1,2,3,4] -> 4
[1,2,3,4,5] -> 5
[1,1,1,5,1,1,1] -> 5
[10,3,1,1,1,1,1,3,10] -> 6

```

This is code-golf, so shortest bytes in any language wins!

# Answer
# J, 61 bytes

```
0<./@-.~[:,[:(~.*#-I.@~:)"1@|:[:(0-.~#;._1@,~&0)"1@|.@|:#"+&1

```

Try it online!

*I believe the final test case should be 6 and that 6 3 1 5 should return 4. Needs to be verified by OP.*

Grotesquely long, but perhaps an interesting idea...

## how

Consider `6 3 1 5`.

* `#"+&1` Expand into a sideways bar chart of ones:

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

```
* `|.@|:` Rotate it regular-ways:

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

```
* `[:(0-.~#;._1@,~&0)"1` For each row, count the runs of ones:

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

```
* `|:` Transpose:

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

```
* `[:(~....I.@~:)"1` For each row, get the nub (uniq) and the nub sieve positions (ie, positions of first occurence of each). Eg with row 1:

```
1 1 1 2 2 4  - Row 1
1 2 4        - Uniq
0 3 5        - Positions of first occurrences

```
* `#-` Subtract the positions from length:

```
0 3 5        - Positions of first occurrences
6 3 1        - Length minus positions

```
* `*` Multiply those by the uniq values: gives us sizes of maximal rectangles. (Remember we're still showing just 1 row even though there are multiple)

```
1 2 4        - Uniq
6 3 1        - Length minus positions
-------------
6 6 4        - Elementwise product

```
* `0<./@-.~[:,` Flatten, remove zeroes, take the min.

```
4

```
> 7 votes

# Answer
# Wolfram Language (Mathematica), 56 bytes

```
Min[(aTr/@Pick[a+0(l=SplitBy[#,#<a&]),Min/@l,a])/@#]&

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 24 bytes

Port of *@Jonah*'s J answer:

```
Å1ζRεÅγsÏ}ζεDÙþ©kygα®*}ß

```

Try it online or verify all test cases.

A port of *@Neil*'s Charcoal answer is 24 bytes as well:

```
0.øŒʒD¦¨ß‹Á2£P}ε¦¨Wsg*}ß

```

Try it online or verify all test cases.

**Explanation:**

```
Å1                # Map each value in the (implicit) input-list to a list of that
                  # many 1s
  ζ               # Zip/transpose; swapping rows/columns,
                  # using a space as filler by default for rows of unequal length
   R              # Reverse the rows
    ε             # Map over each row:
     Åγ           #  Run-length encode it, pushing a list of values and lengths
                  #  separated to the stack
       s          #  Swap so the values are at the top
        Ï         #  Only leave the lengths at truthy (==1) positions
    }ζ            # After the map: zip/transpose with space filler again
      ε           # Map over each row:
       D          #  Duplicate the current list
        Ù         #  Uniquify the items in the copy
         þ        #  Remove all spaces by only keeping digits
          ©       #  Store this in variable `®` (without popping)
           k      #  Get the first 0-based index of each unique value in the list
              α   #  Calculate the absolute difference of each index with
            yg    #  the length of the current row-list
               ®* #  Multiply the values to list `®` at the same positions
      }ß          # After the map: pop and push the flattened minimum
                  # (which is output implicitly as result)

```

```
0.ø               # Surround the (implicit) input-list with leading/trailing 0
   Œ              # Pop and push all sublists
ʒ                 # Filter this list of lists by:
 D                #  Duplicate the sublist
  ¦¨              #  Remove the first and last items in the copy
    ß             #  Pop and push the minimum
     ‹            #  Check for each value in the list if this minimum is larger
      Á           #  Rotate the list of checks once towards the right
       2£         #  Pop and leave just the first two
         P        #  Product to check if both of them are truthy
}ε                # After the filter: map over the remaining sublists:
  ¦¨              #  Remove the first and last items again
    W             #  Push the minimum (without popping the list)
                  #  (this will be an empty string for empty lists)
     s            #  Swap so the list is at the top
      g           #  Pop and push its length
       *          #  Multiply the length by this minimum
 }ß               # After the map: pop and push the minimum integer (ignoring any
                  # empty strings)
                  # (which is output implicitly as result)

```
> 5 votes

# Answer
# Jelly, 16 bytes

```
Ø0jẆµḢ»Ṫ<aṂ)ȦƇ§Ṃ

```

A monadic Link accepting a list of positive integers that yields a positive integer.

**Try it online!** Or see the test-suite.

### How?

```
Ø0jẆµḢ»Ṫ<aṂ)ȦƇ§Ṃ - Link: list of positive integers, H
Ø0               - [0,0]
  j              - join with S -> [0,h1,h2,...,hn,0]
   Ẇ             - all contiguous sublists
    µ      )     - for each sublist, S:
     Ḣ           -   remove & yield the head from S
       Ṫ         -   remove & yield the tail from S (yields 0 if S was empty)
      »          -   maximum
        <        -   less than? (vectorises across the altered S)
          Ṃ      -   minimum (of the altered S; 0 if S is empty)
         a       -   logical AND (vecorises)
             Ƈ   - filter keep those for which:
            Ȧ    -   any and all? (i.e. non-empty and all non-zero)
              §  - sums
               Ṃ - minimum

```

---

Also at 16 (TIO), and perhaps more elegant:

```
>Ɱ’aṣ€0Ẏ¹ƇṂ×LƊ€Ṃ - Link: H
 Ɱ’              - map across decremented values of H with:
>                -   H greater than? (vectorises)
   a             - logical AND H (vectorises)
    ṣ€0          - split each at zeros
       Ẏ         - tighten
        ¹Ƈ       - keep the truthy (i.e. non-empty) ones
             Ɗ€  - for each:
          Ṃ      -   minimum
            L    -   length
           ×     -   multiply
               Ṃ - minimum

```
> 5 votes

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

*-2 bytes by Arnauld*

```
a=>Math.min(...a.map((n,i)=>(g=d=>a[i+=d]>=n&&g(d)+n)(-1,g(1))))

```

Try it online!

Simply find the *smallest* one from all *maximal* rectangles:

```
    *       *       *       *       #       *       *
  * *     * *     # *     * *     * #     * *     * *
 ** ***  ## ***  *# ***  ** ***  ** #**  ** ###  ** ###
 ******  ##****  *#****  ######  ***#**  ***###  ***###
####### *##**** **#**** *###### ****#** ****### ****###

```

Above example show all possible maximal rectangles with height \\$a\_i\\$.

Related
> 4 votes

# Answer
# Charcoal, 40 bytes

```
⊞θ⁰ＦＬθＦιＦ⬤⟦⊖κι⟧›⌊✂θκι¹§θλ⊞υ×⁻ικ⌊✂θκι¹Ｉ⌊υ

```

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

```
⊞θ⁰

```

Push a guard value to the input array. (This also simplifies the iteration as in my answer to the linked question I had to increment variables all over the place but here I effectively get a free increment.)

```
ＦＬθＦι

```

Loop over all of the sublists of the original array.

```
Ｆ⬤⟦⊖κι⟧›⌊✂θκι¹§θλ

```

Check that the minimum of this sublist is greater than both of its neighbours.

```
⊞υ×⁻ικ⌊✂θκι¹

```

Calculate the size of this maximal rectangle.

```
Ｉ⌊υ

```

Output the minimum of all the sizes.
> 4 votes

# Answer
# Jelly, 22 bytes

```
>Ḣ×\×«\ŒɠÄ×QƲ
ŻÇÐƤẎ¹ƇṂ

```

Try it online!

*Should* work now. Filters each suffix to the longest prefix which wouldn't contain suffixes of other suffixes' rectangles, computes the area of each maximal rectangle sharing its left edge with each of those substrings, and returns the smallest non-zero such area.

```
>Ḣ×\×«\ŒɠÄ×QƲ    Monadic helper link: compute areas from "maximal zone" of suffix
 Ḣ               Remove the first item
>                and compute the mask of which remaining items are greater.
  ×\             Zero any ones after the first zero,
    ×            then multiply with corresponding elements of
     «\          the cumulative minima.
       Œɠ        Compute the lengths of runs of equal minima,
         Ä       take the cumulative sums of those,
          ×      and multiply with corresponding elements of
           QƲ    the nub of the cumulative minima.

ŻÇÐƤẎ¹ƇṂ    Main link
Ż           Prepend a 0.
 ÇÐƤ        Call the helper on each suffix,
    Ẏ       concatenate the resulting lists of areas,
     ¹Ƈ     remove 0s,
       Ṃ    and return the minimum.

```
> 2 votes

# Answer
*Doesn't work as intended... yet*

# Husk, ~~16 bytes~~

```
▼M₁¹
*⁰▲mLfo=⁰▼Q

```

Try it online!

### Explanation

```
▼M₁¹    translates to ▼M₁⁰⁰
 M₁⁰⁰   for each number in the input, call the second line with (each number N, the whole input A)
▼       take the minimum of the results

*⁰▲mLfo=⁰▼Q    translates to *⁰▲mLfo=⁰▼Q²
          Q²   each contiguous sublist of A
     fo=⁰▼     filter out the sublists where it's minimum value is N
   mL          take the lengths
*⁰▲            multiply N with the maximum of the lengths

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
aMin[SequenceCases[a,b_/;Min@b==#:>Tr[0b+#]]&/@a]

```

Try it online!

```
                                            /@a     for each height:
    SequenceCases[a,b_          :>Tr[0b+#]]           areas of maximal rectangles
                      /;Min@b==#                          with that height
Min[                                           ]    smallest

```
> 2 votes

# Answer
# Haskell + hgl, 24 bytes.

```
nM(mn*×l)<(bn*^fgF^.ge)

```

In the interested of transparency, since hgl is under heavy development some features used in this answer were only merged into master recently. I wanted to make this answer to show them off.

## Explanation

There are two parts to this first is `bn*^fgF^.ge` this takes every element of the list and gives contiguous sections where all elements are above that height.

So for example `[1,9,3,5,6,7,5]`:

```
  [9]
  [9]     [7]
  [9]   [6,7]
  [9] [5,6,7,5]
  [9,3,5,6,7,5]
[1,9,3,5,6,7,5]

```

Note that there are some duplicates, e.g. `[9]` appears here several times. In addition they are not actually output in this order show here but this is fine for demonstration purposes.

Each list here represents the footprint of a box which cannot be widened. The height of that box is then the minimum element that appears in the footprint.

The second part is `nM(mn*×l)`. This takes each element produced in the first step and multiplies its length by its minimum to get the size of the box. It takes the overall minimum as the result.

## Reflections

This feels a tad long, we have some really powerful tools here like `nM` and `fgF`, but we mostly get bogged down in other stuff. Unfortunately I have few thoughts on how this could be improved.
> 2 votes

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


title: Largest rectangle in a skyline

text:
# Question
Title: Largest rectangle in a skyline
A skyline is an array of positive integers where each integer represents how tall a building is. For example, if we had the array `[1,3,4,2,5,3,3]` this would be the skyline in ascii art:

```
    #
  # #
 ## ###
 ######
#######

```

Your task is to find the area of the largest rectangle in the skyline. In this case, the largest rectangle has area 12. Here is the rectangle, highlighted:

```
    #
  # #
 ## ###
 RRRRRR
#RRRRRR

```

You can assume that the input contains at least one building (the length of the array is \>0). This is , you know the drill.

Inspired by this Puzzling-SE post.

# Test cases

```
[1] -> 1
[2, 2] -> 4
[3, 2, 1] -> 4
[1, 2, 3] -> 4
[1, 5, 1, 5] -> 5
[1, 4, 1, 4, 1] -> 5
[1, 4, 5, 4, 1] -> 12
[1, 5, 4, 5, 1] -> 12
[1, 2, 3, 5, 1, 3] -> 6
[1, 3, 3, 1, 4, 5, 2] -> 8
[1, 3, 3, 1, 1, 1, 1] -> 7

```

# Answer
> 9 votes
# Octave, 50 bytes

```
@(a)max(([c,v]=runlength([(a<=a').*a;0*a](:))).*v)

```

Try it online!

Based on my PARI/GP answer, but more interesting. This worth writing a Jonah-style explanation.

### how

Takes `a = [1,3,4,2,5,3,3]` as an example.

* `a<=a'` creates a matrix where the entry at `(i,j)` is `a[j]<=a[i]`:

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

```
* `.*a` multiplies the `i`-th column of the matrix with `a[i]`:

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

```
* `[...;0*a]` appends a row of zeros to the matrix, so that the columns are separated when taking run length encoding:

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

```
* `...(:)` concatenates the matrix into a column vector (the actual output is the transpose of the following row vector):

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

```
* `[c,v]=runlength` gives the run length encoding, where each non-zero run corresponds to a rectangle in the skyline:

```
c =
7   2   2   1   3   3   1   1   1   4   6   5   1   4   2   1   3   2   2   1   3   1

v =
1   0   3   0   3   0   4   0   4   0   2   0   5   0   3   0   3   0   3   0   3   0

```
* `([c,v]=runlength(...)).*v` multiplies `c` and `v` element by element, which gives the "area" of each run:

```
7    0    6    0    9    0    4    0    4    0   12    0    5    0    6    0    9    0    6    0    9    0

```
* Finally, `max` finds the maximum values of the result:

```
12

```

# Answer
> 8 votes
# Jelly, 7 bytes

```
ẆṂ×LƊ€Ṁ

```

Try it online!

```
Ẇ   Ɗ€     For each contiguous sublist of the input,
 Ṃ×        multiply its smallest element by
   L       its length.
      Ṁ    Return the largest product.

```

# Answer
> 6 votes
# Python 3, 56 bytes basically by AnttiP

```
f=lambda x:x>[]and max(min(x)*len(x),f(x[1:]),f(x[:-1]))

```

Try it online!

# Python 3, 72 bytes

```
lambda x:max(min(x[i:j])*(j-i)for j in range(len(x)+1)for i in range(j))

```

Try it online!

# Python 3.8 (pre-release), ~~86~~ 85 bytes

```
lambda x:(R:=range(0,len(x)+1))and max(min(x[i:j])*(j-i)for i in R for j in R if i<j)

```

Try it online!

Avoid something by pxeger

# Answer
> 6 votes
# Wolfram Language (Mathematica), 35 bytes

-5 bytes thanks to @att.

```
Max[Tr[Min@#+0#]&/@Subsequences@#]&

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 8 bytes

```
ŒεWsg*}à

```

Port of *@UnrelatedString*'s Jelly answer, so make sure to upvote him/her as well!

Try it online or verify all test cases.

**Explanation:**

```
Œ       # Get all sublists of the (implicit) input-list
 ε      # Map each sublist to:
  W     #  Push its minimum (without popping the sublist)
   s    #  Swap so the sublist is at the top again
    g   #  Pop and push its length
     *  #  Multiply it by the minimum
 }à     # After the map: pop and push the maximum
        # (after which it is output implicitly as result)

```

# Answer
> 5 votes
# BQN, 18 bytesSBCS

```
{⌈´(+´≠⥊⌊´)¨∾↓¨↑}

```

Run online!

Prefixes of the input (includes the empty prefix)
`↓¨` Suffixes of each prefix
Flatten into a list of sublists
`( )¨` For each sublist:
`≠⥊⌊´` Reshape the minimum to the length of the sublist

Sum the resulting list `⌈´` Get the maximum result

Instead of `+´≠⥊⌊´` other answers use `≠×⌊´`, but that results in `0×∞ = NaN` for empty sublists, which ends up as the result of `⌈´`.

# Answer
> 5 votes
# Vyxal, 9 bytes

```
ÞSƛgnL*;G

```

Try it Online!

Port of Unrelated String's Jelly answer.

```
ÞSƛ    ;  # For each contiguous sublist
   g  *   # Multiply the smallest element
    nL    # The length.
        G # Get the largest product.

```

# Answer
> 5 votes
# , 63 bytes

```
function(l,r=rle(c(t(cbind(outer(l,l,`<=`)*l,0)))))max(r$l*r$v)

```

Try it online!

Port of alephalpha's solution.

# Answer
> 4 votes
# Brachylog, 9 bytes

```
sᶠ⟨⌋×l⟩ᵐ⌉

```

Try it online!

```
sᶠ    ᵐ     For each contiguous sublist of the input,
  ⟨⌋× ⟩      multiply its smallest element by
    l       its length.
       ⌉    Return the largest product.

```

# Answer
> 4 votes
# MATL, ~~17~~ ~~15~~ 14 bytes

```
&<~G!*"@Y'*vX>

```

Try it out or Test all cases

*(Edit: turns out alephalpha's idea is very similar, this just uses a loop instead of zero padding + linearization)*

With input \[1; 2; 3; 5; 1; 3\]

```
&<~         % make a boolean matrix, each column denoting
            %   which buildings are >= current one

```

1 0 0 0 1 0
1 1 0 0 1 0
1 1 1 0 1 1
1 1 1 1 1 1
1 0 0 0 1 0
1 1 1 0 1 1

```
G!*         % multiply by input

```

1 0 0 0 1 0
1 2 0 0 1 0
1 2 3 0 1 3
1 2 3 5 1 3
1 0 0 0 1 0
1 2 3 0 1 3

```
"@Y'        % for each column, take its run-length encoding

```

eg. for second column,
\[0 2 0 2\]
\[1 3 1 1\]

```
*           % multiply to get rectangle areas

vX>         % cumulatively, keep finding the maximum area

            % implicit loop end, implicit output

```

-1 byte thanks to @LuisMendo.

# Answer
> 2 votes
# Factor, 58 bytes

```
[ all-subseqs [ dup infimum swap length * ] map supremum ]

```

Try it online!

Port of @UnrelatedString's Jelly answer.

* `all-subseqs` Get every possible grouping of contiguous skyscrapers.
* `[ dup infimum swap length * ] map` Get the area of each grouping by multiplying the height of the shortest skyscraper in the grouping by the number of skyscrapers in the grouping.
* `supremum` Return the largest area.

# Answer
> 2 votes
# Pari/GP, 50 bytes

```
a->m=vecmax;m([m([c=(t>=s)*c+=s|t<-a*!c=0])|s<-a])

```

Try it online!

---

# Pari/GP, 50 bytes

```
a->m=0;[[m=max(m,c=(t>=s)*c+=s)|t<-a*!c=0]|s<-a];m

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 69 bytes

```
f=a=>+a||Math.max(Math.min(...a)*a.length,f(a.slice(1),a.pop()),f(a))

```

Try it online!

### Commented

```
f =                // f is a recursive function taking:
a =>               //   a[] = skyline array
  +a ||            // if a[] is a singleton, return its unique value
  Math.max(        // otherwise, return the maximum of:
    Math.min(...a) //   1) the smallest value of a[]
    * a.length,    //      multiplied by the length of a[]
    f(             //   2) the result of a recursive call
      a.slice(1),  //      with the 1st item removed
      a.pop()      //      (remove the last item for the next call)
    ),             //
    f(a)           //   3) the result of a recursive call
                   //      with the last item removed
  )                // end of Math.max()

```

# Answer
> 2 votes
# Charcoal, 19 bytes

```
Ｉ⌈Ｅθ⌈Ｅ⊕κ×⁻⊕κλ⌊✂θλ⊕κ

```

Try it online! Link is to verbose version of code. Explanation: Port of @l4m2's Python answer.

```
   θ                Input array
  Ｅ                 Map over elements
       κ            Current index
      ⊕             Incremented
     Ｅ              Map over implicit range
           κ        Outer index
          ⊕         Incremented
         ⁻          Subtract
            λ       Inner index
        ×           Multiplied by
               θ    Input array
              ✂     Sliced from
                λ   Inner index to
                  κ Outer index
                 ⊕  Incremented
             ⌊      Take the minimum
    ⌈               Take the maximum
 ⌈                  Take the maximum
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 2 votes
# Python3, 78 bytes:

```
f=lambda x,c=0,j=1:j>len(x)or max([min(x[c:j])*(j-c),f(x,c,j+1),f(x,c+1,j+1)])

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~108~~ 97 bytes

```
m;s;j;k;f(a,n)int*a;{for(m=0;n--;)for(j=a[n];s=j;--j,m=s>m?s:m)for(k=n;k--;)s+=a[k]<j?k=0:j;j=m;}

```

Try it online!

Inputs a pointer to an array of positive integers and its length (because pointers in C carry no length info).
Returns the area of the largest rectangle in the skyline.

# Answer
> 1 votes
# APOL, 29 bytes

`M(ƒ(z(Ŀ(s(i))) *(m(∋) l(∋))))`

A port of UnrelatedString's Jelly answer.

## Explanation

```
M(                Largest element of
  ƒ(              For
    z(Ŀ(s(i)))    every contiguous sublist of the input,
    *(m(∋) l(∋))  multiply its smallest item by its length
  )               and make a list of the results.
)
                  implicit print

```

# Answer
> 1 votes
# Husk, 7 bytes

```
▲m§*▼LQ

```

Try it online!

### Explanation

```
▲m§*▼LQ
 m    Q   for each contiguous sublist
  §*      multiply it's
    ▼L    minimum value by it's length
▲         maximum of that

```

# Answer
> 1 votes
# JavaScript (Node.js), 64 bytes

```
a=>Math.max(...a.map((n,i)=>(g=d=>a[i+=d]>=n&&g(d)+n)(-1,g(1))))

```

Try it online!

Related

# Answer
> 1 votes
# Haskell + hgl, 13 bytes

```
xM(mn*×l)<cg

```

In the interested of transparency, since hgl is under heavy development some features used in this answer were only merged into master recently.

## Explanation

We just use the most straightforward possible algorithm.

`cg` gets all contiguous sublists we take these as the footprints for potential boxes. We then for each of these multiply it's length by it's minimum element with `mn*×l` and take the maximum overall.

This is just a simpler version of the algorithm employed in the more interesting version of this challenge.

# Answer
> 0 votes
# Haskell, 65 bytes

```
f l=maximum[x*(minimum$take x t)|t<-scanr(:)[]l,x<-[1..length t]]

```

Try it online!

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


title: Character Cross

text:
# Question
Title: Character Cross
I was expecting to post something more complex as my first puzzle in PCG, but a particular, uh... homework question on Stack Overflow inspired me to post this. They want to:

> print the following pattern for any given word that contains **odd** number of letters:
>
> ```
> P           M
>   R       A
>     O   R
>       G
>     O   R
>   R       A
> P           M
>
> ```

---

> Notice that letters are a knight's move apart in the pattern you need to print. So, every other column is empty. -- (Thanks xnor for pointing this out.)

## Rules

1. Using C++ is prohibited. As I may link this question there.
2. You may use `stdout`, or any means of quickly outputting a string (e.g. `alert()` in JavaScript).
3. As always, shortest code wins.

# Answer
# Canvas, 5 bytes

```
＼＼：⇵ｎ

```

Try it here!

Explanation:

```
\      create a diagonal of the input
 \     create an even steeper diagonal of that
  :⇵   reverse a copy of it vertically
    n  overlap the two

```
> 5 votes

# Answer
## APL (~~37~~ ~~35~~ ~~34~~ 27)

```
↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞

```

It takes input from the keyboard, like so:

```
      ↑{∊2↑¨⍵↑¨I}¨↓(+∨⌽)∘.=⍨⍳⍴I←⍞
CODE-GOLF
C               F
  O           L
    D       O
      E   G
        -
      E   G
    D       O
  O           L
C               F

```
> 22 votes

# Answer
# Python 2 - ~~94 90 89~~ 88

```
s=input()
L=len(s)
R=range(L)
for i in R:print" ".join([s[j]," "][j!=i!=L+~j]for j in R)

```

**Input:**

```
"CODE-GOLF"

```

**Output:**

```
C               F
  O           L
    D       O
      E   G
        -
      E   G
    D       O
  O           L
C               F

```
> 13 votes

# Answer
# Pyth, 22

```
Vzjdm?@zd}N,dt-lzd\ Uz

```

Test:

```
$ pyth -c 'Vzjdm?@zd}N,dt-lzd\ Uz' <<< "CODE-GOLF"
C               F
  O           L
    D       O
      E   G
        -
      E   G
    D       O
  O           L
C               F

```

Explanation:

```
(Implicit)                  z = input()
(Implicit)                  d = ' '
Vz                          for N in range(len(z)):
  jd                            print(d.join(
    m                               map(lambda d:
     ?@zd                                        z[d] if
         }N                                      N in
           ,dt-lzd                                    (d,len(z)-d-1) else
      \                                          " ",
     Uz                                          range(len(z)))))

```
> 13 votes

# Answer
## Python 3: 75 chars

```
s=input()
i=n=len(s)
while i:i-=1;a=[" "]*n;a[i]=s[i];a[~i]=s[~i];print(*a)

```

For line `i`, we start with a list of spaces and set the entries `i` from the front and back to be equal to the letters of the input string. Then, we print the result.

Python strings are immutable, so `a` must be a list of characters instead. The list `a` must be initialized inside the loop or the modifications will carry over between loops. We use `print(*a)` to print each character in the list, space separated, which requires Python 3.

The output lines are symmetrical, so we can have `i` count down rather than up using a while loop.

```
>>> CODE-GOLF
C               F
  O           L
    D       O
      E   G
        -
      E   G
    D       O
  O           L
C               F

```

It also works for an even number of letters.

```
>>> CODEGOLF
C             F
  O         L
    D     O
      E G
      E G
    D     O
  O         L
C             F

```
> 11 votes

# Answer
# CJam, ~~27~~ 25 bytes

```
l_,S*:Sf{W):W2$tW~@tS}zN*

```

Try it online.

### Example run

```
$ cjam <(echo 'l_,S*:Sf{W):W2$tW~@tS}zN*') <<< CROSS; echo
C       S
  R   S
    O
  R   S
C       S

```

As the example in the answer, each line has trailing whitespace.

### How it works

```
                             " N := '\n'; R := []; S = ' '; W := -1 ";
l                            " Q := input()                         ";
 _,S*:S                      " S := len(Q) * S                      ";
       f{            }       " for each C in Q:                     ";
                             "   T := S                             ";
         W):W                "   W += 1                             ";
             2$t             "   T[W] := C                          ";
                W~@t         "   T[~W] := C                         ";
                             "   R += [T]                           ";
                    S        "   R += [S]                           ";
                      z      " R := zip(R)                          ";
                       N*    " R := N.join(R)                       ";
                             " print R                              ";

```
> 8 votes

# Answer
# Pure Bash, 94 bytes

```
l=${#1}
for((;t<l*l;t++));{
((x=t%l))||echo
((x-t/l&&x+t/l+1-l))&&printf \ ||printf ${1:x:1}
}

```
> 5 votes

# Answer
# , ~~99~~ ~~98~~ ~~93~~ 89 bytes

```
m=ifelse(diag(l<-length(w<-el(strsplit(scan(,''),'')))),w,' ')
write(pmax(m,m[,l:1]),1,l)

```

Try it online!

Line 1 reads input string, splits it into characters, stores its length and creates a matrix with the word on its main diagonal – letters of the word are superposed on an identity matrix (and repeated by default to match its length) and only those matching 1's are retained, others being replaced by spaces.

Line 2 prints a matrix formed by elements of either the diagonal matrix or its horizontally mirrored version, whichever are greater.

*−2 + 1 = −1 byte thanks to JayCe*

*−4 bytes thanks to Giuseppe*
> 5 votes

# Answer
# JavaScript (E6) 101 ~~95 129 136~~

**Edit** Wrong letter spacing. Fixed.
**Edit** Simpler and shorter using classic for loops
As a function, output via popup.

```
F=a=>{
  for(l=a.length+1,i=s=o='';++i<l;s='\n')
    for(j=0;++j<l;)
      o+=s+((s=' ')+a)[j==i|i+j==l&&j]
  alert(o)
}

```

*Previous version* using .map

```
F=a=>alert([...a].map((c,p)=>
  --q<p
  ?B(q)+a[q]+B(p-q-1)+c
  :B(p)+c+(p-q?B(q-p-1)+a[q]:'')
,B=n=>' '.repeat(n),q=a.length).join('\n'))

```

**Test** In FireFox/FireBug console

```
F('Java-Script')

```

*Output*

```
J                   t
  a               p
    v           i
      a       r
        -   c
          S
        -   c
      a       r
    v           i
  a               p
J                   t

```
> 4 votes

# Answer
# Ruby, 64

```
f=->w{x=w.size
x.times{|i|y=" "*x
y[i],y[~i]=w[i],w[~i]
puts y}}

```

## Explanation

* Input is taken as the argument to a lambda. It expects a `String`.
* In a loop that loops trough every character in the word (`n` in total):
    + Create a String consisting of `n` spaces.
    + Replace the `i`th and `n-i`th (`~i`, thanks xnor) space with the `i`th and `n-i`th character of the input.
    + Print the line
> 4 votes

# Answer
# Java - 168

A simple nested loop, there's nothing really special going on here.

```
class C{public static void main(String[]a){int b=-1,c=a[0].length()-1,d;for(;b++<c;)for(d=-1;d++<c;)System.out.print((b==d|b==c-d?a[0].charAt(d):" ")+(c==d?"\n":""));}}

```

With line breaks:

```
class C{
    public static void main(String[]a){
        int b=-1,c=a[0].length()-1,d;
        for(;b++<c;)
            for(d=-1;d++<c;)
                System.out.print(
                    (b==d|b==c-d?a[0].charAt(d):" ")+
                    (c==d?"\n":""));
    }
}

```
> 4 votes

# Answer
# Javascript 102 84 85

*Edit: Had to fix spacing. Not so small anymore.*

```
function p(s){for(i in s){o='';for(n in s)o+=(n==i?s[n]:n==s.length-1-i?s[n]:' ')+' ';console.log(o)}}

p('Thanks-Dennis')

T                       s
  h                   i
    a               n
      n           n
        k       e
          s   D
            -
          s   D
        k       e
      n           n
    a               n
  h                   i
T                       s

```
> 4 votes

# Answer
# Befunge-93, ~~68~~ 71

```
:~:84*-!#@#v_\:2*\4+p1+
::+\4+g:!| >$1+0:>p1-::
00+4\*2:\<>0p#:- ^#2g

```

You can test it here. It'll come up with an input dialog box on each pass through `~`; enter your word one character at a time (it does say the input is 'klunky' after all), ending with a space.

It won't print to the console; this wouldn't be Befunge without a hint of self-modification, after all! Instead it will modify its own grid to display the message. After it's done, the grid will look something like this:

```
 ~:84*-!#@#v_\:2*\4+p1+
::+\4+g:!| >$1+0:>p1-::
00+4\*2:\<>0p#:- ^#2g

c               f
  o           l
    d       o
      e   g
        -
      e   g
    d       o
  o           l
c               f

```

(Note the noble sacrifice of the cell at (0,0), after we know the pointer won't go there anymore, for the purpose of storing a piece of data.)

It also works with inputs of even length. Note that, since Befunge-93 is limited to an 80x25 grid, the input size is limited to 21 characters if you run it in a Befunge-93 interpreter. Running it as Befunge-98 should remove this limit.

*Edit* \- Now it works more along the lines of the intended output, at the expense of only three characters of length.
> 4 votes

# Answer
## CJam, ~~38~~ ~~36~~ ~~35~~ ~~34~~ 32 bytes

```
l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N}

```

Test it here. This reads the input word from STDIN. It also works for an even number of characters. This prints a trailing column of spaces, but I don't see anything in the rules against that.

Explanation

```
l:I,,_f{f{_2$=@2$+I,(=|\I=S?S}N}
l:I                              "Read input and store it in I.";
   ,                             "Get string length.";
    ,_                           "Turn into range and duplicate.";
      f{                       } "Map block onto first range, with second range on the stack.";
        f{                   }   "Map block onto second range, with first iterator in stack.
                                  Each invocation of this block will start with grid coordinates
                                  y and x on the stack (x on top).";
          _2$=                   "Duplicate x, duplicate y, check for equality.";
              @2$+               "Pull up y, duplucate x, add,";
                  I,(=           "Check if that's one less than the string length.";
                      |          "Bitwise or between conditions.";
                       \         "Swap condition and x.";
                        I=       "Take x'th character from the string.";
                          S?     "Push a space and select character depending on condition.";
                            S    "Push another space.";
                              N  "Push a line feed.";

```

The contents of the stack are printed automatically at the end of the program.
> 3 votes

# Answer
# C, 105

two slightly different ways of doing it.

```
c,i,j;main(int l,char**v){for(l=strlen(v[1]);j-l;)putchar((c=v[1][i++])?i-1-j&&l-i-j?32:c:(i=0,j++,10));}

i,j;main(int l,char**v){for(l=strlen(v[1]);j-l;i++)putchar((l-i)?i-j&&l-i-j-1?32:v[1][i]:(i=-1,j++,10));}

```

If you want to add extra spaces, replace `putchar(` with `printf(" %c",` for an extra 5 characters.
> 3 votes

# Answer
## J - 36 30 bytes:

*Edit:* 6 characters shorter, credits go to @algorithmshark .

```
(1j1#"1' '&,({~](*>.*&|.)=)#\)

```

eg:

```
   (1j1#"1' '&,({~](*>.*&|.)=)#\) 'Code-Golf'
C               f
  o           l
    d       o
      e   G
        -
      e   G
    d       o
  o           l
C               f

```

Bonus: works with even length strings too:

```
   (1j1#"1' '&,({~](*>.*&|.)=)#\) 'CodeGolf'
C             f
  o         l
    d     o
      e G
      e G
    d     o
  o         l
C             f

```
> 3 votes

# Answer
# Prolog - 240 bytes

```
:-initialization m.
+[]. +[H|T]:-(H=' ';!),+T.
+[H|T]+I+X:-0=:=I,X=H;+T+(I-1)+X.
+L+I+C+S:-L=:=I;S=[D|E],+C+I+B,+C+(L-I-1)+B,+B+2*I+D,+L+(I+1)+C+E,+B,writef('%s\n',[B]).
-X:-get_char(C),(C='\n',X=[];X=[C|Y],-Y).
m:- -X,length(X,L),+L+0+_+X.

```

Invocation:

```
$ echo "Code-Golf" | swipl -qf c.pl
C               f
  o           l
    d       o
      e   G
        -
      e   G
    d       o
  o           l
C               f

```

Readable:

```
:- initialization(main).

vars_to_spaces([]).
vars_to_spaces([' '|T]) :- vars_to_spaces(T).
vars_to_spaces([_|T]) :- vars_to_spaces(T).

get_index([Head|_], Index, Result) :-
    0 =:= Index,
    Result = Head.
get_index([_|Tail], Index, Result) :-
    get_index(Tail, Index-1, Result).

print_loop(Length, Index, Board, String) :-
    Length =:= Index;
    String = [FirstChar|RestString],
    get_index(Board, Index, Line),
    get_index(Board, Length-Index-1, Line),
    get_index(Line, 2*Index, FirstChar),
    print_loop(Length, Index+1, Board, RestString),
    vars_to_spaces(Line),
    writef('%s\n', [Line]).

get_line(Line) :-
    get_char(C),
    (   C = '\n', Line = [];
        Line = [C|More], get_line(More)).

main :-
    get_line(String),
    length(String, Length),
    print_loop(Length, 0, _, String).

```
> 3 votes

# Answer
# Jelly, 11 bytes

```
LḶḤ⁶ẋ;"µ»ṚY

```

Try it online!
> 3 votes

# Answer
# Powershell, 78 bytes

+8 bytes thanks @streetster

```
param($s)$s|% t*y|%{$r=,' '*$s.length;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '}

```

Explaned test script:

```
$f = {

param($s)               # declare a parameter $s stores a word
$s|% t*y|%{             # split $s into chars https://codegolf.stackexchange.com/a/168174/80745
    $r=,' '*$s.length   # create an array of spaces with length equal length of the word
    $r[$i++]=$_         # set first char
    $r[-$i]=$s[-$i]     # set last char
    $r-join' '          # join the array to string
}

}

&$f PROGRAM
''
&$f sword
''
&$f uhm
''
&$f o
''
&$f codegolf  # It works with word that contains even number of letters

```

# Powershell, 70 bytes (if a word can be represented by an array of chars)

+8 bytes thanks @streetster

```
($s=$args)|%{$r=,' '*$s.count;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '}

```

Test script:

```
$f = {

($s=$args)|%{$r=,' '*$s.count;$r[+$i++]=$_;$r[-$i]=$s[-$i];$r-join' '}

}

&$f P R O G R A M
''
&$f s w o r d
''
&$f u h m
''
&$f o
''
&$f c o d e g o l f  # It works with word that contains even number of letters

```

Output for both cases:

```
P           M
  R       A
    O   R
      G
    O   R
  R       A
P           M

s       d
  w   r
    o
  w   r
s       d

u   m
  h
u   m

o

c             f
  o         l
    d     o
      e g
      e g
    d     o
  o         l
c             f

```
> 3 votes

# Answer
## C# (~~214~~ 212)

(Certainly badly) Golfed version:

```
using System;class A{static void Main(){char[]a,w=Console.ReadLine().ToCharArray();int l=w.Length,i=0;for(;i<l;i++){a=new string(' ',2*l-1).ToCharArray();a[2*i]=w[i];a[2*l-2*i-2]=w[l-i-1];Console.WriteLine(a);}}}

```

Ungolfed version:

```
using System;

class A
{
  static void Main()
  {
    char[] a, w = Console.ReadLine().ToCharArray();
    int l = w.Length, i = 0;
    for (; i < l; i++)
    {
      a = new string(' ', 2 * l - 1).ToCharArray();
      a[2 * i] = w[i];
      a[2 * l - 2 * i - 2] = w[l - i - 1];
      Console.WriteLine(a);
    }
  }
}

```

Any hints, tips, tricks or remarks are very welcome, as this is my first attempt at CodeGolf. I just wanted to try it, even though I know my C# byte length won't even come close to double the best solutions ;)

And how do you guys count your bytes? I just posted the above into a Quick Watch window and did `.Length`. I could write a small program to count bytes for me, but I bet there is an easier way that I don't yet know.
> 2 votes

# Answer
# JavaScript (ES6) - ~~185~~ ~~177~~ ~~175~~ 170 bytes

```
f=n=>{return s='  ',r='repeat',n=[...n],l=n.length,j=l/2-.5,[...h=n.slice(0,j).map((c,i)=>s[r](i)+c+s[r](l-2-(i*2))+' '+n[l-i-1]),s[r](j)+n[j],...h.reverse()].join('\n')}

```

Put this in the Firefox console and run as `f('PROGRAM')`:

```
P           M
  R       A
    O   R
      G
    O   R
  R       A
P           M

```

`f("CODE-GOLF")`:

```
C               F
  O           L
    D       O
      E   G
        -
      E   G
    D       O
  O           L
C               F

```
> 2 votes

# Answer
# Mathematica, 149 bytes

```
FromCharacterCode@Flatten[Append[Riffle[#,32],10]&/@MapThread[Max,{#,Reverse@#,ConstantArray[32,Dimensions@#]},2]&@DiagonalMatrix@ToCharacterCode@#]&

```

Input passed as parameter to the function; function returns the output string. There is a trailing newline at the end of the output.

Explanation: We create a diagonal matrix with the string, then we create a copy of it vertically flipped using `Reverse@#` to reverse the rows. Then we have a third matrix of the same dimensions containing only 32 (ascii space). We use `MapThread` to take the element-wise max of these 3 matrices. Finally, we `Riffle` spaces into each row, `Append` a newline at the end, and `Flatten` the result.
> 2 votes

# Answer
# Perl - 90

It might be possible to squeeze some more characters out of this:

```
($j=$i++%8)==7?++$k&&print"\n":print$j+1==$k||7-$j==$k?"$_ ":"  "for split//,($_ x y///c)

```

`89` \+ `1` for `-n`.

Run with:

```
echo "program" | perl -nE'($j=$i++%8)==7?++$k&&print"\n":print$j+1==$k||7-$j==$k?"$_ ":"  "for split//,($_ x y///c)'

```

Output:

```
p           m
  r       a
    o   r
      g
    o   r
  r       a
p           m

```
> 2 votes

# Answer
# PowerShell ~~118~~ ~~102~~ 97

```
($x=[char[]]"$args")|%{$i++;$y=[char[]]" "*$x.Count;$y[$i-1]=$x[$i-1];$y[-$i]=$x[-$i];$y-join' '}

```

Outputs:

```
PS C:\PowerShell> .\cross.ps1 SWORD
S       D
  W   R
    O
  W   R
S       D

```
> 2 votes

# Answer
## T-SQL: 180

Taking the input from variable @i

```
DECLARE @s VARCHAR(MAX)=REPLICATE('  ',LEN(@i)),@ INT=1a:PRINT STUFF(STUFF(@s,@*2-1,1,SUBSTRING(@i,@,1)),LEN(@i)*2-(@*2)+1,1,SUBSTRING(@i,LEN(@i)-@+1,1))SET @+=1IF @<=LEN(@i)GOTO A

```

This stuffs single characters in/decrementing from the start and end into a string of spaces.

Test Result

```
DECLARE @i VARCHAR(MAX)='Super Large'
DECLARE @s VARCHAR(MAX)=REPLICATE('  ',LEN(@i)),@ INT=1a:PRINT STUFF(STUFF(@s,@*2-1,1,SUBSTRING(@i,@,1)),LEN(@i)*2-(@*2)+1,1,SUBSTRING(@i,LEN(@i)-@+1,1))SET @+=1IF @<=LEN(@i)GOTO A
S                   e
  u               g
    p           r
      e       a
        r   L

        r   L
      e       a
    p           r
  u               g
S                   e

```
> 2 votes

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

```
f=s=>[...s].map((_,i,a)=>a.map((c,j)=>j==i|j==s.length+~i?c:' ').join` `).join`
`

```

**EDIT**: -1 Thanks Joe King. I didn't see the TIO gives preformatted direct paste for CG.

Try it online!
> 2 votes

# Answer
# Stax, 13 bytes

```
â┤▼iS╙£≥»u5V╓

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
{       begin block for mapping characters of input
  ]i^)  left-pad each character to length (i+1) where i is the index
m       map using block
r       reverse the array; this produces the southwest-northeast diagonal
m       map using the rest of the program, implicitly output result
  i     iteration index
  xi@   get the i'th character of the original input, where i is the iteration
  &     assign element to array at index
  0\    join with spaces

```

Run this one
> 2 votes

# Answer
# , 88 bytes

```
n=ncol(m<-diag(u<-utf8ToInt(scan(,""))-32));diag(m[,n:1])=u;write(intToUtf8(m+32,T),1,n)

```

Try it online!
> 2 votes

# Answer
# Canvas, 6 bytes

```
＼：↶ｎ ＊

```

Try it here!

# Explanation

```
＼       Create a diagonal with the input
 ：      Duplicate the diagonal
  ↶     Rotate left
    ｎ   Simple overlap
      ＊ Insert spaces on every line

```
> 2 votes

# Answer
# Zsh, ~~90~~ 82 bytes

Kudos to @pxeger for saving 8 bytes.

```
for i ({1..$#1})(for z (${(s::)1}){((i==++j||j+i==$#1+1))||z=\
printf $z\ }
echo)

```

Attempt this Online <sub>~~90 bytes~~</sub>
> 2 votes

# Answer
## C# 208

```
static void Main()
{
string s=Console.ReadLine(),t="";
int n=s.Length;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j)t+=s[i];
else if(i==n-j-1)t+=s[n-i-1];
t+=" ";
}
t+="\n";
}
Console.WriteLine(t);
}

```
> 1 votes

# Answer
No matter how long, there's always gotta be an answer in...

# Java - ~~289~~ 234 bytes

```
public static void main(String[]a){int l=a.length-1,i=0,j;for(;i<=l;i++){for(j=0;j<=l;j++){if(j==i)System.out.print(a[i]);else if(i==l-j)System.out.print(a[j]);else System.out.print(" ");System.out.print(" ");}System.out.println();}}}

```

Ungolfed:

```
    class A {

    public static void main(String[] a) {
        int l = a.length - 1, i = 0, j;
        for (; i <= l; i++) {
            for (j=0; j <= l;j++) {
                if (j == i)
                    System.out.print(a[i]);
                else if (i == l-j)
                    System.out.print(a[j]);
                else
                    System.out.print(" ");
                System.out.print(" ");
                }
            System.out.println();
        }
    }
}

```

Output, lousily done, is:

```
P           M
  R       A
    O   R
      G
    O   R
  R       A
P           M

```

~~Added the `import java.util.Scanner` inside the code because I never remember if the imports count towards the byte count...~~ Damn, I really suck at this.
> 1 votes

# Answer
## GolfScript 46 (DEMO)

```
:w,:l,{l,{.[.l(\-]2$?)!w@[=32]=}%\;''+' '*}%n*

```
> 1 votes

# Answer
# C# (192 / 170)

```
using System;class P{static void Main(){var s=Console.ReadLine();int x,y,l=s.Length;for(x=0;x<l;x++){for(y=0;y<l;y++)Console.Write(x==y||l-x==y+1?s.Substring(x,1):" ");Console.Write("\n");};}}

```

Or, as "Main() only":

```
static void Main(){var s=Console.ReadLine();int x,y,l=s.Length;for(x=0;x<l;x++){for(y=0;y<l;y++)Console.Write(x==y||l-x==y+1?s.Substring(x,1):" ");Console.Write("\n");};}

```
> 1 votes

# Answer
# Charcoal, ~~9~~ ~~7~~ ~~17~~ 10 bytes

```
↘Ｓ⟲ＯＯＬθＵＥ¹

```

+10 bytes because I missed the requirement of space-columns.
-7 bytes thanks to *@ASCII-only*.

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

Challenges like this is why Charcoal was made.

**Explanation:**

Print the input-string in a down-right direction:

```
Print(:DownRight, InputString());
↘Ｓ

```

Rotate it 90 degree counterclockwise, and shift it up the length of the input-string amount of times with overlap:

```
RotateOverlapOverlap(Length(q));
⟲ＯＯＬθ

```

Put a space gap of size 1 between every column:

```
Extend(1);
ＵＥ¹

```
> 1 votes

# Answer
# QBasic, 91 bytes

```
INPUT w$
l=LEN(w$)
FOR i=1TO l
c$=MID$(w$,i,1)
LOCATE i+1,i*2
?c$
LOCATE l-i+2,i*2
?c$
NEXT

```

Loops through the input word and uses the `LOCATE` statement to place each letter (twice) on the screen.
> 1 votes

# Answer
# K (oK), 31 bytes

**Solution:**

```
`c$a||a:(2*#x)$(-1-2*!#x)$,:'x:

```

Try it online!

**Explanation:**

Generate the diagonal, and or with the reverse of the diagonal

```
`c$a||a:(2*#x)$(-1-2*!#x)$,:'x: / the solution
                             x: / save input as x
                          ,:'   / enlist (,:) each-both (')
                         $      / pad (negative is right-pad)
               (        )       / do this together
                      #x        / count (#) length of x
                     !          / range (!) 0..this count
                   2*           / double it
                -1-             / subtract from -1
              $                 / pad
        (    )                  / do this together
           #x                   / count (#) length of x
         2*                     / multiply by 2
      a:                        / save as a
     |                          / reverse (|) it
   a|                           / or (|) with a
`c$                             / cast to characters

```
> 1 votes

# Answer
# K4, 26 bytes

**Solution:**

```
a||a:(2*#x)$(-1-2*!#x)$$x:

```

**Explanation:**

Similar to my oK answer but a little shorter:

```
a||a:(2*#x)$(-1-2*!#x)$$x: / the solution
                        x: / save input as x
                       $   / string ($) breaks into char lists
                      $    / cast ($)
            (        )     / do this together
                   #x      / count (#) length of x
                  !        / range (!) 0..this count
                2*         / double it
             -1-           / subtract from -1
           $               / pad
     (    )                / do this together
        #x                 / count (#) length of x
      2*                   / multiply by 2
   a:                      / save as a
  |                        / reverse (|) it
a|                         / or (|) with a

```
> 1 votes

# Answer
# PHP, 81 bytes

```
for($k=strlen($s=$argn);$k;$t[2*$i]=$s[$i++],$t[2*--$k]=$s[$k],print"$t
")$t=" ";

```

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

# Answer
# Python 3, 176 bytes

```
w=input();l=len(w);d=l//2;n=' ';x=range(d)
for i in x:print(n*i*2+w[i],n*(l+2-i*4),w[-1*i-1])
print(n*(l-1)+w[d])
for i in x:print(n*(l-i*2-3)+w[-1*(d+i+2)],n*(i*4+1),w[d+i+1])

```

Try it online!

This is super stupid, any improvements that you notice are welcome
> 1 votes

# Answer
# TI-Basic, 75 bytes

```
Input Str1
length(Str1→L
For(I,1,L
"
For(J,1,L
If max(J={I,1-I+L:Then
Ans+sub(Str1,J,1)+"
Else
Ans+"
End
End
Disp Ans
End

```

There is 1 space at the end of lines 4 and 7, and there are 2 spaces at the end of line 9. Outputs a leading space at the beginning of each line.

---

Alternatively, a larger but faster method (100 bytes):

```
Input Str1
length(Str1→L
"
For(I,1,L
Ans+"  →Str2
End
For(I,1,L
min(I,1-I+L→K
2(max(L,2)-Ans
Disp sub(Str2+sub(Str1,K,1)+Str2,Ans+4,Ans)+sub(Str1,L-K+1,1
End

```

There is 1 space at the end of line 3. Outputs two leading spaces if the input has a length of 1.
> 1 votes

# Answer
# Jelly, 10 bytes

```
ṪṭaɗƤ⁶»Ṛ$G

```

Try it online!

Erik's existing answer ties with minor modifications to also use `G`: `LḶ⁶ẋ;"µ»ṚG`.

```
    Ƥ         For each prefix of the input,
Ṫ             remove the last element
 ṭ            and append it back onto
  aɗ ⁶        the remaining elements replaced with spaces.
      »       Take the maximum of each element of that and
       Ṛ$     its reverse.
         G    Grid format: join each row on spaces then join the rows on newlines.

```
> 0 votes

# Answer
# C++:

```
#include <iostream>
#include <string>

int main()
{
    char a[] = {'P','R','O','G','R','A','M'};
    int length = sizeof(a)/sizeof(a[0]);
    int l = length - 1, i, j;
    for (i=0; i <= l; i++) {
        for (j=0; j <= l;j++) {
            if (j == i)
                std::cout<<a[i];
            else if (i == l-j)
                std::cout<<a[j];
            else
                std::cout<<"s";
        }
        std::cout<<"\n";
    }
}

```
> -2 votes

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