Draw an ASCII Rectangle

20

3

Given two integers as input in an array, draw a rectangle, using the first integer as width and second as height.

Or, if your language supports it, the two integers can be given as separate inputs.

Assume the width and height will never be less than 3, and they will always be given.

Example Outputs:

[3, 3]

|-|
| |
|-|

[5, 8]

|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

[10, 3]

|--------|
|        |
|--------|

This is code-golf, so the answer with the lowest amount of bytes wins.

MCMastery

Posted 2016-09-18T13:04:35.640

Reputation: 783

Answers

6

Jolf, 6 bytes

,ajJ'|

Try it here! My box builtin finally came in handy! :D

,ajJ'|
,a       draw a box
  j      with width (input 1)
   J     and height (input 2)
    '    with options
     |    - corner
          - the rest are defaults

Conor O'Brien

Posted 2016-09-18T13:04:35.640

Reputation: 36 228

10

Jelly, 14 bytes

,þ%,ỊḄị“-|| ”Y

Try it online! or verify all test cases.

How it works

,þ%,ỊḄị“-|| ”Y  Main link. Left argument: w. Right argument: h

,þ              Pair table; yield a 2D array of all pairs [i, j] such that
                1 ≤ i ≤ w and 1 ≤ j ≤ h.
   ,            Pair; yield [w, h].
  %             Take the remainder of the element-wise division of each [i, j]
                by [w, h]. This replaces the highest coordinates with zeroes.
    Ị           Insignificant; map 0 and 1 to 1, all other coordinates to 0.
     Ḅ          Unbinary; convert each pair from base 2 to integer.
                  [0, 0] -> 0 (area)
                  [0, 1] -> 1 (top or bottom edge)
                  [1, 0] -> 2 (left or right edge)
                  [1, 1] -> 3 (vertex)
       “-|| ”   Yield that string. Indices are 1-based and modular in Jelly, so the
                indices of the characters in this string are 1, 2, 3, and 0.
      ị         At-index; replace the integers by the correspoding characters.
             Y  Join, separating by linefeeds.

Dennis

Posted 2016-09-18T13:04:35.640

Reputation: 196 637

This is a wonderful use of :) – Lynn – 2016-09-19T12:01:03.327

9

Matlab, 69 65 56 bytes

Thanks @WeeingIfFirst and @LuisMendo for some bytes=)

function z=f(a,b);z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])='|'

This is really simple in Matlab: First make a matrix of the desired size, then index the first and last row to insert the -, and do the same with the first and last column to insert |.

For example f(4,3) returns

|--|
|  |
|--|

flawr

Posted 2016-09-18T13:04:35.640

Reputation: 40 560

@WeeingIfFirst Oh, of course, thank you very much! – flawr – 2016-09-18T14:22:06.090

6 bytes shorter: z([1,b],1:a)=45;z(1:b,[1,a])=124;z=[z,''] – Stewie Griffin – 2016-09-18T14:31:10.547

Even shorter: z(b,a)=' ';z([1,b],:)=45;z(:,[1,a])=124 – Luis Mendo – 2016-09-18T14:54:21.430

@LuisMendo Thanks! We still need the string tough, otherwise the array is converted to a numerical one. – flawr – 2016-09-18T14:55:46.370

@flawr z(b,a)=' ' initiallizes as char. After that you can fill with numbers and they are automatically cast to char. z maintains its original type – Luis Mendo – 2016-09-18T14:56:50.683

That is strange, I always had the impression that this won't work =/ Anyway, thanks a lot! – flawr – 2016-09-18T14:59:02.787

8

PHP, 74 Bytes

for(;$i<$n=$argv[2];)echo str_pad("|",$argv[1]-1,"- "[$i++&&$n-$i])."|\n";

Jörg Hülsermann

Posted 2016-09-18T13:04:35.640

Reputation: 13 026

1You can still win one byte with a physical linebreak. – Titus – 2016-09-18T14:16:27.627

1-2 bytes with !$i|$n==++$i instead of !$i|$n-1==$i++ – Titus – 2016-09-18T14:22:00.703

1another byte with $i++&&$n-$i?" ":"-" – Titus – 2016-09-18T14:58:27.783

1$i++&&$n-$i?" ":"-" --> "- "[$i++&&$n-$i] (-2) – Titus – 2016-09-28T08:05:16.260

8

JavaScript (ES6), 63 bytes

