Virus vs Antidotes code golf [chiuso]


12

Esiste un array 2D rettangolare contenente virus indicati con "v", antidoto1 indicato con "a" e antidoto2 indicato con "b" (non esistono valori diversi da "v", "a" e "b").

L'antidoto1 può uccidere i virus vicini solo nelle direzioni orizzontale e verticale, ma l'antidoto2 può uccidere i virus vicini (se presenti) nelle direzioni orizzontale, verticale e diagonale.

Una volta attivati ​​gli antidoti, quanti virus rimarranno alla fine?

Esempi:

Ingresso:

vv
vv

Uscita: 4

Ingresso:

av
vv

Uscita: 1

Ingresso:

vvv
vbv
vvv

Uscita: 0

Ingresso:

bvb
bav
vab
vvv
vvb
vvv
vvv
bva
vav

Uscita: 3


2
Apprezzo le tue modifiche @Grimy - Anche bella sfida :)
pixma140

2
@KevinCruijssen, non ha forma irregolare.
Kiara Dan,

4
Possiamo prendere 3 valori (distinti) arbitrari invece di "v", "a" e "b"?
attinat

2
gli antivirus si avvolgono (ovvero, "a" nella riga inferiore rimuove una "v" nella riga superiore)?
Brian,

2
@Kiara Dan Consiglierei di non consentire 3 valori distinti, in quanto mantiene un certo carattere nella sfida, nonché la possibile intelligenza forzata con punti di codice delle lettere.
lirtosiast

Risposte:


8

Python 3 , 135 byte

j=''.join
p='j(s)'+4*'.replace("%s%s","%s%s")'%(*'vbbbbvbbavacvaca',)
f=lambda x:j(eval(2*'(eval(p)for s in zip(*'+'x))))')).count('v')

Provalo online!

-2 byte grazie a Kevin Cruijssen

Spiegazione

Sostituisce 'v' in 'b' se si trova accanto a 'b'. Successivamente, sostituisce tutte le "v" in "c" se si trova accanto a "a". Una seconda iterazione con la versione trasposta dell'array cancella tutti i virus verticali e diagonali. Infine, restituirà il numero rimanente di 'v's.


Come funzione ricorsiva più leggibile (155 byte)


3
È possibile rimuovere lo spazio dopo y>1else. Bel approccio però. All'inizio non ero sicuro di come si occupasse della diagonale b, ma sembra funzionare bene a causa delle tue sostituzioni. :) +1 da parte mia.
Kevin Cruijssen,

@KevinCruijssen Grazie! Le diagonali vengono gestite sostituendo "v" con "a" se si trovano accanto a "b". Nella seconda iterazione, le "v" adiacenti vengono quindi rimosse.
Jitse,

3
Per il seguente input, l'output dovrebbe essere 3, ma il suo ritorno 4: bvb bav vab vvv vvb vvv vvv bva vav
Kiara Dan


1
@KevinCruijssen Ne ho trovato uno ancora più corto, ma il tuo suggerimento salva un altro byte!
Jitse,

5

JavaScript (ES7), 108 byte

Accetta input come una matrice di caratteri.

f=m=>(g=(y,X,V)=>m.map(r=>r.map((v,x)=>V?v>f&V>'a'>(x-X)**2+y*y-2?r[x]=n--:0:v<f?g(-y,x,v):n++)|y++))(n=0)|n

Provalo online!

Simile alla mia risposta originale, ma fare V>'a'>(x-X)**2+y*y-2è in realtà 1 byte più breve rispetto all'uso del trucco hexa descritto di seguito. ¯ \ _ (ツ) _ / ¯


JavaScript (ES7), 109 byte

Accetta input come una matrice di caratteri.

f=m=>(g=(y,X,V)=>m.map(r=>r.map((v,x)=>V?v>f&(x-X)**2+y*y<V-8?r[x]=n--:0:v<f?g(-y,x,'0x'+v):n++)|y++))(n=0)|n

Provalo online!

Come?

UN1=(X1,y1)UN2=(X2,y2)

