23

# 输入

• `s` -正方形
• `t` - 三角形

# 输出实例

``````Input: s3+
Output:
***
***
***

Input: t5+

Output:
*
***
*****

Input: t3-
Output:
***
*
``````

# 特别说明

3

Ashwin Gupta

9

## Pyth，40 36 34 32字节

-1字节@isaacg

``````JstPz_W}\+zjl#m.[J*\*-J*}\tzyd;J
``````

lambda内的分号现在是lambda变量的全局值，此功能节省一个字节。

``````                         Implicit: z = input
JstPz                    J = size.
_W }\+z                  Reverse if "+" in z
j l# m                J  Join the nonempty lines in map lambda d:... over range(J)
.[J            ;   Pad the following with spaces (;) to length J
*\*               "*", this many times:
-J*}\tzyd        J if "t" not  in z,
otherwise the correct number for a triangle.
``````

1

ETHproductions'1

isaacg

6

# Pyth，38个字节

``````JsPtzj?}\szm*\*JJ_W}\-zm.[J*\*hyd;/hJ2
``````

5

# 的JavaScript（ES6），142 146 147

``````i=>([,a,b]=i.match`.(.+)(.)`,Array(l=i<'t'?+a:-~a/2).fill('*'.repeat(a)).map((r,i)=>l-a?(' '.repeat(i=b<'-'?--l:i)+r).slice(0,a-i):r).join`
`)``````

``````F=i=>(
[,a,b]=i.match`.(.+)(.)`,
Array(l=i<'t'?+a:-~a/2).fill('*'.repeat(a))
.map((r,i)=>l-a?(' '.repeat(i=b<'-'?--l:i)+r).slice(0,a-i):r)
.join`\n`
)

function test() { O.textContent=F(I.value) }

test()``````
``````Input: <input id=I oninput="test()" value="t11-"/>
<pre id=O></pre>``````

`\d`-> `.`，因为保证前后只有一个非数字
ETHproductions

@ETHproductions对，谢谢
edc65 '16

ETHproductions 2016年

`i.match(/.(.+)(.)/)`->`i.match`.(.+)(.)``
81655

@ user81655很好的提示，谢谢
edc65 '16

5

## Python 2，106字节

``````s=raw_input()
n=int(s[1:-1])
for i in[range(1,n+1,2),n*[n]][s<'t'][::2*('+'in s)-1]:print('*'*i).center(n)``````

4

# Japt，62 60 55 52 51字节

``````V=Us1 n;U<'t?Vo ç*pV):0oV2 £S²pY iY'*pV-X})·z2*!Uf-
``````

``````      // Implicit: U = input string, S = space
V=    // Set variable V to
Us1   // everything after the first char of U,
n;    // converted to a number. This turns e.g. "12+" into 12.
``````

``````U<'t?      // If U comes before "t" lexicographically (here, if the first char is "s"),
Vo         //  make a list of V items,
ç*pV)      //  and set each item to V asterisks.
:0oV2      // Otherwise, create the range [0, V) with steps of 2 (e.g. 7 -> [0,2,4,6]),
£       }) //  and map each item X and index Y to:
S²pY       //   Repeat 2 spaces Y times. This creates a string of Y*2 spaces.
iY'*pV-X   //   At position Y in this string (right in the middle), insert V-X asterisks.
·          // Join with newlines.
``````

``````!Uf-    // Take the logical not of U.match("-").
// If U contains "-", this returns false; otherwise, returns true.
2*      // Multiply by two. This converts true to 2, false to 0.
z       // Rotate the list 90° that many times.
// Altogether, this turns the shape by 180° if necessary.
``````

4

# Python 2中，235 193 167 157字节

``````d=raw_input()
x=int(d[1:-1])
o="\n".join("*"*x for i in range(x))if d<"t"else"\n".join(("*"*i).center(x)for i in range(x,0,-2))
print o[::-1]if"+"in d else o
``````

``````d=raw_input()
x=int(d[1:-1])
if "s" in d:
for y in range(x):
o+="*"*x+"\n"
o=o[:-1]
else:
b=0
while x+1:
o+=" "*b+"*"*x+" "*b+"\n"
x-=2
b+=1
o=o[:-1]
if d[-1]=="+":
o=o[::-1]
print o
``````

ბიმო

1

Doorknob

2016年

2
@DenkerAffe在窗口中计数时，每个换行符减去1个字节-换行符在Windows中为2个字节，而在其他环境中为1个字节
edc65 2016年

1

Sherlock9

3

# JavaScript，220个字节。

``````q=s=>+s.slice(1,s.length-1);f=s=>s[0]=="s"?("*".repeat(q(s))+"\n").repeat(q(s)):Array.apply(0,Array(-~(q(s)/2))).map((_,n)=>(s[s.length-1]=="-"?~~(q(s)/2)-n:n)).map(n=>(" ".repeat(q(s)/2-n)+"*".repeat(n*2+1))).join("\n")
``````

