태그 보관물: popularity-contest

popularity-contest

바위, 종이, 가위, 도마뱀, 스팍 [폐쇄]

두 개의 문자열을 입력으로 사용하고 결과에 대한 단일 출력을 리턴하는 함수를 작성하십시오. 가장 인기있는 답변이 이깁니다.

가위 바위 보 도마뱀의 규칙은 다음과 같습니다.

  • 가위 잘라 종이
  • 종이는 바위를 덮는다
  • 바위는 도마뱀을 분쇄
  • 도마뱀 독
  • 스팍이 가위
  • 가위는 도마뱀을 해독합니다
  • 도마뱀은 종이를 먹는다
  • 스팍은 종이를 반증한다
  • 스팍은 바위를 기화시킨다
  • 가위 바위 보

가능한 모든 입력 사례에 대한 출력은 다음과 같습니다.

winner('Scissors', 'Paper') -> 'Scissors cut Paper'
winner('Scissors', 'Rock') -> 'Rock breaks Scissors'
winner('Scissors', 'Spock') -> 'Spock smashes Scissors'
winner('Scissors', 'Lizard') -> 'Scissors decapitate Lizard'
winner('Scissors', 'Scissors') -> 'Scissors tie Scissors'
winner('Paper', 'Rock') -> 'Paper covers Rock'
winner('Paper', 'Spock') -> 'Paper disproves Spock'
winner('Paper', 'Lizard') -> 'Lizard eats Paper'
winner('Paper', 'Scissors') -> 'Scissors cut Paper'
winner('Paper', 'Paper') -> 'Paper ties Paper'
winner('Rock', 'Spock') -> 'Spock vaporizes Rock'
winner('Rock', 'Lizard') -> 'Rock crushes Lizard'
winner('Rock', 'Scissors') -> 'Rock breaks Scissors'
winner('Rock', 'Paper') -> 'Paper covers Rock'
winner('Rock', 'Rock') -> 'Rock ties Rock'
winner('Lizard', 'Rock') -> 'Rock crushes Lizard'
winner('Lizard', 'Spock') -> 'Lizard poisons Spock'
winner('Lizard', 'Scissors') -> 'Scissors decapitate Lizard'
winner('Lizard', 'Paper') -> 'Lizard eats Paper'
winner('Lizard', 'Lizard') -> 'Lizard ties Lizard'
winner('Spock', 'Rock') -> 'Spock vaporizes Rock'
winner('Spock', 'Lizard') -> 'Lizard poisons Spock'
winner('Spock', 'Scissors') -> 'Spock smashes Scissors'
winner('Spock', 'Paper') -> 'Paper disproves Spock'
winner('Spock', 'Spock') -> 'Spock ties Spock'

@Sean Cheshire가 제안한 추가 과제 :이 사이트의 목록과 같은 사용자 지정 목록을 허용합니다. n- 항목 목록을 사용하면 항목이 (n-1) / 2 이전으로 잃고 다음 (n-1) / 2를 이깁니다.



답변

APL

vs←{
    n←'Scissors' 'Paper' 'Rock' 'Lizard' 'Spock'
    x←n⍳⊂⍺ ⋄ y←n⍳⊂⍵ ⋄ X←⍺ ⋄ Y←⍵ ⋄ r←{X,⍵,⊂Y}
    x=y:     r (-x=0)↓'ties'
    y=5|1+x: r x⌷'cut' 'covers' 'crushes' 'poisons' 'smashes'
    y=5|3+x: r x⌷'decapitate' 'disproves' 'breaks' 'eats' 'vaporizes'
    ⍵∇⍺
}

타이 / 타이를 포함하여 모든 경우에 필요한대로 정확하게 출력합니다. 실제 단어를 제외하고 조회 테이블이 없습니다.

http://ngn.github.io/apl/web/에서 시도해 볼 수 있습니다

'Spock' vs 'Paper'
Paper  disproves  Spock

APL은 알고 있습니다!


답변

SED

#!/bin/sed
#expects input as 2 words, eg: scissors paper

s/^.*$/\L&/
s/$/;scissors cut paper covers rock crushes lizard poisons spock smashes scissors decapitates lizard eats paper disproves spock vaporizes rock breaks scissors/
t a
:a
s/^\(\w\+\)\s\+\(\w\+\);.*\1 \(\w\+\) \2.*$/\u\1 \3 \u\2/
s/^\(\w\+\)\s\+\(\w\+\);.*\2 \(\w\+\) \1.*$/\u\2 \3 \u\1/
t b
s/^\(\w\+\)\s\+\1;\(\1\?\(s\?\)\).*$/\u\1 tie\3 \u\1/
:b


답변

다음은 모든 크기의 규칙 문자열을 기반으로하는 일반적인 솔루션입니다. 올바른 이름 “Spock”에 대해 대문자를 올바르게 수행하고 복수 오브젝트에 대해 ‘tie’대신 ‘tie’를 지정하기위한 규칙을 허용합니다.

