하향 숫자 레이스


10

당신의 임무는 최종 숫자 경주 대결에서 이전 합계에 임의의 숫자를 추가하는 프로그램을 만드는 것입니다.

각 레이서 (열)는 0에서 시작하여 모든 레이서가 승리하는 데 필요한 점수에 도달 할 때까지 레이스의 각 단계에서 이전 합계에 1 또는 0을 추가합니다. 1 또는 0은 무작위로 선택해야합니다 (랜덤의 표준 정의는 여기 참조 ). 출력 결과는 각 열이 하나의 경주자를 나타내는 경주 결과를 다음 형식으로 표시합니다.

>> racers:5,score needed:2

0 0 0 0 0 # all racers start at 0
+ + + + + # add
1 0 0 0 1 # random 1 or 0
= = = = = # equals
1 0 0 0 1 # sum
+ + + + +
0 0 0 0 1
= = = = =
1 0 0 0 2 # winner!
+ + + +  
1 1 1 1  
= = = =  
2 1 1 1  
  + + +  
  1 1 1  
  = = =  
  2 2 2   # losers

참고 : 숫자 +와 = 만 출력에 포함하면됩니다.

입력

프로그램은 다음 두 매개 변수를 입력으로 승인합니다.

  1. 레이서 수 (컬럼)-2보다 커야 함
  2. 승리하는 데 필요한 점수 (1보다 커야 함)

이것은 가장 적은 바이트를 가진 프로그램 인 코드 골프입니다.

편집 : 시행 할 수없는 최대 점수는 9입니다. 이는 열의 무결성을 유지하는 것입니다. 또한 출력에서 ​​열 사이의 공백을 생략 할 수 있습니다.


지원해야 할 최대 열 수와 최대 점수는 얼마입니까?
nanofarad

최대 값은 정의되어 있지 않으므로 최소값과 동일합니다. 최소 3 개의 열과 2의 점수입니다.
atlasologist

3
필요한 점수는 두 자리입니까?
Leaky Nun

4
"숫자, + 및 = 만 출력에 포함하면됩니다." 공간은 어떻습니까?
Leaky Nun

공간은 보존 할 필요가 없으며 명확성을 위해 예에 있습니다. 두 자리수에 대한 좋은 질문입니다. 최대 점수가 9라고 가정합니다. 질문을 편집하겠습니다.
atlasologist

답변:


5

젤리, 37 36 33 바이트

,‘X
0Ç<³$пµżIFµ“+=”ṁṖ⁸żF
ÇСḊz⁶G

Dennis 덕분에 3 바이트.

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

설명

,‘X                    Helper link. Argument: n. Radomly return n or n+1.

 ‘                     Increment n
,                      Pair. Yield [n, n+1]
  X                    Return a random item from the pair.

0Ç<³$пµżIFµ“+=”ṁṖ⁸żF   Monadic link. Argument: s. Generate one racer.

0                       Start with value 0.
  <³$пµ                While value is less than s:
 Ç                        Use helper link to increment current value.
                        Collect intermediate results in a list.
         I              Compute consecutive differences.
        ż               Zip intermediate results with their next increment value 0 or 1.
          Fµ            Flatten. Let's call the current list A.
                        Odd items of A are racer state and even items are random 0 or 1.
            “+=”        Yield "+=".
                 Ṗ      Yield A without its last element.
                ṁ       Mold i.e Repeat the characters of the string until it contains length(A)-1 characters.
                  ⁸ż    Zipwith. Pair the elements of A with the correponding characters
                    F   Flatten.

ÇСṫ2z” G               Main link. Arguments: s (score needed), r (#racers)

ÇС                     Call the link above r times.
                        Generate a list of r racers.
   Ḋ                    Remove first element of the list (its a garbage s value)
    z⁶                  Transpose with space as fill value.
      G                 Grid. Format the result.

첫 번째 헬퍼 링크를 ,‘X(증가 된 n 쌍 , 무작위 선택)으로 바꿀 수 있습니다 . 메인 링크 ṫ2에서 (dequeue) 및 변수 로 대체 할 수 있습니다 .
Dennis


2

TSQL, 367 (345) 341 바이트

골프

DECLARE @r int=20, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)a:PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0WHILE @i<@r
SELECT
@i+=1,@A+=char(43-x*11),@s+=IIF(x=1,' ',LEFT(y,1)),@=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))FROM(SELECT
IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z
PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')IF @>''goto a

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

언 골프 드 :

DECLARE @r int=10, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)
a:
PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0

