Word Poker, chi vince?


13

L'input sarà composto da due parole di cinque lettere. In realtà non devono essere parole del dizionario, solo cinque lettere ciascuna, tutte minuscole o tutte maiuscole, a scelta. Nelle parole di input apparirà solo AZ e avranno sempre una lunghezza di 5 caratteri.

Il tuo programma è di segnarli entrambi come se fossero mani di poker e dare la mano più alta. Ovviamente i semi non si applicano qui, solo le classifiche, quindi non ci sono vampate.

Il tipico sistema di classificazione del poker è: "1 paio", "2 coppie", "3 di un tipo", "dritto", "full house", "4 di un tipo", "5 di un tipo" e, naturalmente, c'è la possibilità che la mano (o la parola in questo caso) non valga nulla.

Nel caso di legami , le lettere più vicine ad A sono considerate più alte, quindi una coppia di As batte una coppia di Bs. In alcuni casi, entrambe le mani potrebbero essere identiche, ma in un ordine diverso (o meno), in quel caso l'output può essere eseguito sia a mano che in versione resort.

Questa pagina esterna contiene informazioni su come identificare il vincitore e in particolare risolve i vincoli all'interno delle classifiche specifiche, nel caso in cui non si abbia familiarità con il punteggio delle mani di poker.

Nel caso di rettilinei : le lettere devono essere adiacenti all'alfabeto e non devono essere avvolte. Quindi 'defgh' in qualsiasi ordine è una scala, 'xyzab' non lo è.

Esempi di come segnare una sola mano:

word   | scored as
---------------------
ccccc  | 5 of a kind     <-- highest ranking
woooo  | 4 of a kind
opopo  | full house
vurst  | straight
vovvu  | 3 of a kind
ppoww  | 2 pairs
upper  | 1 pair
kjsdf  | high card only (in this case D) <-- lowest ranking

Quindi il programma produrrà effettivamente risultati come questo:

input        |  output
-----------------------
voviu,kjsdf  |  voviu     because a pair beats nothing 
opoqo,upper  |  opoqo     because 3 of a kind beats a pair
woooo,ggegg  |  ggegg     because 4 Gs beats 4 Os
queue,hopup  |  queue     because 2 pairs beats 1 pair
lodpl,ddkop  |  ddkop     because pair DD beats pair LL
huhyg,hijht  |  huhyg     both have pair HH, but G beats I
ddffh,ccyyz  |  ccyyz     both have 2 pairs, but CC(yyz) beats DD(ffh)
okaok,nkunk  |  nkunk     KK ties with KK, but NN beats OO
abcdf,bcdef  |  bcdef     because it is a straight
qtery,retyq  |  qtery     identical! so doesnt matter
abedc,vyxwz  |  abedc     because it is a "higher" straight
hhhij,hijkl  |  hijkl     because straight beats 3 of a kind
aaabb,zzzzz  |  zzzzz     because nothing beats 5 of a kind

L'ordine delle lettere sia nell'input che nell'output è irrilevante, quindi l'ordine nell'output può essere diverso dall'input, ma deve essere presente lo stesso inventario di lettere.

L'output deve contenere esattamente cinque lettere, né più né meno.

Si applicano le solite regole di codegolf. Il codice più corto vince.

Risposte:


4

JavaScript ( 224 218 213 byte)

s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

Ungolfed:

s=>t=>(
  v=s=>(
    o={},
    l=n=0,
    z=3.5,
    [...s].sort().map(c=>(
      n+=o[c]=-~o[c],
      z*=!l|l+1==(l=c.charCodeAt())
    )),
    [n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]
  ),
  w=v(s),x=v(t),
  w[0]>x[0] || w[0]==x[0] && w[1]<x[1] ? s : t
)

Dopo le map()corse, n + zdetermina la classifica di una mano:

inserisci qui la descrizione dell'immagine

(Puoi capire perché ho inizializzato za 3.5.)

In caso di pareggio, Object.keys(o).sort()viene utilizzato per determinare la mano più alta.

Frammento:

f=

s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

