다중도 테스트


21

프로그래밍 언어를 사용하여 다음과 같은 방식으로 1에서 99 사이의 숫자 (둘 다 포함)를 표시하십시오.

  • 숫자는 단일 공백으로 구분됩니다.
  • 숫자를 3으로 나눌 수 있으면 괄호 안에 있어야합니다.
  • 숫자를 4로 나눌 수 있으면 대괄호 안에 있어야합니다.
  • 숫자를 3과 4로 나눌 수 있으면 괄호와 대괄호 안에 있어야합니다 (대괄호는 숫자에 더 가깝습니다).

프로그램이 정확하게 표시되어야합니다.

1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)


3
각 항목을 새 줄에 출력 할 수 있습니까 아니면 출력이 모두 한 줄에 있어야합니까?
ETHproductions

4
공백으로 출력을 끝낼 수 있습니다. 몇 가지 대답은 그렇게 가정합니다.
Dennis

답변:





4

젤리 , 21 20 바이트

³Ṗµ3,4ṚƬḍד([“])”j)K

온라인으로 사용해보십시오!

작동 원리

³Ṗµ3,4ṚƬḍד([“])”j)K  Main link. No arguments.

³                     Set the return value to 100.
 Ṗ                    Pop; yield [1, ..., 99].
  µ               )   Map the chain in between over [1, ..., 9]; for each integer k:
   3,4                    Set the return value to [3, 4].
      ṚƬ                  Reverse until a loop is reached. Yields [[3, 4], [4, 3]].
        ḍ                 Test k for divisibility by [[3, 4], [4, 3]], yielding a
                          matrix of Booleans.
         ד([“])”         Repeat the characters of [['(', '['], [']', ')']] as many
                          times as the Booleans indicate.
                 j        Join the resulting pair of strings, separated by k.
                   K  Join the resulting array of strings, separated by spaces.


3

, 30 바이트

⪫EEE⁹⁹I⊕ι⎇﹪⊕κ⁴ι⪫[]ι⎇﹪⊕κ³ι⪫()ι 

온라인으로 사용해보십시오! 링크는 자세한 버전의 코드입니다. 설명:

    ⁹⁹                          Literal 99
   E                            Map over implicit range
        ι                       Current value
       ⊕                        Incrementd
      I                         Cast to string
  E                             Map over list of strings
            κ                   Current index
           ⊕                    Incremented
             ⁴                  Literal 4
          ﹪                     Modulo
              ι                 Current value
                []              Literal string `[]`
                  ι             Current value
               ⪫                Join i.e wrap value in `[]`
         ⎇                      Ternary
 E                              Map over list of strings
                      κ         Current index
                     ⊕          Incremented
                       ³        Literal 3
                    ﹪           Modulo
                        ι       Current value
                          ()    Literal string `()`
                            ι   Current value
                         ⪫      Join i.e wrap value in `()`
                   ⎇            Ternary
                                Literal space
⪫                               Join list
                                Implicitly print

3

J , 54 53 바이트

@Jonah 덕분에 1 바이트 감소