WHILE @i<@r
  SELECT
    @i+=1,
    @A+=char(43-x*11),
    @s+=IIF(x=1,' ',LEFT(y,1)),
    @=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))
  FROM(SELECT IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z

PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')

IF @>''GOTO a

테스트 사이트의 랜덤 시드는 항상 동일하며 매번 동일한 결과를 제공하며 스튜디오 관리에서는 다른 결과를 제공합니다. 레이서와 목표에 다른 값을 사용하여 다른 그림을 얻을 수 있습니다


1

파이썬 3, 237 바이트

from random import*
def f(n,t):
 x='0'*n,;i=j=0;y=''
 while' '*n!=x[i]:
  if j==n:j=0;x+=y,;y='';print(x[i]);i+=1
  y+=' 'if x[i][j]in(' ',str(t))else eval(["'+'","str(randint(0,1))","'='","str(int(x[i-3][j])+int(x[i-1][j]))"][i%4]);j+=1

인수를 통해 입력을 받고 STDOUT으로 인쇄하는 함수입니다. 이 접근법은 모든 레이서에 대해 출력이 '+ value = value'형식의주기 4주기를 따른다는 사실을 이용합니다. 카운터 모듈로 4를 사용하면 각 단계에 대해 원하는 값을 문자열로 포함하는 목록을 색인화 할 수 있으며 결과는 Python의 평가 함수를 사용하여 평가할 수 있습니다.

작동 원리

from random import*                       Import Python's random module to access the
                                          randint function
def f(n,t):                               Function with input number of racers n and target
                                          number t
x='0'*n,;i=j=0;y=''                       Initialise return tuple storage x, state number
                                          i, racer number j and append string y for x
while' '*n!=x[i]:                         Loop through all j for some i. If the current
                                          state consists only of spaces, all racers have
                                          finished, so stop
y+=...eval([...][i%4])...                 Index into list, using i mod 4, to find the
                                          desired process for the cycle step, and append to
                                          y
(If first step of cycle)
...+...                                   Plus sign
(If second step of cycle)
...str(randint(0,1))...                   Random number from (0,1)
(If third step of cycle)
...=...                                   Equals sign
(If fourth step of cycle)
...str(int(x[i-3][j])+int(x[i-1][j]))...  Addition of random number to previous racer
                                          'score'
...' 'if x[i][j]in(' ',str(t))...         But append space if the racer has previously
                                          finished, or has reached the target
...j+=1                                   Increment j
if j==n:j=0;x+=y,;y='';print(x[i]);i+=1   If j=n, all j must have been looped through.
                                          Reset j, append new state y to x, reset y, print
                                          current state to STDOUT and increment i. When
                                          this first executes, x contains only the initial
                                          state, meaning that this is printed and the cycle
                                          starts with the second state.

Ideone에서 사용해보십시오


1

파이썬 2 , 191 바이트

from random import*
def c(p,w,r=[],l=0):
 while p:
	p-=1;s='0'
	while`w`>s[-1]:s+="+%s="%randint(0,1);s+=`eval(s[-4:-1])`;l+=2
	r+=[s]
 for z in map("".join,zip(*(t+l*' 'for t in r))):print z

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


파이썬 3 , 200 바이트

from random import*
def c(p,w,r=[],l=0):
 while p:
  p-=1;s='0'
  while str(w)>s[-1]:s+="+%s"%randint(0,1);s+="=%s"%eval(s[-3:]);l+=2
  r+=[s]
 for z in map("".join,zip(*(t+l*' 'for t in r))):print(z)

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


0

파이썬 2, 278 바이트

import random
r=5
w=2
s=(0,)*r
while s.count(w)<len(s):
    print ''.join(map(lambda a:str(a),s))+"\n"+'+'*len(s)
    s = tuple(map(lambda x: x<w and x+random.randrange(2) or x,s))
    print ''.join(map(lambda a:str(a), s))+"\n"+'='*len(s)
    s = tuple([x for x in s if x!= w])

여기서 r은 아니오입니다. 레이서와 w는 이길 점수입니다

여기 사용해보십시오!


2
프로그램을 테스트했는데 질문에 설명 된 결과가 표시되지 않고 모든 것이 왼쪽으로 이동되었습니다.
t-clausen.dk

0

펄 5 , 150 바이트

$,=$";say@n=(0)x(@e=('=')x(@p=('+')x<>));$t=<>;while(grep$_<$t,@n){@r=map{$_+=($g=0|rand 2);$g}@n;for$l(p,r,e,n){say map{$n[$_]>$t?$":$$l[$_]}0..$#n}}

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

첫 번째 입력은 레이서 수이고, 두 번째 입력은 점수가 필요합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.