``````q=s=>+s.slice(1,s.length-1);                                                                                                                                                                                                 Define a function, q, that takes returns the argument, without the first and last character, casted into an integer.
f=s=>                                                                                                                                                                                            Define a function, f, that takes one argument, s. (This is the main function)
s[0]=="s"?                                                                                                                                                                                  If the first character of s is "s" then...
("*".repeat(q(s))     )                                                                                                                                                           Repeat the "*" character q(s) times.
(                +"\n")                                                                                                                                                           Append a newline to that
.repeat(q(s))                                                                                                                                              Repeat that q(s) times.
:                                                                                                                                             Else... (the first character of s isn't "s")
Array.apply(0,Array(          ))                                                                                                             Create an array of length...
Array.apply(0,Array(-~(q(s)/2)))                                                                                                             floor(q(s)/2)+1
.map((_,n)=>                                   )                                                             Map each element, _ with index n to...
.map((_,n)=>(s[s.length-1]=="-"?              ))                                                             If the last element of s is "-" then...
.map((_,n)=>(s[s.length-1]=="-"?~~(q(s)/2)-n  ))                                                             floor(q(s)/2)-n
.map((_,n)=>(s[s.length-1]=="-"?            : ))                                                             Else...
.map((_,n)=>(s[s.length-1]=="-"?             n))                                                             Just n
.map(n=>                                        )            Map each element into...
.map(n=>(" ".repeat(q(s)/2-n)                   )            Repeat " ", q(s)/2-n times.
.map(n=>(                   )+"*".repeat(n*2+1)))            Append "*", repeated 2n+1 times.
.map(n=>(" ".repeat(        )+"*".repeat(n*2+1))).join("\n") Join with newlines
``````

isanae

3

1

isanae

1
@Loovjo我认为他的意思是解释的第一行。对于JavaScript答案，我通常缩进解释而不是采用这种样式，因此您无需滚动即可查看其中的一半。
user81655'1

@ user81655是的，我的意思是在解释中。现在我明白了困惑！
isanae '16

3

# Python 2中，157个 132字节

``````def f(s):
S=int(s[1:-1])
for n in([range(1,S+2,2),range(S,0,-2)]['-'in s],[S]*S)['s'in s]:
print "{:^{S}}".format('*'*n,S=S)
``````

Denker

1

Denker

@DenkerAffe，无论出于何种原因，我都记得逆变器是可选的，因此无法正常工作，但我想我只是弥补了这一点
wnnmaw

2

## 视网膜，102 85字节

``````\d+
\$0\$*:¶
^((\w)+):(:+)
\$1\$2\$3\$2¶\$0
m`s\$|:t

)`(.+)¶-(\D*)
-\$2¶\$1
m`^.

G`.
T`ts:` *
``````

Notepad ++表示您的代码为89个字节，而不是85个字节。我使用了ISO-8859-1编码，然后继续使用Edit> EOL Convertion> UNIX / Linux Format，`\n`而不是使用`\r\n`。内容的Base64 ：（`XGQrCiQwJCo6wrYKXigoXHcpKyk6KDorKQokMSQyJDMkMsK2JDAKbWBzJHw6dAoKKWAoLispwrYtKFxEKikKLSQywrYkMQptYF4uCgpHYC4KVGB0czpgICo=`从Notepad ++直接复制）。奇怪的是，任何在线解决方案都给我85个字节...哼...
Ismael Miguel

@IsmaelMiguel Notepad ++如何计算`¶`。在ISO 8859-1中，它们绝对是一个字节（值182）。
Martin Ender

2

## 严重的是54个字节

``````,#i's=`≈;'**@½≈";#dXdXεj' +"£n`@`≈;'**n`@Iƒ('-=WXa0WXü
``````

``````,#i                                                    Take input, push chars separately
's=                                   Iƒ            IF the first char is "s":
`      `@                run the quoted function
≈;'**n                  make list of n strings of n *'s
`                       `@                       ELSE run the quoted function:
≈;                                                make two copies of int n
'**                                             use one to make string of n *'s
@½≈                                          cut the other in half (e.g. 5->2)
"           "£n                           run n/2 times the quoted function:
;#                                        copy the string as list of chars
dXdX                                    discard the last 2 *'s
εj                                  join back into string
' +                               prepend a space
('-=WX 0WX  IF the third character is "-":
a       invert the stack
ü pop and print the entire stack
``````

@Mego：看到了`#dXdXεj`吗？STRING SLICING ？？？

2

## ES6，178个172 159字节

``````s=>(p=s.match(/d+|./g),u=n=+p[1],m=n+1>>1,t=' '.repeat(n)+'*'.repeat(n),v=s<'t'?0:p[2]<'-'?(u=m,1):-1,[...Array(s<'t'?n:m)].map(_=>t.substr(u,u,u+=v)).join`
`)
``````

``````     *****
``````

``````     |*****| (5)
| ***| (4)
|  *| (3)
``````

@ThomasKwa Huh，在我更正了`t`处理代码之后，结果证明了这一点，`w`并且`u`变得等效，并且为我节省了足够的字节，可以将我带回178！

`[,b,c]=s.match`及更高版本`s<'t'`...应该保存一些字节（仅

@ edc65只是不保存比赛`s`允许我使用`s<'t'`哪个保存了6个字节，谢谢。

2

# MATL，48个字节

``````' *'jt4Y2m)U1\$l't'Gm?2MQ2/:1L3\$)R!P!R'+'Gm?P]]Q)
``````