f=
(w,h,g=c=>`|${c[0].repeat(w-2)}|
`)=>g`-`+g` `.repeat(h-2)+g`-`
;
<div oninput=o.textContent=f(w.value,h.value)><input id=w type=number min=3 value=3><input id=h type=number min=3 value=3><pre id=o>

Neil

Posted 2016-09-18T13:04:35.640

Reputation: 95 035

Passing a template function as a default argument? Clever! – Florrie – 2016-09-19T01:04:08.130

8

Haskell, 62 55 bytes

f[a,b]n=a:(b<$[3..n])++[a]
g i=unlines.f[f"|-"i,f"| "i]

Usage example:

*Main> putStr $ g 10 3
|--------|
|        |
|--------|

The helper function f takes a two element list [a,b] and a number n and returns a list of one a followed by n-2 bs followed by one a. We can use f thrice: to build the top/bottom line: f "|-" i, a middle line: f "| " i and from those two the whole rectangle: f [<top>,<middle>] j (note: j doesn't appear as a parameter in g i because of partial application).

Edit: @dianne saved some bytes by combining two Char arguments into one String of length 2. Thanks a lot!

nimi

Posted 2016-09-18T13:04:35.640

Reputation: 34 639

I like the # idea! – flawr – 2016-09-18T15:54:29.743

2I think you can save a few bytes by defining (a:b)#n=a:([3..n]>>b)++[a] and writing ["|-"#i,"| "#i]#j – dianne – 2016-09-18T20:00:08.097

@dianne: Very clever. Thanks a lot! – nimi – 2016-09-18T20:33:00.260

8

Python 2, 61 58 bytes

-3 bytes thanks to @flornquake (remove unnecessary parentheses; use h as counter)

def f(w,h):exec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h

Test cases are at ideone

Jonathan Allan

Posted 2016-09-18T13:04:35.640

Reputation: 67 804

('- '[1<i<h]) doesn't need the parentheses. – flornquake – 2016-09-19T12:24:01.353

Save another byte by using h as the counter: exec"print'|'+'- '[1<h<%d]*(w-2)+'|';h-=1;"%h*h – flornquake – 2016-09-19T12:35:07.313

@flornquake I had meant to check the necessity of those parentheses, but forgot. Using h as the counter is smart! Thanks. – Jonathan Allan – 2016-09-19T17:23:45.310

7

Vimscript, 93 83 75 74 73 66 64 63 bytes

Code

fu A(...)
exe "norm ".a:1."i|\ehv0lr-YpPgvr dd".a:2."p2dd"
endf

Example

:call A(3,3)

Explanation

fun A(...)    " a function with unspecified params (a:1 and a:2)
exe           " exe(cute) command - to use the parameters we must concatenate :(
norm          " run in (norm) al mode
#i|           " insert # vertical bars
\e            " return (`\<Esc>`) to normal mode
hv0l          " move left, enter visual mode, go to the beginning of the line,  move right (selects inner `|`s)
r-            " (r)eplace the visual selection by `-`s
YpP           " (Y) ank the resulting line, and paste them twice
gv            " re-select the previous visual selection
r<Space>      " replace by spaces
dd            " Cut the line
#p            " Paste # times (all inner rows) 
2dd           " Remove extra lines

Note that it is not using norm! so it might interfere with vim custom mappings!

Christian Rondeau

Posted 2016-09-18T13:04:35.640

Reputation: 301

5

05AB1E, 23 22 20 bytes

Input taken as height, then width.

F„ -N_N¹<Q~è²Í×'|.ø,

Explanation

F                          # height number of times do
    N_                     # current row == first row
          ~                # OR
      N¹<Q                 # current row == last row
 „ -       è               # use this to index into " -"
            ²Í×            # repeat this char width-2 times
               '|          # push a pipe
                 .ø        # surround the repeated string with the pipe
                   ,       # print with newline

Try it online!

Saved 2 bytes thanks to Adnan

Emigna

Posted 2016-09-18T13:04:35.640

Reputation: 50 798

Using substrings instead of the if-else statement saves two bytes: F„ -N_N¹<Q~è²Í×'|.ø,.

– Adnan – 2016-09-18T15:01:31.717

5

MATL, 19 bytes

'|-| '2:"iqWQB]E!+)

Try it online!

Explanation

The approach is similar to that used in this other answer. The code builds a numerical array of the form

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

and then its values are used as (1-based, modular) indices into the string '|-| ' to produce the desired result.

'|-| '                % Push this string
      2:"     ]       % Do this twice
         i            % Take input
          q           % Subtract 1
           W          % 2 raised to that
            Q         % Add 1
             B        % Convert to binary
               E      % Multiply by 2
                !     % Transpose
                 +    % Add with broadcast
                  )   % Index (modular, 1-based) into the string