console.log(/voviu/.test(f('voviu')('kjsdf')))       //because a pair beats nothing 
console.log(/opoqo/.test(f('opoqo')('upper')))       //because 3 of a kind beats a pair
console.log(/ggegg/.test(f('woooo')('ggegg')))       //because 4 Gs beats 4 Os
console.log(/queue/.test(f('queue')('hopup')))       //because 2 pairs beats 1 pair
console.log(/ddkop/.test(f('lodpl')('ddkop')))       //because pair DD beats pair LL
console.log(/huhyg/.test(f('huhyg')('hijht')))       //both have pair HH, but G beats I
console.log(/ccyyz/.test(f('ddffh')('ccyyz')))       //both have 2 pairs, but CC(yyz) beats DD(ffh)
console.log(/nkunk/.test(f('okaok')('nkunk')))       //KK ties with KK, but NN beats OO
console.log(/bcdef/.test(f('abcdf')('bcdef')))       //because it is a straight
console.log(/qtery|retyq/.test(f('qtery')('retyq'))) //identical! so doesnt matter
console.log(/abedc/.test(f('abedc')('vyxwz')))       //because it is a "higher" straight
console.log(/hijkl/.test(f('hhhij')('hijkl')))       //because straight beats 3 of a kind
console.log(/zzzzz/.test(f('aaabb')('zzzzz')))       //because nothing beats 5 of a kind


3

Gelatina ,  28 27 29  27 byte

+2 e poi -2 correggi un bug, quindi re-golf.

FI=1ȦḤW
OµNĠLÞṚịµL€+Ç,N
ÇÞṪ

Un collegamento monadico che prende un elenco di "mani" e restituisce (uno dei) vincitori.

Funziona con input tutto maiuscolo o tutto minuscolo.
(... ma non misto, per questo anteponi la riga finale con Œlo Œu).

Provalo online! o vedi la suite di test .

Come?

FI=1ȦḤW - Link 1, straight offset: grouped and reverse sorted hand ordinals
        -                     e.g. [[-101],[-100],[-99],[-98],[-97]]
F       - flatten                  [-101,-100,-99,-98,-97]
 I      - increments               [1,1,1,1]
  =1    - equal 1? (vectorises)    [1,1,1,1]
    Ȧ   - any and all?             1
     Ḥ  - double                   2
      W - wrap in a list           [2]
        -   The purpose of this is so that when "a" from Link 2 represents a straight we
        -   get [2], whereas for any other hand we get [0]. Adding the [2] to [1,1,1,1,1]
        -   (the lengths of a straight's groups) yields [3,1,1,1,1], placing it between
        -   three of a kind, [3,1,1], and a full house, [3,2], as required.

OµNĠLÞṚịµL€+Ç,N - Link 2, hand rank key function: list of characters       e.g. "huhyg"
O               - cast to ordinals                                [104,117,104,121,103]
 µ              - monadic chain separation, call that o
  N             - negate (to give them a reverse-sort order) [-104,-117,-104,-121,-103]
   Ġ            - group indices by value                            [[4],[2],[1,3],[5]]
     Þ          - sort by key function:
    L           -   length                                          [[4],[2],[5],[1,3]]
      Ṛ         - reverse                                           [[1,3],[5],[2],[4]]
       ị        - index into o                       [[-104,-104],[-103],[-117],[-121]]
        µ       - monadic chain separation (call that a)
         L€     - length of €ach                                              [2,1,1,1]
            Ç   - call last link (2) as a monad -> [isStraight? * 2]                [0]
           +    - addition (vectorises)                                       [2,1,1,1]
              N - negate o                                [[104,104],[103],[117],[121]]
             ,  - pair                        [[2,1,1,1],[[104,104],[103],[117],[121]]]
                -   now sorting by this will first be comparing the hand class, and if
                -   and only if they match comparing the card values in the required order.

ÇÞḢ - Main link: list of lists of characters (list of hands)
 Þ  - sort by key function:
Ç   -   last link (2) as a monad
  Ṫ - tail (best or an equal-best hand)

Così incredibilmente breve rispetto a quello che sto facendo in JS 0.o
Stephen

3
@StephenS Benvenuto in PPCG, dove crei qualcosa in un linguaggio non golfistico e poi qualcuno crea qualcosa in Jelly, 05AB1E, Pyth, CJam, ecc. Che è più corto del tuo nome in lingua: I: P
HyperNeutrino

1
@StephenS - JS dovrebbe competere con JS. Non lasciare che le lingue del golf ti impediscano di presentare soluzioni ben ponderate in altre lingue!
Jonathan Allan

@JonathanAllan mi impedisce di fare troppi sforzi per pensare e astrarre un problema che può essere risolto in ~ 25 caratteri, ecco il violino su cui stavo lavorando - ho scritto tutto il boilerplate e nessuno del codice reale
Stephen

È fantastico, ma di recente ho aggiunto un caso di prova che non viene calcolato, in particolare ["hhhij", "hijkl"]. Penso che sia per il modo in cui classifichi una scala come [3,1,1,1,1]?
Polpo,

3

JavaScript ( 250 247 232 byte)

S=d=>(x={},l=99,h=s=0,[...d].map(v=>x[v]=-~x[v]),Object.keys(x).map(v=>(c=91-v.charCodeAt(),t=x[v],s+=1e4**t,c<x[t]?0:x[t]=c,g=(h=c>h?c:h)-(l=c<l?c:l))),[5,4,3,2,1].map(v=>s+=0|x[v]**v),s+(s<5e7&&g<5?1e13:0)),C=a=>b=>(S(a)>S(b)?a:b)

Codice non registrato e casi di test in JSFiddle: https://jsfiddle.net/CookieJon/8yq8ow1b/

Salvati alcuni byte grazie a @RickHitchcock. @StephenS & @Arnauld


Questo è quello che stavo cercando di fare ma non avevo idea di come fare.
Stephen,

Neanche fino a dopo che ho iniziato! :-)
Bumpy

