Codingame 에서이 도전을 받았으며 내 것보다 더 나은 솔루션이 궁금합니다.
표준 입력을 통한 너비가 주어지면 주어진 너비와 길이로 빈 사각형 '#'을 그립니다.
예:
5 결과
#####
# #
# #
# #
#####
나는 이것을 사용하여 파이썬을 사용하여 다른 파이썬 코드에 특히 관심이 있습니다. 그러나 원하는 언어로 솔루션을 게시하십시오.
Codingame 에서이 도전을 받았으며 내 것보다 더 나은 솔루션이 궁금합니다.
표준 입력을 통한 너비가 주어지면 주어진 너비와 길이로 빈 사각형 '#'을 그립니다.
예:
5 결과
#####
# #
# #
# #
#####
나는 이것을 사용하여 파이썬을 사용하여 다른 파이썬 코드에 특히 관심이 있습니다. 그러나 원하는 언어로 솔루션을 게시하십시오.
답변:
암호:
NβBββ#
설명:
Nβ # Get input from the command line and store into β
B # Draw a hollow box with...
β # Width β
β # Height β
# # Filled with the character '#'
# Implicitly output the box
N에서와 같이 표현식에도 사용될 수 있습니다 int(input()). 이 문제가 "주어진 너비와 높이로 빈 사각형을 그립니다"라면 해결책은 다음과 같습니다 BNN#.
:G\1>&*~35*c
: % Input n implicitly. Push range [1 2 ... n]
% STACK: [1 2 3 4 5]
G % Push n again
% STACK: [1 2 3 4 5], 5
\ % Modulo
% STACK: [1 2 3 4 0]
1> % Does each entry exceed 1?
% STACK: [0 1 1 1 0]
&* % Matrix with all pair-wise products
% STACK: [0 0 0 0 0;
0 1 1 1 0;
0 1 1 1 0;
0 1 1 1 0;
0 0 0 0 0]
~ % Negate
% STACK: [1 1 1 1 1;
1 0 0 0 1;
1 0 0 0 1;
1 0 0 0 1;
1 1 1 1 1]
35* % Multiply by 35
% STACK: [35 35 35 35 35;
35 0 0 0 35;
35 0 0 0 35;
35 0 0 0 35;
35 35 35 35 35]
c % Convert to char. 0 is interpreted as space. Display implicitly
% STACK: ['#####';
'# #';
'# #';
'# #';
'#####']
,ajj"###
,ajj draw a box with height (input) and width (input)
"### with a hash border
#필요한가요?
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+'\n'+'#'*n
#\n#입력이있을 때 반환1
인쇄하는 55 바이트 버전
def f(n):a=n-2;print'#'*n,'\n#%s#'%(' '*a)*a,'\n'+'#'*n
모든 입력에서 작동하는 62 바이트 버전 :
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+('\n'+'#'*n)*(n>1)
f=사용하지 않으면 말할 필요가 없습니다.
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoO
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOmoOoomMMM
moOMMMMOOmOomOoMoomoOmoOMOomoomOoMMMmoOMMMMOoMOoMOOmOomOomOomOoMoo
moOmoOMoomoOMMMmoOmoOMMMMOoMOoMOOmOomOomOomOoMoomoOmoOmoOmoOMOomoo
mOomOomOoMoomoOmoOMOomoomOomOomOomOoMoomoOmoOmoOMOOmOoMoomoOMOomoo
온라인으로 사용해보십시오! 두 번째 줄의 숫자를 원하는 숫자로 변경하여 출력을 변경하십시오.
여기에서 사용하고있는 COW 인터프리터는 Perl로 작성되었으며 (이 문제보다 최신 버전이지만) 여기 에 코드를 입력하면 동일한 결과를 얻을 수 있습니다. .
; Note: [n] means "value stored in the nth block of memory".
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoO ;Stores 10 in [0]. 10 is the code point for carriage return
MMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO ;Stores 32 in [1]. 32 is the code point for whitespace
MMMmoOMMMMoOMoOMoO ;Stores 35 in [2]. 35 is the code point for #
moOoom ;Reads STDIN for an integer, and stores it in [3]
MMMmoOMMM ;Copies [3] into [4]
MOO ;Loop as long as [4] is non-zero
mOomOoMoo ;Navigate to [2] and print the character with that code point
moOmoOMOo ;Navigate to [4] and decrement
moo ;End loop
mOoMMMmoOMMMMOoMOo ;Copy [3] into [4] and decrement [4] twice
MOO ;Loop as long as [4] is non-zero
mOomOomOomOoMoo ;Navigate to [0] and print the character with that code point
moOmoOMoo ;Navigate to [2] and print the character with that code point
moOMMMmoOmoOMMMMOoMOo ;Navigate to [3] and copy it into [5], then decrement [5] twice
MOO ;Loop as long as [5] is non-zero
mOomOomOomOoMoo ;Navigate to [1] and print the character with that code point
moOmoOmoOmoOMOo ;Navigate to [5] and decrement
moo ;End loop
mOomOomOoMoo ;Navigate to [2] and print the character with that code point
moOmoOMOo ;Navigate to [4] and decrement
moo ;End loop
mOomOomOomOoMoo ;Navigate to [0] and print the character with that code point
moOmoOmoO ;Navigate to [3]
MOO ;Loop as long as [3] is non-zero
mOoMoo ;Navigate to [2] and print the character with that code point
moOMOo ;Navigate to [3] and decrement
moo ;End loop
String c(int n){String r="";for(int i=n,j;i-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j++<2?"#":" ");return r;}
@ OlivierGrégoire 덕분에 1 바이트가 절약 되었습니다 . @cliffroot
덕분에 2 바이트 절약 .
교차 사각형 만들기 답변을 기반으로 파생 솔루션입니다 .
for(int i=n,j;i-->0;r+="\n")있습니까? 우리는 어떤 것이 가장 중요한지 또는 가장 중요한지 상관하지 않기 때문에 그 순서를 지키는 것이 타당하지 않습니까?
param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z
JohnLBevan 덕분에 -1 바이트
input 을 가져 와서 포스트 감소 된 해시 마크로 $n설정합니다 . 파이프 라인에 사본을 배치하기 위해이를 패린으로 캡슐화합니다. 그런 다음 쉼표 연산자를 사용하여 미리 감소 된 , spaces 행으로 구성된 배열을 만듭니다 . 그것들은 파이프 라인에 남아 있습니다. 그런 다음 파이프 라인에 다시 배치 하십시오. 끝에 암시 적 인 출력 은 요소 사이에 줄 바꿈을 도입하므로 무료로 얻을 수 있습니다.$z$n$n$n##$zWrite-Output
OP의 코드 는 input n <= 1에 대해 작동하지 않기 때문에 input 을 지원할 필요가 없다는 것을 의미했습니다 1.
PS C:\Tools\Scripts\golfing> 2..6|%{"$_";.\draw-a-hollow-square.ps1 $_;""}
2
##
##
3
###
# #
###
4
####
# #
# #
####
5
#####
# #
# #
# #
#####
6
######
# #
# #
# #
# #
######
param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z
.if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
-6 바이트를 제거 .if하고 j두 번째 대신 사용.if
문자열 f대신에 a 대신을 사용하여 -18 바이트.for
NULL로 끝나는 문자열이 아닌 -12 바이트 da
입력은 의사 레지스터 $t0(예 :)를 통해 전달됩니다 r $t0 = 5; {above-code}.
설명:
.if @$t0 *Verify width($t0) at least 1
{ *(registers have unsigned values)
r $t3 = 2000000; *Set $t3 to address where the
*string will be constructed
f @$t3 L@$t0 23; *Put width($t0) '#' at 2000000($t3)
f 2 * @$t3 L@$t0 20; *Put width($t0) ' ' at 4000000(2*$t3)
eb 2 * @$t3 23; *Put '#' on left of ' ' string
eb 2 * @$t3 + @$t0 - 1 23; *Put '#' on right of ' ' string
da @$t3 L@$t0; *Print the top of the box
j 1 < @$t0 *If width($t1) at least 2
'
.for (r $t1 = @$t0 - 2; @$t1; r $t1 = @$t1 - 1) *Loop width($t0)-2 times to...
{
da 2 * @$t3 L@$t0 *...print the sides of the box
};
da @$t3 L@$t0 *Print the bottom of the box
'
}
샘플 출력 :
0:000> r$t0=0
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
0:000> r$t0=1
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x1 bytes
Filled 0x1 bytes
02000000 "#"
0:000> r$t0=2
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x2 bytes
Filled 0x2 bytes
02000000 "##"
02000000 "##"
0:000> r$t0=5
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x5 bytes
Filled 0x5 bytes
02000000 "#####"
04000000 "# #"
04000000 "# #"
04000000 "# #"
02000000 "#####"
n=>(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b
( 0또는 처리하지 않음 1)
13 바이트의 추가 바이트 ( 71 바이트 )의 경우 가능합니다!
n=>n?n-1?(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b:'#':''
이 솔루션은 매우 간단 합니다. 몇 바이트를 절약하기 위해 반복 하지 않기 위해 많은 스토리지를 수행 합니다. variablsm이 없으면 축소되지 않습니다.
n => // Anonymous function definition (Param `n` is the size)
'#'.repeat(n) + // # `n` times to form the top
`
#${' '.repeat(n - 2)}#` // Followed by a newline followed by a hash and `n` - 2 spaces and
// another hash to make one of the middle lines
.repeat(n - 2) + // The above middle lines repeated `n` - 2 times
'#'.repeat(n) // Followed by the top line again
<script type="text/babel">var f=n=>n?n-1?(b='#'[r='repeat'](n))+`\n#${' '[r](n-=2)}#`[r](n)+`\n`+b:'#':'',b,r;function c(){document.getElementById('pre').textContent = f(+document.getElementById('input').value);}</script><input id="input" onkeydown="c();" onkeyup="c();" onchange="c();" onclick="c();" placeholder="Size"><pre id="pre"></pre>
!n?'':n==1?'#':함수 본문의 시작 부분에, 추가로 15 바이트를, 당신은 입력을 처리 할 수 0및 1.
n=>(b='#'[r='repeat'](n))그런 다음 #${" "[r](n-=2)}등을 반복하지 않고 3 바이트를 절약 repeat:)
n=int(input())
for x in range(n):
r=list(' '*n);r[0]=r[-1]='#'
if x%(n-1)==0:r='#'*n
print("".join(r))
list(' '*n) with [' ']*n. You can also replace x%(n-1) with x%~-n
for block into a list comprehension you can save more than 20 bytes
int() and the brackets around print.
<1 instead of ==0.
m=input()-2
for c in'#'+' '*m+'#':print'#'+m*c+'#'
작품 n>=2. Prints each line with a pound sign, n-2 of the appropriate symbol, then another pound sign.
파운드 기호의 별칭을 지정하면 길이가 같습니다.
m=input()-2;p='#'
for c in p+' '*m+p:print p+m*c+p
다른 시도 :
lambda n:'#'*n+('\n#'+' '*(n-2)+'#')*(n-2)+'\n'+'#'*n
lambda n:'#'*n+'\n#%s#'%((n-2)*' ')*(n-2)+'\n'+'#'*n
lambda n:'\n'.join(['#'*n]+['#'+' '*(n-2)+'#']*(n-2)+['#'*n])
n=input();s='#'+' '*(n-2)+'#'
for c in s:print[s,'#'*n][c>' ']
s='##'+' #'*(input()-2)+'##'
for c in s[::2]:print s[c>' '::2]
s='#'+' '*(input()-2)+'#'
for c in s:print s.replace(' ',c)
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i*j&&i^n-1&&j^n-1?32:35));}
곱하기에 몰래 바이트를 저장 ...
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i&&j&&i^n-1&&j^n-1?32:35));}
또한 j를 카운트 다운하고 몇 가지를 더 저장하십시오 ...
i,j;f(n){for(i=n;i--;puts(""))for(j=0;j++<n;putchar(i&&j^1&&i^n-1&&j^n?32:35));}
i를 n에서 0으로 카운트 다운하고 몇 바이트를 절약하십시오 ...
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i^1&&j^1&&i^n&&j^n?32:35));}
이해하기 쉽고 1 바이트 더
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i==1|i==n|j==1|j==n?35:32));}
&& instead of &?
{n->a="*"*n+"\n";n-=2;print(a+"*${' '*n}*\n"*n+a)}
Works for n > 1. Thanks to @Billywob for a couple of bytes swapping out the array for a matrix.
cat(rbind(b<-'#',cbind(b,matrix(' ',n<-scan()-2,n),b),b,'
'),sep='')
Uses rbind and cbind to put rows and columns of #'s around an n-2 square matrix of spaces. Newlines are bound to the rows as well. The newline in the source is significant. Input is from STDIN
\n. You could save two bytes by using matrix instead of array though.
-20 thanks to @Cyoce and @AlexL.
(defun s(v)(format t"~v,,,vA~%"v #\# #\#)(dotimes(h(- v 2))(format t"~v,,,vA~A~%"(- v 1)#\ #\# #\#))(format t"~v,,,vA"v #\# #\#))
Usage:
* (s 5)
#####
# #
# #
# #
#####
Basically uses format twice for the top and bottom and a loop for the rows in between. The format call for the top and bottom outputs a line starting with # and padded to the appropriate width with #s. The format call for the rows in between works similarly, except the padding is spaces and a # gets printed at the end of the line.
Note: I'm rather new to Lisp and expect to have a lot of room for improvement on this.
s? Or do am anonymous function?
dotimes (h (- v 2)) or could it be dotimes(h(- v 2))?
l#n=l<$[1..n]
f n=unlines$'#'#n:('#':' '#(n-2)++"#")#(n-2)++['#'#n]
Usage example:
Prelude> putStrLn $ f 4
####
# #
# #
####
How it works:
l#n=l<$[1..n] -- helper function that makes n copies of l
'#'#n -- make a string of n copies of #, followed by
#(n-2) -- n-2 copies of
'#':' '#(n-2)++"#" -- # followed by n-2 times spaces, followed by #
['#'#n] -- and a final string with n copies of #
unlines -- join with newlines in-between
,þ%µỊṀ€€ị⁾# Y
,þ%µỊṀ€€ị⁾# Y - Main link: n
þ - outer product with
, - pair: [[[1,1],[2,1],...,[n,1]],[[1,2],[2,2],...,[n,2]], ... ,[[1,n],[2,n],...,[n,n]]]
% - mod n: [[[1,1],[2,1],...,[0,1]],[[1,2],[2,2],...,[0,2]], ... ,[[1,0],[2,0],...,[0,0]]]
µ - monadic chain separation
Ị - abs(z)<=1: [[[1,1],[0,1],...,[1,1]],[[1,0],[0,0],...,[1,0]], ... ,[[1,1],[0,1],...,[1,1]]]
€€ - for each for each
Ṁ - maximum: [[1, 1, ...,1], [1, 0, ..., 1], ... ,[1, 1, ..., 1] ]
ị - index into (1 based)
⁾# - "# ": ["##...#","# ...#", ...,"##...#"]
Y - join with line feeds
15 bytes of code, +1 for -n flag.
(Y_Xa-2WR'#s)My
Works for input >= 2. Try it online!
First, we define a function y that takes a string argument, repeats it a-2 times (where a is the first command-line input), and wraps the result in #.
Y _ X a-2 WR '#
_ Identity function
X a-2 String-repeated by a-2
WR '# Wrapped in #
Y Yank the resulting function into y
Next, we apply this function twice--once normally, then again with map--to obtain the square as a list of strings:
y M (y s)
(y s) Call function y with s (preinitialized to " ") as argument
y M Map y to each character of the resulting string
For input of 4, (y s) results in "# #" and y M (y s) in ["####"; "# #"; "# #"; "####"]. This latter value is then printed, with the -n flag causing it to be newline-separated.
To get from the ungolfed to the golfed version:
Y is an operator, which means we can use it in an expression. Instead of Y... followed by (ys), we can just do (Y...s).y; so yM(Y_Xa-2WR'#s) won't work. Solution: swap the operands of the Map operator. As long as one of them is a function and the other is an iterable type, it doesn't matter what order they come in.(let*((d display)(g(λ()(for((i n))(d"#")))))(g)(d"\n")(for((i(- n 2)))(d"#")(for((i(- n 2)))(d" "))(d"#\n"))(g))
Ungolfed:
(define (f n)
(let* ((d display)
(g (λ ()
(for ((i n))
(d "#"))
(d "\n"))))
(g)
(for ((i (- n 2)))
(d "#")
(for ((i (- n 2)))
(d " ") )
(d "#\n"))
(g)))
Testing:
(f 5)
Output:
#####
# #
# #
# #
#####
Pretty darn long for a "golfing" language, but I have forgotten how a lot of it works :P
i_2-_u'#*N+_'#' u*'#N+++u*u
Explanation:
i_2-_u # take input and triplicate, subtracting 2 (5 -> [3,3,5])
'#*N+_ # create the top and bottom rows
'#' u*'#N+++u* # create input - 2 copies of middle rows
u # rotate left 1 to get correct order, implicit output
Golfed:
void F(int n){Console.Write($"{new string('#',n)}\n");for(int i=2;i<n;i++)Console.Write($"#{new string(' ',n-2)}#\n");Console.Write(new string('#',n));}
Ungolfed:
void F(int n)
{
Console.Write($"{new string('#', n)}\n");
for (int i = 2; i < n; i++)
Console.Write($"#{new string(' ', n - 2)}#\n");
Console.Write(new string('#', n));
}
EDIT1: Loop range optimization.
Line split in two for readability:
#N::((var X (repeat "#" N))(print X)(each (seq 3 N) (scope #X::((print (+ "#"
(repeat " " (- N 2)) "#")))))(print X))
Sample usage:
% square.lithp
(
(import "lists")
(def s #N::((var X (repeat "#" N))(print X)(each (seq 3 N) (scope #X::((print (+ "#" (repeat " " (- N 2)) "#")))))(print X)))
(s 10)
)
Output:
$ ./run square.lithp
##########
# #
# #
# #
# #
# #
# #
# #
# #
##########