Luis Mendo

Posted 2016-09-18T13:04:35.640

Reputation: 87 464

5

C, 73 bytes

i;f(w,h){for(i=++w*h;i--;)putchar(i%w?~-i%w%~-~-w?i/w%~-h?32:45:124:10);}

orlp

Posted 2016-09-18T13:04:35.640

Reputation: 37 067

4

Common Lisp, 104 bytes

Golfed:

(defun a(w h)(flet((f(c)(format t"|~v@{~A~:*~}|~%"(- w 2)c)))(f"-")(loop repeat(- h 2)do(f" "))(f"-")))

Ungolfed:

(defun a (w h)
  (flet ((f (c) (format t "|~v@{~A~:*~}|~%" (- w 2) c)))
    (f "-")
    (loop repeat (- h 2) do
     (f " "))
    (f "-")))

user59819

Posted 2016-09-18T13:04:35.640

Reputation:

4

Python 2, 56 bytes

w,h=input()
for c in'-%*c'%(h-1,45):print'|'+c*(w-2)+'|'

flornquake saved one byte.

Lynn

Posted 2016-09-18T13:04:35.640

Reputation: 55 648

1Nice use of string formatting! You can save a byte using %c conversion: '-%*c'%(h-1,45) – flornquake – 2016-09-19T12:47:16.543

Oh, I thought %*c wasn’t even a thing! Thank you. :) – Lynn – 2016-09-19T13:41:58.347

'-%%%dc'%~-h%45 also works for the same length. – xnor – 2016-09-19T19:33:06.140

3

Mathematica, 67 64 bytes

Thanks to lastresort and TuukkaX for reminding me that golfers should be sneaky and saving 3 bytes!

Straightforward implementation. Returns an array of strings.

