16
\$\begingroup\$

Specification

Write the shortest possible code in any language that does the following:

It takes two arguments, x and y, and generates x + y lines of text.

The first x lines should consist of y nested pairs of square brackets separated by a space surrounding a single digit, which cycles from 1 to 9, then 0 to 9, etc. from line to line.
The following y lines have the letter X in place of the digit and successively replace the innermost remaining pair of square brackets with spaces. The last line only contains the X, surrounded by spaces.

All output is ASCII.
You may choose to output a final newline (following a space), but you may also choose not to.
You may use either CR, CRLF, or LF as newline sequences.
The last line must contain an appropriate number of spaces following the central X.

The only valid inputs are positive integers. Zero is not a valid input.
You’re free to impose a reasonable, technically-driven limit on input size, even if the problem is solvable without. For instance, if there’s some function available for 16 bit integers that isn’t for bigints for some reason, and using it makes your program shorter, that’s a valid reason for a input size constraint.
Your code may reject invalid input or simply behave in any way on invalid input.

Examples

Example with x = 12, y = 8:

[ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 2 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 3 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 4 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 5 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 6 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 7 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 8 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 9 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 0 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ 2 ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [   X   ] ] ] ] ] ] ]
[ [ [ [ [ [     X     ] ] ] ] ] ]
[ [ [ [ [       X       ] ] ] ] ]
[ [ [ [         X         ] ] ] ]
[ [ [           X           ] ] ]
[ [             X             ] ]
[               X               ]
                X                

Example with x = 5, y = 1

[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]
[ 5 ]
  X  

Example with x = 1, y = 10:

[ [ [ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ [   X   ] ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [     X     ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [       X       ] ] ] ] ] ] ]
[ [ [ [ [ [         X         ] ] ] ] ] ]
[ [ [ [ [           X           ] ] ] ] ]
[ [ [ [             X             ] ] ] ]
[ [ [               X               ] ] ]
[ [                 X                 ] ]
[                   X                   ]
                    X                    
\$\endgroup\$
8
  • 5
    \$\begingroup\$ I would advise against restrictions like forcing specific variable names (especially since some languages might not have that concept or the ability to name parameters freely) - we have a reasonable site definition of what's valid input/output, and for "take two numbers" and "output a multi-line string", that's pretty well-defined and you won't need to worry about people exploiting I/O loopholes :) \$\endgroup\$
    – hyper-neutrino
    May 29, 2021 at 15:21
  • \$\begingroup\$ OK, I’ll remove the comments on arguments \$\endgroup\$ May 29, 2021 at 15:22
  • \$\begingroup\$ For future reference, we strongly recommend using the Sandbox to get feedback on challenge ideas before posting them to main. \$\endgroup\$
    – pxeger
    May 29, 2021 at 15:28
  • 1
    \$\begingroup\$ The comment about arguments was something I added after posting it. \$\endgroup\$ May 29, 2021 at 15:30
  • 1
    \$\begingroup\$ OK, thanks for the info on the appropriate timeframe. I’ll keep this in mind in the future. \$\endgroup\$ May 30, 2021 at 6:40

14 Answers 14

7
\$\begingroup\$

05AB1E, 22 bytes

Takes the inputs in reversed order.

L<+'[δиR²LT%¹'Xи«ªζ».º

Try it online!

This works by creating half of the columns, transposing to rows and adding the other half with a mirror.

L<+                     # push range [x .. x+y-1]
   '[δи                 # for each number in the range, create a list of that many '['
       R                # reverse the list of lists
        ²L              # push range [1 .. x]
          T%            # each number %10
            ¹'Xи        # a list of y 'X'
                «       # append this to the modulo range
                 ª      # append to the list of columns
                  ζ     # transpose to list of rows, filling with space
                   »    # join each row by spaces, rows by newlines
                    .º  # self-intersected mirror
\$\endgroup\$
7
\$\begingroup\$

Jelly,  33  27 bytes

-1 thanks to caird coinheringaahing (use of ))