def winner(p1, p2):
    rules = ('scissors cut paper covers rock crushes lizard poisons Spock'
    ' smashes scissors decapitate lizard eats paper disproves Spock vaporizes'
    ' rock breaks scissors tie scissors'.split())

    idxs = sorted(set(i for i, x in enumerate(rules)
                      if x.lower() in (p1.lower(), p2.lower())))
    idx = [i for i, j in zip(idxs, idxs[1:]) if j-i == 2]
    s=' '.join(rules[idx[0]:idx[0]+3] if idx
          else (rules[idxs[0]], 'ties', rules[idxs[0]]))
    return s[0].upper()+s[1:]

결과 :

>>> winner('spock', 'paper')
'Paper disproves Spock'
>>> winner('spock', 'lizard')
'Lizard poisons Spock'
>>> winner('Paper', 'lizard')
'Lizard eats paper'
>>> winner('Paper', 'Paper')
'Paper ties paper'
>>> winner('scissors',  'scissors')
'Scissors tie scissors'


답변

파이썬

class Participant (object):
    def __str__(self): return str(type(self)).split(".")[-1].split("'")[0]
    def is_a(self, cls): return (type(self) is cls)
    def do(self, method, victim): return "%s %ss %s" % (self, method, victim)

class Rock (Participant):
        def fight(self, opponent):
                return (self.do("break", opponent)  if opponent.is_a(Scissors) else
                        self.do("crushe", opponent) if opponent.is_a(Lizard)   else
                        None)

class Paper (Participant):
        def fight(self, opponent):
                return (self.do("cover", opponent)    if opponent.is_a(Rock)  else
                        self.do("disprove", opponent) if opponent.is_a(Spock) else
                        None)

class Scissors (Participant):
        def fight(self, opponent):
                return (self.do("cut", opponent)       if opponent.is_a(Paper)  else
                        self.do("decaitate", opponent) if opponent.is_a(Lizard) else
                        None)

class Lizard (Participant):
        def fight(self, opponent):
                return (self.do("poison", opponent) if opponent.is_a(Spock) else
                        self.do("eat", opponent)    if opponent.is_a(Paper) else
                        None)

class Spock (Participant):
        def fight(self, opponent):
                return (self.do("vaporize", opponent) if opponent.is_a(Rock)     else
                        self.do("smashe", opponent)    if opponent.is_a(Scissors) else
                        None)

def winner(a, b):
    a,b = ( eval(x+"()") for x in (a,b))
    return a.fight(b) or b.fight(a) or a.do("tie", b)


답변

파이썬

def winner(p1, p2):
    actors = ['Paper', 'Scissors', 'Spock', 'Lizard', 'Rock']
    verbs = {'RoLi':'crushes', 'RoSc':'breaks', 'LiSp':'poisons',
             'LiPa':'eats', 'SpSc':'smashes', 'SpRo':'vaporizes',
             'ScPa':'cut', 'ScLi':'decapitate', 'PaRo':'covers',
             'PaSp':'disproves', 'ScSc':'tie'}
    p1, p2 = actors.index(p1), actors.index(p2)
    winner, loser = ((p1, p2), (p2, p1))[(1,0,1,0,1)[p1 - p2]]
    return ' '.join([actors[winner],
                     verbs.get(actors[winner][0:2] + actors[loser][0:2],
                               'ties'),
                     actors[loser]])


답변

루비, 산술 접근

액터는 각 액터 a[i]가 액터 a[i+1]a[i+2]모듈로 5 와 같은 방식으로이기도록 배열로 배열 될 수 있습니다 .

%w(Scissors Lizard Paper Spock Rock)

그런 다음, 배우에 대한 A인덱스 i우리는 그가 전년도 배우 일치하는 방법을 볼 수 있습니다 B인덱스 j수행하여 result = (j-i)%5: 결과 12수단을 그 배우 1 또는 각각 그의 앞에 2 개소에 대하여 배우 A는 원; 34유사하게 그 배열에 그 뒤에 배우에 대해 손실을 의미한다. 0넥타이를 의미합니다. (이것은 언어에 따라 다를 수 있습니다; Ruby (j-i)%5 == (5+j-i)%5에서도 j>i.)

내 코드에서 가장 흥미로운 부분은이 속성을 사용하여 두 배우의 인덱스 정렬 기능을 찾는 것입니다. 리턴 값은 -1, 0 또는 1이 될 것이다 예상대로 :

winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 }

모든 것이 여기 있습니다 :

def battle p1,p2
    who = %w(Scissors Lizard Paper Spock Rock)
    how = %w(cut decapitate poisons eats covers disproves smashes vaporizes crushes breaks)
    i,j = [p1,p2].map { |s| who.find_index s }

    winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 }

    method = (winner-loser)%5/2
    what = method == 0 && "ties" || how[winner*2 + method-1]

    return "#{who[winner]} #{what} #{who[loser]}"
end


답변

파이썬


  def winner(p,q):
        if p==q:
           return(' '.join([p,'tie',q]))
        d = {'ca':'cut','ao':'covers','oi':'crushes','ip':'poisons','pc': 'smashes','ci':'decapitate','ia':'eats', 'ap':'disproves', 'po':'vaporizes','oc': 'breaks'}
        [a,b] = [p[1],q[1]]
        try:
           return(' '.join([p,d[a+b],q]))
        except KeyError:
           return(' '.join([q,d[b+a],p]))

까다로운 사전을 사용합니다.