Table[Which[j<2||j==#,"|",i<2||i==#2,"-",0<1," "],{i,#2},{j,#}]&

Greg Martin

Posted 2016-09-18T13:04:35.640

Reputation: 13 940

1Use 0<1 in place of True – for Monica – 2016-09-19T11:59:52.893

1I think that j==1 can be reduced to j<1, and i==1 to i<1. – Yytsi – 2016-09-19T17:34:57.280

3

Turtlèd, 40 bytes

Interpreter is slightly no longer buggèd

?;,u[*'|u]'|?@-[*:l'|l[|,l]d@ ],ur[|'-r]

Explanation

?                            - input integer into register
 ;                           - move down by the contents of register
  ,                          - write the char variable, default *
   u                         - move up
    [*   ]                   - while current cell is not *
      '|                     - write |
        u                    - move up
          '|                 - write | again
            ?                - input other integer into register
             @-              - set char variable to -
               [*             ] - while current char is not *
                 :l'|l          - move right by amount in register, move left, write |, move left again
                      [|,l]     - while current cell is not |, write char variable, move left
                           d@   - move down, set char variable to space (this means all but first iteration of loop writes space)
                               ,ur   -write char variable, move up, right
                                  [|   ] -while current char is not |
                                    '-r - write -, move right

Destructible Lemon

Posted 2016-09-18T13:04:35.640

Reputation: 5 908

3

Python 3, 104 95 bytes

( feedback from @mbomb007 : -9 bytes)

def d(x,y):return'\n'.join(('|'+('-'*(x-2)if n<1or n==~-y else' '*(x-2))+'|')for n in range(y))

(my first code golf, appreciate feedback)

user59855

Posted 2016-09-18T13:04:35.640

Reputation:

Welcome! You can remove some of the spaces, use range(y) instead of range(0,y), and if n is never negative you can use if n<1or n==~-y else – mbomb007 – 2016-09-19T13:56:18.427

See the Python tips page

– mbomb007 – 2016-09-19T13:56:34.673

@mbomb007 thanks! I'll check it out. – None – 2016-09-19T21:16:53.737

2

Ruby, 59 54 52 bytes

Oh, that's a lot simpler :)

->x,y{y.times{|i|puts"|#{(-~i%y<2??-:' ')*(x-2)}|"}}

Test run at ideone

daniero

Posted 2016-09-18T13:04:35.640

Reputation: 17 193

1You can save a couple bytes by using a literal newlines instead of \n. – Jordan – 2016-09-18T16:29:33.720

1You can save bytes by not defining i and j. Replace i's definition with x-=2. Instead of j, just use (y-2). – m-chrzan – 2016-09-19T05:25:27.767

Yeah, thanks :) – daniero – 2016-09-19T16:10:18.390

2

PHP, 82 bytes

list(,$w,$h)=$argv;for($p=$h--*$w;$p;)echo$p--%$w?$p%$w?$p/$w%$h?" ":"-":"|
":"|";

indexing a static string including the newline

list(,$w,$h)=$argv;         // import arguments
for($p=$h--*++$w;$p;)       // loop $p through all positions counting backwards
    // decrease $h and increase $w to avoid parens in ternary conditions
    echo" -|\n"[
        $p--%$w             // not (last+1 column -> 3 -> "\n")
        ?   $p%$w%($w-2)    // not (first or last row -> 2 -> "|")
            ?+!($p/$w%$h)   // 0 -> space for not (first or last row -> 1 -> "-")
            :2
        :3
    ];

Titus

Posted 2016-09-18T13:04:35.640

Reputation: 13 814

Dear downvoter: why? – Titus – 2016-09-19T13:55:03.943

1It could be because a user saw that your answer was flagged as low quality in the review queue. If you post an explanation of your code, or anything more than a one-liner, you can avoid it being automatically flagged. – mbomb007 – 2016-09-19T14:33:58.750

@mbomb: I have never seen anyone post a description for a oneliner in a non-eso language. – Titus – 2016-09-19T16:06:41.773

Or output, or a non-golfed version. It doesn't matter as long as the content is not too short. But you probably haven't been around long if you haven't seen that. Some Python one-liners can be pretty complicated. Look at some of @xnor's. – mbomb007 – 2016-09-19T18:12:16.077

2

Batch, 128 bytes

@set s=
@for /l %%i in (3,1,%1)do @call set s=-%%s%%
@echo ^|%s%^|
@for /l %%i in (3,1,%2)do @echo ^|%s:-= %^|
@echo ^|%s%^|

Takes width and height as command-line parameters.

Neil

Posted 2016-09-18T13:04:35.640

Reputation: 95 035

2

Haxe, 112 106 bytes

function R(w,h){for(l in 0...h){var s="";for(i in 0...w)s+=i<1||i==w-1?'|':l<1||l==h-1?'-':' ';trace(s);}}

Testcases

R(5, 8)
|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

R(10, 3)
|---------|
|         |
|---------|

Yytsi

Posted 2016-09-18T13:04:35.640

Reputation: 3 582

2

Java 135 bytes

public String rect(int x, int y){
String o="";
for(int i=-1;++i<y;){
o+="|";
for(int j=2;++j<x)
if(i<1||i==y-1)
o+="-";
else
o+=" ";
o+="|\n";
}
return o;
}

Golfed:

String r(int x,int y){String o="";for(int i=-1;++i<y;){o+="|";for(int j=2;++j<x;)if(i<1||i==y-1)o+="-";else o+=" ";o+="|\n";}return o;}

Roman Gräf

Posted 2016-09-18T13:04:35.640

Reputation: 2 915

I count 136 :) You can also save a char by removing the space after the first comma. – Christian Rondeau – 2016-09-18T20:31:12.060

1First of all, this code doesn't compile. Even if this would compile, it wouldn't 'draw' a rectangle as the OP currently wants. -1. – Yytsi – 2016-09-18T20:49:01.107

@TuukkaX I fixed that newline problem, but I don't see any reason why it should not compile. Of course you have to put that code in a class, but then it should work. – Roman Gräf – 2016-09-19T04:42:36.510

1"I don't see any reason why it should not compile". What's this then: o+=x "|\n"? Did you mean to put an + there? – Yytsi – 2016-09-19T04:55:11.433

Thanks. I didn't wanted to place any characters there. – Roman Gräf – 2016-09-19T05:12:47.413

2

Lua, 120 93 bytes

Saved quite a few bytes by removing stupid over complexities.

function(w,h)function g(s)return'|'..s:rep(w-2)..'|\n'end b=g'-'print(b..g' ':rep(h-2)..b)end

Ungolfed:

function(w,h)                           -- Define Anonymous Function
    function g(s)                       -- Define 'Row Creation' function. We use this twice, so it's less bytes to function it.
        return'|'..s:rep(w-2)..'|\n'    -- Sides, Surrounding the chosen filler character (' ' or '-'), followed by a newline
    end
    b=g'-'                              -- Assign the top and bottom rows to the g of '-', which gives '|---------|', or similar.
    print(b..g' ':rep(h-2)..b)          -- top, g of ' ', repeated height - 2 times, bottom. Print.
end

Try it on Repl.it

ATaco

Posted 2016-09-18T13:04:35.640

Reputation: 7 898

2

PowerShell v3+, 55 bytes

param($a,$b)1..$b|%{"|$((' ','-')[$_-in1,$b]*($a-2))|"}

Takes input $a and $b. Loops from 1 to $b. Each iteration, we construct a single string. The middle is selected from an array of two single-length strings, then string-multiplied by $a-2, while it's surrounded by pipes. The resulting strings are left on the pipeline, and output via implicit Write-Output happens on program completion, with default newline separator.

Alternatively, also at 55 bytes

param($a,$b)1..$b|%{"|$((''+' -'[$_-in1,$b])*($a-2))|"}

This one came about because I was trying to golf the array selection in the middle by using a string instead. However, since [char] times [int] isn't defined, we lose out on the savings by needing to cast as a string with parens and ''+.

Both versions require v3 or newer for the -in operator.

Examples

PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 10 3
|--------|
|        |
|--------|

PS C:\Tools\Scripts\golfing> .\draw-an-ascii-rectangle.ps1 7 6
|-----|
|     |
|     |
|     |
|     |
|-----|

AdmBorkBork

Posted 2016-09-18T13:04:35.640

Reputation: 41 581

2

Perl, 48 bytes

Includes +1 for -n

Give sizes as 2 lines on STDIN

perl -nE 'say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"'
3
8
^D

Just the code:

say"|".$_ x($`-2)."|"for"-",($")x(<>-1-/$/),"-"

Ton Hospel

Posted 2016-09-18T13:04:35.640

Reputation: 14 114

Nice one, as always. Note that you've got a backtick at the end of the line while you probably wanted to write a single quote ;-) – Dada – 2016-09-19T21:21:55.400

@Dada Fixed. Thanks. – Ton Hospel – 2016-09-19T22:00:34.717

1

bash, sed and coreutils, 95 89 bytes

You can define a function like this

f(){ n=$[$1-2];yes \ |sed $[$2*n]q|tr -d \\n|fold -w$n|sed 's/^\|$/|/g;1!{$!b};s/ /-/g';}

Or in a more readable format:

f() { 
  n=$(($1-2))

  # The next couple of lines create a rectangle of spaces
  # matching the desired size
  yes ' '          |
  head -n$(($2*n)) |
  tr -d '\n'       |
  fold -w$n        |

  # Add the pipes and dashes
  sed '
    s/^\|$/|/g   # Replace first and last character by a pipe
    1! {$!b }    # Do nothing if not on first or last line
    s/ /-/g      # Add the dashes
  '
  echo
}

You can now say f 4 3:

|--|
|  |
|--|

If you care about trailing new-line, add an echo at the end of function.

Thor

Posted 2016-09-18T13:04:35.640

Reputation: 2 526

1

Python 2, 67 bytes

def f(a,b):c="|"+"-"*(a-2)+"|\n";print c+c.replace("-"," ")*(b-2)+c

Examples

f(3,3)

|-|
| |
|-|

f(5,8)

|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|

f(10,3)

|--------|
|        |
|--------|

ElPedro

Posted 2016-09-18T13:04:35.640

Reputation: 5 301

1

MATL, 21 17 bytes

Z"45ILJhY('|'5MZ(

This is a slightly different approach than the one of the MATL-God.

Z"                   Make a matrix of spaces of the given size
  45ILJhY(           Fill first and last row with '-' (code 45)
          '|'5MZ(    Fill first and last column with '|' (using the automatic clipboard entry 5M to get ILJh back)

Thanks @LuisMendo for all the help!

Try it Online!

flawr

Posted 2016-09-18T13:04:35.640

Reputation: 40 560

1

PHP 4.1, 76 bytes

<?$R=str_repeat;echo$l="|{$R('-',$w=$W-2)}|
",$R("|{$R(' ',$w)}|
",$H-2),$l;

This assumes you have the default php.ini settings for this version, including short_open_tag and register_globals enabled.

This requires access through a web server (e.g.: Apache), passing the values over session/cookie/POST/GET variables.
The key W controls the width and the key H controls the height.
For example: http://localhost/file.php?W=3&H=5

Ismael Miguel

Posted 2016-09-18T13:04:35.640

Reputation: 6 797

@Titus You should read the link. Quoting: "As of PHP 4.2.0, this directive defaults to off". – Ismael Miguel – 2016-09-28T08:56:36.583

Ouch sorry I take everything back. You have the version in your title. I should read more carefully. – Titus – 2016-09-28T09:16:18.660

@Titus That's alright, don't worry. Sorry for being harsh on you. – Ismael Miguel – 2016-09-28T09:50:51.727

Nevermind; that´s the price I pay for being pedantic. :D – Titus – 2016-09-28T10:59:28.403

@Titus Don't worry about it. Just so you know, around half of my answers are written in PHP 4.1. It saves tons of bytes with input – Ismael Miguel – 2016-09-28T14:22:10.303

1

Python 3, 74 chars

p="|"
def r(w,h):m=w-2;b=p+"-"*m+p;return b+"\n"+(p+m*" "+p+"\n")*(h-2)+b

vpzomtrrfrt

Posted 2016-09-18T13:04:35.640

Reputation: 201

1

Python (70 bytes)

def r(w,h): print '\n'.join(['|'+('-' if i%(h-1)==0 else ' ')*(w-2)+'|' for i in range(h)])

Edit: lambda function for a few less bytes (thanks @DJMcMayhem)

r=lambda w,h:'\n'.join(['|'+('-'if i%(h-1)==0 else' ')*(w-2)+'|'for i in range(h)])

Edit#2: if notation is greedy

r=lambda w,h:'\n'.join(['|'+(0<i<h-1 and' 'or'-')*(w-2)+'|'for i in range(h)])

Edit#3: -8 bytes with list trick

r=lambda w,h:'\n'.join(['|'+'- '[0<i<h-1]*(w-2)+'|'for i in range(h)])

Fabien Bouleau

Posted 2016-09-18T13:04:35.640

Reputation: 121

Hello, welcome to the site! Some tips, 1) you have some unnecessary whitespace that you could remove. 2) A lambda function is shorter since you don't need to call print (you can just return instead) – James – 2016-09-19T05:19:46.387

I count 83 bytes – TuxCrafting – 2016-09-19T08:54:15.453

1

C#, 102 93 bytes

Saved 9 bytes thanks to milk - completely forgot to concatenate strings. The compare trick is pretty cool too.

w=>h=>{var s="";for(int i=0;i<h;)s+="|"+new String(1>i++%(h-1)?'-':' ',w-2)+"|\n";return s;};

Try it online!

Full source, including test cases:

using System;

namespace DrawASCIIRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,string>> d= w=>h=>{var s="";for(int i=0;i<h;)s+="|"+new String(1>i++%(h-1)?'-':' ',w-2)+"|\n";return s;};
            Console.WriteLine(d(3)(3));
            Console.WriteLine(d(5)(8));
            Console.WriteLine(d(10)(3));
        }
    }
}

adrianmp

Posted 2016-09-18T13:04:35.640

Reputation: 1 592

1Using 1>i++%(h-1) instead of i++<1||i>h-1 will save 1 byte. You can also put all the string concats into a single statement so the for is a one liner and doesn't need braces, saving another 8 bytes: s+="|"+new string(1>i++%(h-1)?'-':' ',w-2)+"|\n" – milk – 2016-09-19T19:44:30.897

1

Swift(2.2) 190 bytes

let v = {(c:String,n:Int) -> String in var s = "";for _ in 1...n {s += c};return s;};_ = {var s = "|"+v("-",$0-2)+"|\n" + v("|"+v(" ",$0-2)+"|\n",$1-2) + "|"+v("-",$0-2)+"|";print(s);}(10,5)

I think Swift 3 could golf this a lot more but I don't feel like downloading Swift 3.

Danwakeem

Posted 2016-09-18T13:04:35.640

Reputation: 141

1

C 87 bytes

f(b,a,c,k){for(;c<a*b;++c)printf("%s",(k=c%b)==b-1?"|":!k?"\n|":c<b||c>a*b-b?"-":" ");}

this is the main for some test...

main() 
{f(3,3,0,0); f(5,8,0,0); f(10,3,0,0);
 return 0;
}


|-|
| |
|-|
|---|
|   |
|   |
|   |
|   |
|   |
|   |
|---|
|--------|
|        |
|--------|

RosLuP

Posted 2016-09-18T13:04:35.640

Reputation: 3 036

1

F#, 131 bytes

let d x y=
 let q = String.replicate (x-2)
 [for r in [1..y] do printfn "%s%s%s" "|" (if r=y||r=1 then(q "-")else(q " ")) "|"]

user59855

Posted 2016-09-18T13:04:35.640

Reputation:

0

APL (Dyalog Unicode), 25 bytes

'|','|',⍨'-'⍪'-'⍪⍨''⍴⍨-∘2

Try it online!

-∘2 subtract two

''⍴⍨ use that as height and width to reshape an empty string (padding with spaces)

'-'⍪⍨ put dashes below

'-'⍪ put dashes on top

'|',⍨ put stiles on the right

'|', put stiles on the left

Adám

Posted 2016-09-18T13:04:35.640

Reputation: 37 779

0

Python, 105 bytes

[a,b]=input().split()
def d(e):print("|"+e*(int(a)-2)+"|")
d("-")
for f in range(2,int(b)):d(" ")
d("-")

Try it online

Евгений Новиков

Posted 2016-09-18T13:04:35.640

Reputation: 987

0

tcl, 99

puts [set M |[string repe - [incr w -2]]|]
incr w
time {puts |[format %$w\s |]} [incr h -2]
puts $M

demo

sergiol

Posted 2016-09-18T13:04:35.640

Reputation: 3 055

0

Pyth, 22 bytes

VJE.[Q*-Q2?}N,0tJ\-d\|

A program that takes input of the width, followed by the height, on STDIN and prints the result.

Try it online

How it works

VJE.[Q*-Q2?}N,0tJ\-d\|  Program. Inputs: Q, E
 JE                     Assign E to J
V                       For N in [0, 1, 2, ..., J-1]:
             ,0tJ        Yield [0, J-1]
           }N            N is in that list
          ?              If that:
                 \-       Yield "-"
                         Else:
                   d      Yield " "
      *-Q2               Repeat that Q-2 times
   .[Q              \|   Evenly pad that with "|" on both sides to length Q
                         Implicitly print

TheBikingViking

Posted 2016-09-18T13:04:35.640

Reputation: 3 674

0

Actually, 35 bytes

¬'|@α(¬;)' *╗`╜o'|o`Mi('-*"|%s|"%;)

Try it online!

Explanation:

¬'|@α(¬;)' *╗`╜o'|o`Mi('-*"|%s|"%;)
¬                                    height - 2
 '|@α                                ["|" for _ in range(height-2)]
     (¬;)                            width - 2, duplicate, move to bottom of stack
         ' *                         " "*(width-2)
            ╗                        save to register 0
             `╜o'|o`M                for each "|" in list of "|"s:
              ╜o                       append (width-2) spaces
                '|o                    append a second "|"
                     i               flatten list
                      (              bring copy of (width-2) back to top
                       '-*           "-"*(width-2)
                          "|%s|"%    surround with "|"s
                                 ;)  dupe, move copy to bottom of stack
                                     (implicitly print stack contents, one element per line)

Mego

Posted 2016-09-18T13:04:35.640

Reputation: 32 998

0

Python 3, 68 bytes

def f(a,b):
 c='|'+'-'*(a-2)+'|\n';print(c+c.replace(*'- ')*(b-2)+c)

0WJYxW9FMN

Posted 2016-09-18T13:04:35.640

Reputation: 2 663

0

Racket 108 bytes

(λ(w h)(for((j h))(display #\|)(for((i(- w 2)))(display(if(or(= j 0)(= j(- h 1)))#\-" ")))(displayln #\|)))

Ungolfed:

(define f
  (λ (w h)
    (for ((j h)) 
      (display #\|)
      (for ((i (- w 2)))
        (display (if (or
                      (= j 0)
                      (= j (- h 1)))
                     #\-
                     " ")))
      (displayln #\|))))

Testing:

(f 5 3)

Output:

|---|
|   |
|---|

rnso

Posted 2016-09-18T13:04:35.640

Reputation: 1 635