Ø[j
%⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G

A full program that accepts \$x\$ and \$y\$ and prints the result.

Try it online!

How?

Ø[j - Link 1, wrap in []: a
Ø[  - list of characters = ['[', ']']
  j - join (with a) = ['[', a, ']']

%⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G - Main Link: x, y
    )                   - for each (v in [1..x]):
 ⁵                      -   ten
%                       -   (v) modulo (10)
   ¡                    -   repeat (y times):
  Ç                     -     call last Link (1) as a monad
                     ¤  - nilad followed by link(s) as a nilad:
      ”X                -   character = 'X'
         ¡              -   repeat (y times):
        Ç               -     call last Link (1) as a monad
                   Ƭ    -   loop until no change, collecting up inputs:
                  ¦     -     sparse application...
                 $      -     ...to (1-based) indices: last two links as a monad:
           i”]          -       first index of character ']' (call this i)
                $       -       last two links as a monad:
               C        -         complement -> 1-i
              ;         -         concatenate -> [i, 1-i]
          ⁶             -     ...of: space character (replaces innermost [] with spaces)
                    Ḋ   -   dequeue (remove the leading one with all []s present)
     ;                  - concatenate
                      G - format as a grid
                        - implicit print
\$\endgroup\$
3
4
\$\begingroup\$

JavaScript (ES6), 99 bytes

Building line by line.

Expects (x)(y).

(x,n=0)=>g=y=>y?'[ '[R='repeat'](y-=++n>x)+(n>x?(p='  '[R](n-x))+'X'+p:n%10)+' ]'[R](y)+`
`+g(y):''

Try it online!


JavaScript (ES6), 115 bytes

Building character by character.

Expects (x)(y).

x=>y=>(k=x-1,g=n=>k-~y?` 
][X${(x-k)%10}`[--n?(q=n-y+~y)?n&(k>0|q*q>k*k*4)&&2^q>0:5^k<0:k---k]+g(n||w):'')(w=y*4+2)

Try it online!

\$\endgroup\$
5
  • 1
    \$\begingroup\$ That's the first time I've ever seen --- in an actual answer. Correct me if I'm wrong, but does it return 0 while decrementing k? \$\endgroup\$
    – emanresu A
    May 29, 2021 at 21:38
  • \$\begingroup\$ @Ausername It's equivalent to k-- - k, which decrements k and returns 1. \$\endgroup\$
    – Arnauld
    May 29, 2021 at 22:08
  • \$\begingroup\$ @Ausername either that or k- --k. Not sure about operator precedence, but that also returns 1 \$\endgroup\$
    – user100690
    May 30, 2021 at 8:20
  • \$\begingroup\$ @ophact I can't think of a way to prove it off the top of my head with k---k but here is a way to make sure that k+++k is k++ + k and not k + ++k. \$\endgroup\$
    – Arnauld
    May 30, 2021 at 9:11
  • \$\begingroup\$ Typically, lexical phase is greedy, which means it will always match as long as it can. A well known tricky is 3.toString() is invalid (and you have to write 3..toString() instaed) due to the fact that lexical parser greedy take 3. as a single token. There are some (rare) exceptions, for example C++ specification fixed the parsing of vector<vector<int>> in C++11. \$\endgroup\$
    – tsh
    May 31, 2021 at 7:17
4
\$\begingroup\$

Python 2, 87 bytes

-1 byte thanks to @Lynn, with a min trick

The main difference from the previous answer is a clever use of min. When i <= x, v+'X'+v equals X, which is lexicographically larger than any digit [0-9]. When i > x, v starts with leading spaces, which causes i%10 to be chosen instead.

x,y=input()
i=0
while y:i+=1;y-=i>x;v=(i-x)*'  ';print'[ '*y+min(`i%10`,v+'X'+v)+' ]'*y

Try it online!

Python 2, 88 bytes

Input is taken from STDIN.

x,y=input()
i=0
while y:i+=1;y-=i>x;v=-x%i*'  ';print'[ '*y+[`i%10`,v+'X'+v][i>x]+' ]'*y

I finally get an oppurtunity to show off this nice trick: -x%i*' '. It turns out that -x%i is equivalent to i-x, when i>=x. On its own, it is one byte longer, but it allows us to drop the parentheses in the string multiplication.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ It looks like while y:i+=1;y-=i>x;v=(i-x)*' ';print'[ '*y+min(`i%10`,v+'X'+v)+' ]'*y saves a byte; I'm also eyeing while y:i+=1;y-=i>x;print'[ '*y+min(`i%10`,'X'.center(i-x<<2|1))+' ]'*y but it's the same length. \$\endgroup\$
    – Lynn
    Jun 27, 2021 at 1:20
  • \$\begingroup\$ @Lynn Thanks for the improvement. The min is nice... \$\endgroup\$ Jun 27, 2021 at 1:59
3
\$\begingroup\$

JavaScript (ES6), 92 bytes

x=>h=(y,N=x+y)=>N?h(y,N-1)+(g=_=>y--?x+y<N?`  ${g()}  `:`[ ${g()} ]`:N>x?'X':N%10)(y)+`
`:''

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ On the testcase with x=5, y=1 there are no brackets on either side \$\endgroup\$
    – user100690
    May 31, 2021 at 9:40
  • 1
    \$\begingroup\$ @Arnauld should get fixed now. \$\endgroup\$
    – tsh
    May 31, 2021 at 9:46
2
\$\begingroup\$

Vyxal, 56 bytes

(‛[ ¹*n₀%‛ ]¹*++,)¹‹(‛  n›*‛[ ¹nε‹*p\X+‛  n›*+‛ ]¹nε‹*+,

Try it Online!

Its bad I know.

\$\endgroup\$
2
\$\begingroup\$

J, 73 bytes

+:@[|."1((,'X'$~,&1)~10":@|1+i.),.~' []'{~[:(,.~2*|."1)@|.@,.0,~"0+>/&i.[

Try it online!

\$\endgroup\$
2
\$\begingroup\$

R, 105 115 bytes

function(x,y,`|`=strrep,l="[ ",r=" ]",p=paste0)cat(p(l|y,1:x%%10,r|y),p(l|y:1-1,s<-"  "|1:y,"X",s,r|y:1-1),sep="
")

Try it online!

Returns a vector of lines.
Prints the result.

function(x,y,           # function taking x and y as input
`|`=strrep,             # assign strrep to operator with low precedence
l="[ ",r=" ]",p=paste0) # defining variables in function's arguments saves bytes
cat(                    # concatenate the two parts
p(                      # paste element-wise (recycling if necessary)
 l|y,                   # left bracket with space y times
  1:x%%10,              # row index mod 10
   r|y),                # and right bracket preceded by space y times
p(                      # the second part
 l|y:1-1,               # `l` declining number of times
  s<-"  "|1:y,          # required number of spaces (save as s for later)
   "X",                 # literal X
    s,                  # we've seen that before
     r|y:1-1),          # right brackets
sep="\n")               # join elements by newline
\$\endgroup\$
2
  • \$\begingroup\$ This is great, but unfortunately, as per comment to your question, the OP stated that you can either print or output a single string (containing the new-lines)... \$\endgroup\$
    – digEmAll
    May 31, 2021 at 8:32
  • 1
    \$\begingroup\$ @digEmAll - thanks. I missed the reply from OP. Correction in progress! \$\endgroup\$
    – pajonk
    May 31, 2021 at 9:29
1
\$\begingroup\$

Canvas, 22 bytes

[×*ω[]k⇵∔⁷{A%]╶X*∔+ *│

Try it here!

Takes input as y on the first line and x on the second line.

\$\endgroup\$
1
\$\begingroup\$

Excel, 112 bytes

=LET(z,SEQUENCE(A1+B1),s,IF(z>A1,z-A1,0),b,REPT(" ",s),REPT("[",B1-s)&b&IF(z>A1,"X",MOD(z,10))&b&REPT("]",B1-s))

Link to Spreadsheet

Explanation

  • =LET(z,SEQUENCE(A1+B1), z = vertical array of numbers from 1 to x+y
  • s,IF(z>A1,z-A1,0), if z > x then s = z - x else z = 0
  • b,REPT(" ",s), string of spaces for each row
  • REPT("[",B1-s) string of "[" for each row
  • &b&IF(z>A1,"X",MOD(z,10))&b spaces and middle for each row
  • &REPT("]",B1-s)) string of "]" for each row
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 166 164 128 bytes

x=>y=>[...Array(x+y)].map((e,i)=>'[ '[r='repeat'](d=i<x?y:y-i+x-1)+(m='  '[r](i>=x&&y-d))+(i<x?++i%10:'X')+m+' ]'[r](d)).join`
`

Try it online!

Unlike my previous submission which replaced a string of spaces, this simply builds each line.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 33 30 28 bytes

NθNη↷²⭆θ﹪⊕ιχ×Xη⸿Eη×[⁺θι‖BUE¹

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

NθNη

Input x and y.

↷²

Change the default output direction to downwards.

⭆θ﹪⊕ιχ

Print the central column of digits.

×Xη

Print the Xs.

⸿Eη×[⁺θι

Move to the previous column and print the right trapezium of [s to the left.

‖B

Mirror the canvas.

UE¹

Spread out the columns.

\$\endgroup\$
1
\$\begingroup\$

Haskell, 122 bytes

x%y=mapM putStrLn[(r>>"[ ")++min[last$show i](v++"X"++v)++(r>>" ]")|i<-[1..x+y],r<-[[1+max i x..x+y]],v<-[[1..i-x]>>"  "]]

Try it online!

The most noteworthy trick here is using min to decide between digits and X.

Namely, "X" > "9" > " X " > " X " > …

so that if we only make v have the right amount of spaces, then min(digit, v++"X"++v) will choose the appropriate string.

\$\endgroup\$
0
\$\begingroup\$

Python 2, 147 bytes

lambda x,y,N="  ":"\n".join(["[ "*y+`z%10`+y*" ]"for z in range(1,x+1)]+["[ "*z+N*(y-z)+"X"+N*(y-z)+" "+z*"] "for z in range(y,0,-1)])+"\n"+N*y+"X"

Try it online!

-8 bytes thanks to @ophact

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 149 \$\endgroup\$
    – user100690
    May 29, 2021 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.