Q(UN1,UN2)=(X2-X1)2+(y2-y1)2

Considerando le coordinate intere, appare come segue:

854585212541145212585458

Perciò:

  • UN1UN2Q(UN1,UN2)<2
  • UN1UN2Q(UN1,UN2)<3

238

  • UN16-810=210
  • B16-810=310

Commentate

f =                      // named function, because we use it to test if a character
                         // is below or above 'm'
m => (                   // m[] = input matrix
  g = (                  // g is a recursive function taking:
    y,                   //   y = offset between the reference row and the current row
    X,                   //   X = reference column
    V                    //   V = reference value, prefixed with '0x'
  ) =>                   //
    m.map(r =>           // for each row r[] in m[]:
      r.map((v, x) =>    //   for each value v at position x in r[]:
        V ?              //     if V is defined:
          v > f &        //       if v is equal to 'v'
          (x - X) ** 2 + //       and the quadrance between the reference point and
          y * y          //       the current point
          < V - 8 ?      //       is less than the reference value read as hexa minus 8:
            r[x] = n--   //         decrement n and invalidate the current cell
          :              //       else:
            0            //         do nothing
        :                //     else:
          v < f ?        //       if v is either 'a' or 'b':
            g(           //         do a recursive call:
              -y,        //           pass the opposite of y
              x,         //           pass x unchanged
              '0x' + v   //           pass v prefixed with '0x'
            )            //         end of recursive call
          :              //       else:
            n++          //         increment n
      ) | y++            //   end of inner map(); increment y
    )                    // end of outer map()
  )(n = 0)               // initial call to g with y = n = 0
  | n                    // return n

grazie @Arnauld, puoi anche spiegare il codice?
Kiara Dan,

3
@KiaraDan Done.
Arnauld

3

05AB1E , 33 30 29 byte

2F.•s¯}˜?•2ô€Â2ä`.:S¶¡øJ»}'v¢

Provalo online o verifica alcuni altri casi di test .

Porto di risposta Python 3 @Jitse , quindi assicurati di votarlo!
-1 byte grazie a @Jitse .

Spiegazione:

La versione legacy ha il vantaggio di poter comprimere / trasporre un elenco di stringhe, in cui la nuova versione avrebbe bisogno di un esplicito S e J, poiché funziona solo con elenchi di caratteri. Tuttavia, la nuova versione è ancora più corta di 3 byte utilizzando €Âin combinazione con una stringa compressa più corta. Nella versione precedente, manterrebbe solo l'ultimo valore nello stack all'interno della mappa, ma nella nuova versione, manterrà tutti i valori nello stack all'interno della mappa.

2F                  # Loop 2 times:
  .•s¯}˜?•          #  Push compressed string "vbvabbca"
   2ô               #  Split it into parts of size 2: ["vb","va","bb","ca"]
     €Â             #  Bifurcate (short for duplicate & reverse copy) each:
                    #   ["vb","bv","va","av","bb","bb","ca","ac"]
       2ä           #  Split it into two parts:
                    #   [["vb","bv","va","av"],["bb","bb","ca","ac"]]
         `          #  Push both those lists separated to the stack
          .:        #  Replace all strings once one by one in the (implicit) input-string
            S       #  Then split the entire modified input to a list of characters
             ¶¡     #  Split that list by newlines into sublists of characters
               ø    #  Zip/transpose; swapping rows/columns
                J   #  Join each inner character-list back together to a string again
                 »  #  And join it back together by newlines
}'v¢               '# After the loop: count how many "v" remain

Vedi questo mio suggerimento 05AB1E (sezione Come comprimere le stringhe che non fanno parte del dizionario? ) Per capire il motivo per cui .•s¯}˜?•è "vbvabbca".