### 说明

``````' *'        % push string. Will be indexed into to obtain final result
j           % input string
t           % duplicate
4Y2         % predefined literal string '0123456789'
m           % logical index of digits in input string
)           % index into input string to obtain substring with digits
U           % convert to number
1\$l         % generate square of ones with that size
't'         % push character 't'
G           % push input string
m           % true if input string contains 't'
?           % if so...
2M        % push argument of call to function `l`, i.e. square size
Q2/       % add 1 and divide by 2. Call result T
:         % generate vector [1, 2, ... T]
1L        % predefined literal representing Matlab's `:` index
3\$)       % two dimensional index. Transforms square into rectangle
R         % remove (set to zero) lower-left corner
!P!       % flip horizontally
R         % remove lower-left corner. This gives inverted triangle
'+'       % push character '+'
G         % push input
m         % true if input contains '+'
?         % if so...
P       % flip vertically
]         % end if
]           % end if
Q           % add 1. This gives array of values 1 and 2
)           % index string ' *' with this array to produce char array
% implicitly display that char array
``````

1

# C，259字节

``````#define x(y);)putchar(y)
#define m(n)for(n=0;n++<
#define T {m(q)i x(32);m(q)s-i*2 x(42);puts("");}
main(q,v,i,s)char**v;{s=atoi(v[1]+1);if(*v[1]=='s')m(i)s*s x(42)&&!(i%s)&&puts("");else if(strchr(v[1],'+'))for(i=s/2+1;i-->0;)T else for(i=-1;i++<s/2+1;)T}
``````

### 不打高尔夫球

``````main(q,v,i,size)char**v; // neat way of declaring variables
{
size=atoi(v[1]+1);
if(*v[1]=='s')
{
for(i=0;i++<size*size;)
{
putchar(42); // returns 42 (true)
if(!(i%size))
puts("");
}
}
else if(strchr(v[1],'+')) // if finds plus sign
{
for(i=size/2+1;i-->0;) // iterate the height of the triangle
{
for(q=0;q++<i;)putchar(32); // conveniently i is the number os spaces before each line
for(q=0;q++<size-i*2;) putchar(42);
puts("");
}
}
else for(i=-1;i++<size/2+1;) // does the same as above but inverted order
{
for(q=0;q++<i;)putchar(32);
for(q=0;q++<size-i*2;)putchar(42);
puts("");
}
}
``````

1

# 露比（99）

``````->s{n=s[1,2].to_i
n.times{|i|d=(s.ord-115)*(s[-1]<=>?,)*(n-1-i*2)
d<1&&puts((?**(n+d)).center(n))}}
``````

``````f=->s{                         #take a string as an argument
n=s[1,2].to_i                #take 2 characters starting at index 1 and convert to a number for the size
n.times{|i|                  #iterate through n rows
d=                         #calculate how many stars "MORE THAN" n we need on a row
(s.ord-115)*               #ascii code for 1st character of string - 115 : s-->0, t-->1
(s[-1]<=>?,)*              #compare last character of input with comma character - --> +1 + --> -1
(n-1-i*2)                  #row number * 2: 0 at centre, positive above it, negative below it
d<1&&                      #only output if d is nonpositive (i.e we need less than n or exactly n stars)
puts((?**(n+d)).center(n)) #print n+d stars, centred in a field of n characters padded by whitespace
}
}

f[gets.chomp]
``````

1

# Jolf，37个字节，无竞争

``````onFiΒ€ioSgiγ?='sn―sΒ'*―TΒ1'*?='-SZiγγ
``````

## 第1部分：解析字符串

``````onFiΒ€ioSgi
on          set n to
Fi         the first entity of i (the shape identifier)
Β       set Β (beta) to
€i      the "inside" of i (in this case, the size) as a number
oS   set S to
gi  the last entity of i (the inverter)
``````

## 第2部分：获得结果

``````γ?='sn―sΒ'*―TΒ1'*
γ                 set γ (gamma) to the result of the following expression
?='sn             if n is the character s,
―sΒ'*         then return a pattern "s" (a square) made with "*"s
―TΒ1'*    otherwise, return a pattern "T" (triangle) that is centered and
has a scale factor of 1, made with "*"s
``````

## 第3部分：取反结果

``````?='-SZiγγ
?='-S     if S is a "-"
Ziγ   return γ, inverted across its lines
γ  otherwise, return γ untouched
``````
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.