(*stdout(3|.0=4 3 1 3 4&|,1=":)#3|.']) ([',":)@>i.100

온라인으로 사용해보십시오!


이걸 해줘서 고마워 또한 왜 stdout여기서 해야합니까 ... 전에 본 적이 없습니다. @FrownyFrog
조나

@Jonah 완전한 문자열로 출력 할 수 없으며 잘립니다 (...) stdout은 그렇게하지 않으며 줄 바꿈도 인쇄하지 않으므로 각 숫자를 별도로 인쇄 할 수도 있습니다. 어떤 이유로 후행 공백이 나타나지만 (4 개가 있고 1 개만 의도적으로 있습니다)
FrownyFrog

이 접근법은 회전과 사용 선택 모두에서 정말 영리합니다 #. 나는 보조 동사에 서라운드 도입했다 ()[]: g=. {.@[ , ":@] , {:@[. 장황함!
요나

질문 하나 더 : LF대신에 사용한 이유 _. 후자는 작동하는 것 같습니다.
요나

3

C, C ++, 136 133 131 129 128 124 바이트

Zacharý 덕분에 -5 바이트, D 언어의 write () 함수에서 영감을 얻음 (Zacharý 답변 참조)

mriklojn 덕분에 -2 바이트

mriklojn 덕분에 C 버전의 경우 -12 바이트

ceilingcat 덕분에 -4 바이트

#include<cstdio>
void f(){for(int i=0;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

C 특정 최적화 : 115 바이트

#include<stdio.h>
i;f(){for(;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

MSVC는 당신이 inf f()일을 할 수 있습니까? 내 의견을 삭제 한판 승부 '미안 해요, 난 (내가하지 않았다) 짧은 것을 알았는데
재커리

@ Zacharý 아니요, 함수가 너무 간단하고 "f는 int를 반환해야합니다"라고 생각합니다. BTW, 솔루션 3 짧은 바이트였다 (I의 점진 움직이는 한 쌍의 압축 등)
HatsuPointerKun

1
댕, 점잖은 것을 잊어 버렸습니다 printf. C stdio를 사용할 수 없습니까?
Zacharý

2
적어도 gcc 5.3.1에서는 #include가 필요하지 않으며 함수 반환 유형을 제거 할 수 있다는 사실도 사용 / 탐색 할 수 있습니다. 또한 int i전역 범위에서 함수 외부 를 선언하면 기본값은 0으로 설정되고 데이터 유형은 기본값으로 설정됩니다 int. 이것은 0에서 시작하는 루프가 발생할 것이고, 당신이 같이 당신은 루프, 제작 조건 표현에 증가를 이동할 수있는이 문제를 해결하기 위해i;f(){for(;++i<=99;)
mriklojn

1
")\0"+i%3대신 제안하십시오 i%3?"":")". 또한 i=0루프 시작 부분에 추가해야한다고 생각합니다 .
ceilingcat

3

Powershell, 60 바이트

"$(1..99|%{($_,"($_)","[$_]","([$_])")[!($_%3)+2*!($_%4)]})"

설명:

  • 4 개의 요소를 가진 배열 : $_, "($_)", "[$_]", "([$_])"
  • 그리고 색인 : [!($_%3)+2*!($_%4)]
  • 각 번호마다 반복
  • 결과를 문자열로 변환

덜 골프 테스트 스크립트 :

$f = {

$r = 1..99|%{
    ($_, "($_)", "[$_]", "([$_])") [!($_%3)+2*!($_%4)]
}
"$($r)"

}

$expected = '1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)'
$result = &$f
$result-eq$expected
$result

산출:

True
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)

3

MathGolf , 41 40 34 29 바이트

♀({îû)(î+╫îa_'(\')ßyΓî34α÷ä§ 

참고 : 뒤에 공백이 있습니다

단지 내 초 MathGolf의 대답은 ..
-5 덕분 바이트 @JoKing을 .

온라인으로 사용해보십시오.

설명:

♀(             # Push 99 (100 decreased by 1)
  {            # Start a loop, which implicitly loops down to (and excluding) 0
   û)(         #  Push string ")("
      î+       #  Append the 1-indexed index
              #  Rotate the string once towards the right
   îa          #  Push the 1-indexed index of the loop, wrap in a list
   _           #  Duplicate it
    '(        '#  Push string "("
      \        #  Swap the top two items of the stack
       ')     '#  Push string ")"
         ßy    #  Wrap all three into a list, and join them
   Γ           #  Wrap all four into a list
               #  (We now have a list [N, "(N)", "[N]", "([N])"], where N is the index)
   î           #  Push the 1-indexed index of the loop
    34         #  Push 3 and 4 to the stack
      α        #  Wrap all three into a list
       ÷       #  Check for each if the index is divisible by it
               #  (resulting in either [0,0], [0,1], [1,0], or [1,1]
        ä      #  Convert from binary to integer
               #  (resulting in either 0, 1, 2, or 3
         §     #  Push the string at that index from the array
               #  Push a space
               # (After the loop, output the entire stack joined together implicitly)

@JoKing 감사합니다! q생략 될 수 있다는 것을 몰랐고 루프에서 암시 적으로 수행되었습니다. 또한 2/3/4 스트링 내장이 있다는 것을 몰랐습니다. 래핑 된 트릭으로 래핑 된 트릭이 작동하지 않는 것이 너무 나쁩니다.
케빈 크루이 ssen

글쎄, 그것은 프로그램의 끝에서 암시 적 출력에 대한 각 반복의 명시 적 출력을 대신 거래 한 것입니다.
Jo King

@ JoKing 예, 그러나 전체 스택이 상단이 아닌 함께 결합되어 출력 될지 몰랐습니다. :)
Kevin Cruijssen

내 솔루션은 40 바이트에 접근하고 있었지만 잘못 읽고 대괄호 대신 중괄호를 사용해야한다고 생각했습니다. 솔루션에서 잘하셨습니다!
maxb


2

루아, 161123 바이트

b=""for i=1,99 do;c,d=i%3==0,i%4==0;b=b..(c and"("or"")..(d and"["or"")..i..(d and"]"or"")..(c and")"or"").." "end;print(b)

온라인으로 사용해보십시오!

언 골프 드 :

b = ""
for i = 1, 99 do
    c = 1 % 3 == 0
    d = 1 % 4 == 0
    a = ""
    if c then
        a = a .. "("
    end
    if d then
        a = a .. "["
    end
    a = a .. i
    if d then
        a = a .. "]"
    end
    if c then
        a = a .. ")"
    end
    b = b .. a .. " "
end
print(b)


2

C (gcc) , 84 바이트

main(i){while(99/i++)printf("%s%s%d%s%s ","("+i%3,"["+i%4,i-1,"]"+i%4,")"+i%3);}

각 "브래킷 문자열"의 시작 부분에는 널 바이트가 있습니다.

온라인으로 사용해보십시오!


그리고 "("+ i % 3에서 i = 2에 대한 주소가 0 문자 값을 가리키는 지 어떻게 알 수 있습니까? {2,3}의 i에 대해 "["+ i % 4에 대해 동일합니까? "
RosLuP

PPCG는 구현에 의해 언어를 정의하므로 gcc와 함께 작동합니다.
Dennis

나는 gcc 컴파일러의 모든 구현에서 컴파일 된 코드라고 말할 수 없다고 생각합니다. 아마도 PC에서 실행되는 것만 가능합니다 (그러나 가능하지는 않습니다)
RosLuP

@RosLuP gcc 적어도 같은 아키텍처를 가진 모든 것에서 대부분의 컴퓨터에서 동일한 방식으로 작동합니다
ASCII 전용


2

PowerShell , 67 62 바이트

"$(1..99|%{'('*!($x=$_%3)+'['*!($y=$_%4)+$_+']'*!$y+')'*!$x})"

온라인으로 사용해보십시오!

기본적으로 문자열 곱셈 시간 부울 변수 (암시 적으로 1 또는 0으로 캐스트)를 사용 하는 FizzBuzz . 이러한 문자열은 파이프 라인에 남아 있으며 따옴표 안에있는 스크립트 블록 내에 수집됩니다. $OutputFieldSeparator배열 의 기본값 은 공백이므로 공백으로 구분 된 배열 요소를 암시 적으로 제공합니다.


2

C #을 124 117 123 바이트

Kevin Cruijssen 덕분에 -5 바이트

x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));}

테스트 :

Action<int> t = x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));}
t.Invoke(0);
Console.ReadKey();

C #의 진출로 보았습니다. C #은 삼항 연산자의 왼쪽 인수로 정수를 허용합니까, 아니면 부울이어야합니까?
Zacharý

나는 C #에 대해 잘 모르지만 x대신에 사용할 수 i있으므로 걱정할 필요가 int 없습니까? (물론 설정해야합니다).
Zacharý

@ Zacharý 아니오, CS0029 오류 "암시 적으로 int를 부울로 변환 할 수 없습니다"라는 오류가 발생합니다. 그리고 예, 사용할 수 있으며 i 일 i때 0으로 초기화 할 수 있습니다 Invoke. 그러나 그것이 바이트 카운트 에 t ( Action<int>) 선언 과 호출 ( t.Invoke(0)) 을 포함시켜야한다는 것을 의미하지 않습니까?
HatsuPointerKun

같은 x=>{for(x=0;x++<99;)Console.Write((x%3==0?"(":"")+(x%4==0?"[":"")+x+(x%4==0?"]":"")+(x%3==0?")":"")+(x%99==0?"":" "));};것이 작동 하는지 묻고 있습니다.
Zacharý

1
다섯 ==0이 될 수 있습니다 <1.
Kevin Cruijssen


2

루비 , 72 66 바이트

p [*1..99].map{|x|a=x
a="[#{x}]"if x%4<1
a="(#{a})"if x%3<1
a}*' '

추가 트리밍을위한 @ jonathan-frech 및 @ conor-obrien에게 감사합니다.


PPCG에 오신 것을 환영합니다! 70 바이트 .
Jonathan Frech

PPCG에 오신 것을 환영합니다! 배열 과 문자열 이 다음과 a.join baba*b
같기

2

PowerShell, 98 82 74 67 63 62 바이트

@Veskah 덕분에 무려 -31 바이트, @ASCII 전용 덕분에 -5 바이트

(1..99|%{(($a=($_,"[$_]")[!($_%4)]),"($a)")[!($_%3)]})-join' '

온라인으로 사용해보십시오!

나는 아직도 내가 여기서 무엇을했는지 잘 모르겠습니다.


70 바이트를 위한 빠른 골프 . $ a를 문자열로 캐스팅 할 필요는 없으며 "$a"여전히 값을 대체합니다. (참고 : 작은 따옴표는을 대체하지 않고 $foo큰 따옴표 만 대체 합니다). 또 다른 트릭은 0 또는 1 만 신경
쓰면

리스트 인덱싱도 사용하는 경우 67 바이트 .
Veskah




1

펄 -E, 60 바이트

$,=$";say map$_%12?$_%3?$_%4?$_:"[$_]":"($_)":"([$_])",1..99

숫자 사이에 줄 바꿈을 사용할 수 있으면 일부 바이트를 저장할 수 있습니다.이 경우 루프를 이동하면서을 제거하고 루프 로 $,=$";변경할 수 있습니다 .mapforsay


1
당신 아비가일입니까? /^1$|^(11+?)\1+$/?의 발명가
msh210

1
와우. 당신이 여기에 영광입니다!
msh210


1

Batch, 145 bytes

@set s=
@for /l %%i in (1,1,99)do @set/an=%%i,b=n%%4,p=n%%3&call:c
@echo%s%
:c
@if %b%==0 set n=[%n%]
@if %p%==0 set n=(%n%)
@set s=%s% %n%

코드는 서브 루틴으로 넘어가지만 문자열은이 시점에서 이미 인쇄되었으므로 코드가 무해하게 실행됩니다.




1

sfk, 225 bytes

for n from 1 to 99 +calc -var #(n)/3+1/3 -dig=0 +calc -var #text*3-#(n) +setvar t +calc -var #(n)/4 -dig=0 +calc -var #text*4-#(n) +xed -var _0_#(t)\[#(n)\]_ _*_#(t)#(n)_ +xed _0*_([part2])_ _?*_[part2]_ +xed "_\n_ _" +endfor

Try it online!


1

Bash, 61 bytes

-14 bytes, thanks to Dennis

seq 99|awk '{ORS=" ";x=$1%4?$1:"["$1"]";print$1%3?x:"("x")"}'

explanation

Pretty straightforward:

  • seq produces 1..99
  • we pipe that into awk with the output record separator (ORS) set to space so the output is a single line.
  • the main awk body just adds "[]" when the number is divisible by 4, and then adds, on top of that, "()" when divisible by 3.

Try it online!



1

PHP, 65 bytes

while($i++<99)echo$i%4?$i%3?$i:"($i)":($i%3?"[$i]":"([$i])")," ";

or

while($i++<99)echo"("[$i%3],"["[$i%4],$i,"]"[$i%4],")"[$i%3]," ";

(requires PHP 5.5 or later)

Run with -nr or try them online.


1

Python 2, 78 bytes

i=0
exec"i+=1;u=i%3/-2*(i%4/-3-1);print'([%0d])'[u:7-u:1+(i%3<1<=i%4)]%i,;"*99

Try it online!

I envisioned this cool approach slicing '([%0d])' but I can't get the expressions any shorter.


1

Java 8, 92 91 bytes

-1 byte thanks to @Dana

i->{for(;i++<99;)out.printf((i>1?" ":"")+(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i),i);}

Try it online!

Alternative solution, 82 bytes (with trailing space in the output - not sure if that's allowed):

i->{for(;i++<99;)out.printf((i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i)+" ",i);}

Explanation:

for(;i++<99;) - a for loop that goes from the value of i (reused as input, taken to be 0 in this case) to 99

out.printf(<part1>+<part2>,i); - formats the string before immediately printing it to stdout with the value of i

where <part1> is (i>1?" ":"") - prints the space before printing the number unless that number is 1, in which case it omits the space

and <part2> is (i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i) - if i is divisible by both 3 and 4, i has both square and round brackets around it; else if i is divisible by 3, i has round brackets; else if i is divisible by 4, i has square brackets; else, i has no brackets.


Save a byte by moving the space to the beginning of each loop iteration (i>1:" ":"")
dana

That would only work if I printed the result in reverse (see this) but would actually save 2 bytes instead of 1.
NotBaal

Unfortunately that's not the same as the expected output as per the question, but thank you for the suggestion nevertheless!
NotBaal

1
The "try it online" links seem to be broken. I was thinking i->{for(;i++<99;)out.printf((i>1?" ":"")+(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i),i);} ?
dana

1
Ohhhh you're right that does work! Thanks for that!
NotBaal
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.