Non è necessario bc=> base si applica bv=> baprima av=> ac. Pertanto .•6øнãI•(la forma compressa di "" bvavbaac ") è sufficiente, risparmiando 2 byte.
Grimmy,

@Grimy Il risultato è 1 invece di 3 per l'ultimo caso di test .
Kevin Cruijssen,

1
@KevinCruijssen due passaggi sostitutivi invece di tre sembra fare il trucco dopo tutto
Jitse

@Jitse Grazie. La stringa di compressione è più corta di 2 byte, ma ora ho bisogno di .:(sostituire tutto una volta) invece di :(continuare a sostituire tutto fino a quando non è più presente). Ancora -1, però. :) Grazie per avermi fatto sapere.
Kevin Cruijssen,

2

Java 10, 211 209 byte

m->{int i=m.length,j,c=0,f,t,I,J;for(;i-->0;)for(j=m[i].length;j-->0;c+=m[i][j]>98?f/9:0)for(f=t=9;t-->0;)try{f-=m[I=i+t/3-1][J=j+t%3-1]==98||Math.abs(I-i+J-j)==1&m[I][J]<98?1:0;}catch(Exception e){}return c;}

Modifica della mia risposta per la sfida All the single eights .
-2 byte grazie a @ceilingcat .

Provalo online.

Spiegazione:

m->{                           // Method with char-matrix parameter & int return-type
  int i=m.length,              //  Amount of rows
      j,                       //  Amount of columns
      c=0,                     //  Virus-counter, starting at 0
      f,                       //  Flag-integer
      t,I,J;                   //  Temp-integers
  for(;i-->0;)                 //  Loop over the rows of the matrix
    for(j=m[i].length;j-->0    //   Inner loop over the columns
        ;c+=                   //     After every iteration: increase the counter by:
            m[i][j]>98         //      If the current cell contains a 'v'
             f/9               //      And the flag is 9:
                               //       Increase the counter by 1
            :0)                //      Else: leave the counter unchanged by adding 0
      for(f=t=9;               //    Reset the flag to 9
          t-->0;)              //    Loop `t` in the range (9, 0]:
         try{f-=               //     Decrease the flag by:
           m[I=i+t/3-1]        //      If `t` is 0, 1, or 2: Look at the previous row
                               //      Else-if `t` is 6, 7, or 8: Look at the next row
                               //      Else (`t` is 3, 4, or 5): Look at the current row
            [J=j+t%3-1]        //      If `t` is 0, 3, or 6: Look at the previous column
                               //      Else-if `t` is 2, 5, or 8: Look at the next column
                               //      Else (`t` is 1, 4, or 7): Look at the current column
            ==98               //      And if this cell contains a 'b'
            ||Math.abs(I-i+J-j)==1
                               //      Or if a vertical/horizontal adjacent cell
              &m[I][J]<98?     //      contains an 'a'
               1               //       Decrease the flag by 1
            :0;                //      Else: leave the flag unchanged by decreasing with 0
         }catch(Exception e){} //     Catch and ignore any ArrayIndexOutOfBoundsExceptions,
                               //     which is shorter than manual checks
  return c;}                   //  And finally return the virus-counter as result

1

Carbone , 39 byte

WS⊞υι≔⪫υ⸿θPθ≔⁰ηFθ«≧⁺›⁼ιv⁺№KMb№KVaηι»⎚Iη

Provalo online! Il collegamento è alla versione dettagliata del codice. Spiegazione:

WS⊞υι≔⪫υ⸿θPθ

Unisci le stringhe di input con i \rcaratteri e disegna il risultato sulla tela.

≔⁰η

Cancella il numero di virii live.

Fθ«

Scorri i caratteri nell'input.

≧⁺›⁼ιv⁺№KMb№KVaη

Se il carattere corrente è un virus e non ci sono adiacenti bs in alcuna direzione o as ortogonalmente, incrementare il numero di virii vivi.

ι»

Ripeti con il prossimo personaggio.

⎚Iη

Cancella la tela e stampa il numero totale di virii live.


1

Perl (-00lp ), 82 byte

Usando regex per sostituire vcon lo spazio, quindi conta le vs

/.
/;$,="(|..{@-})";$;="(|.{@-,@+})";$_=s/(a$,|b$;)\Kv|v(?=$,a|$;b)/ /s?redo:y/v//

TIO

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.