s=0,h=0=> s=h=0Credo
Stephen,

1
Risolto ora dopo un sacco di capelli. Determinare il tie-breaker nei casi in cui la mano è la stessa E i personaggi più bassi nel 1 ° e nel 2 ° gruppo più grande erano gli stessi era il killer (circa 33 byte SOLO per quello !?) :-(
Bumpy

x[v]=x[v]?++x[v]:1può diventare x[v]=(x[v]|0)+1, salvando 3 byte.
Rick Hitchcock,

2

Python 2.7, 242 223 byte

from collections import*
s=sorted
f=lambda x,y:s(map(lambda h:(lambda (r,n):((3,1.5)if len(r)==5 and ord(r[0])+4==ord(r[4])else n,[-ord(d) for d in r],h))(zip(*s(Counter(h).items(),key=lambda z:(-z[1],z[0])))),(x,y)))[1][2]

Simile nel concetto di base agli esempi javascript (ordina per forza della mano con un'eccezione per i rettilinei; quindi per rango); ma approfittando di collections.CounterPurtroppo, .most_commonnon ha il comportamento desiderato; quindi ho dovuto aggiungere una chiave di ordinamento personalizzata.

Modifica: un po 'più di golf nel codice per tagliare 19 byte.

Codice non golfato

from collections import Counter

def convertHand(h):
    # first get item counts, appropriately ordered; e.g. cbabc -> (('b',2), ('c',2),('a',1))
    sortedPairs = sorted(Counter(h).items(),key=lambda x:(-x[1],x[0]))

    # 'unzip' the tuples to get (('b','c','a'), (2,2,1))
    ranks, numberFound = zip(*sortedPairs) 

    if len(ranks)==5:
        # no pairs; is it a straight? well, since they are in increasing order...
        if ord(ranks[0])+4 == ord(ranks[4]):
            # replace numberFound with something that will sort above 3 of a kind but below full house
            numberFound = (3,1.5)

    # invert the values of the ranks, so they are in decreasing, rather then increasing order
    ranks = [-ord(r) for r in ranks]

    # arrange tuples so we can sort by numberFound, and then ranks; and keep a reference to the hand
    return (numberFound, ranks, h)

# put it all together...
def f(x,y):
    hands = [convertHand(h) for h in (x,y)]
    rankedHands = sorted(hands)
    return rankedHands[1][2]

1

Mathematica, 635 byte

H[x_]:=Block[{t},T=Sort@ToCharacterCode[x];L=Last/@Tally@T;t=0;S=Count;If[S[L,2]==1,t=1];If[S[L,2]==2,t=2];If[S[L,3]==1,t=3];If[S[Differences@T,1]==4,t=4];If[S[L,2]==1&&S[L,3]==1,t=5];If[S[L,4]==1,t=6];If[S[L,5]==1,t=7];t];F[K_,v_]:=First@Flatten@Cases[Tally@K,{_,v}];B=ToCharacterCode;(Z=Sort@B@#1;Y=Sort@B@#2;a=H[#1];b=H[#2];If[a>b,P@#1,If[a<b,P@#2]]If[a==b&&a==0,If[Z[[1]]<Y[[1]],P@#1,P@#2]];If[a==b&&(a==1||a==2),If[F[Z,2]<F[Y,2],P@#1,If[F[Z,2]==F[Y,2],If[F[Z,1]<F[Y,1],P@#1,P@#2],P@#2]]];If[a==b&&(a==3||a==5),If[F[Z,3]<F[Y,3],P@#1,P@#2]];If[a==b&&a==6,If[F[Z,4]<F[Y,4],P@#1,P@#2]];If[a==b&&(a==7||a==4),If[Tr@Z<Tr@Y,P@#1,P@#2]])&

.
.
Modulo di input

["abcde", "kkekk"]


C'è un modo per testarlo online?
Polpo,

1
sandbox.open.wolframcloud.com/app/objects incolla con ctrl + v aggiungi l'input alla fine del codice ed esegui con
maiusc
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.