Che cosa abbiamo?


17

Ispirato e in memoria del nostro amato genio,

John Scholes, 1948-2019

STRAPPARE

Ha inventato e implementato dfns - il suo magnum opus e il soggetto della sfida.

Per gli interessati: ultima documentazione e video dfns completi con John .

Compito

Dato un codice sorgente ASCII, rispondi a quale delle seguenti quattro categorie appartiene:

  1. Dyadic dop

  2. Dop monadico

  3. DFN

  4. Altro

Puoi restituire quattro valori coerenti, ma indica la tua mappatura se non è ovvio.

Dettagli

Si può presumere che il codice sorgente inizi sempre con una parentesi graffa aperta {e termina con una parentesi graffa chiusa }.

Le parentesi graffe nidificate in modo ricorsivo possono verificarsi (ad es. {{{}}}), Ma le categorie 1-3 non possono mai avere una profondità di annidamento delle parentesi graffe inferiore a 1 (quindi {}{}"Altro") e tutte le parentesi graffe devono essere bilanciate (così {{}come "Altro").

I caratteri nei seguenti contesti su una riga vengono ignorati:

  1. A destra di #(un commento):significant#ignored

  2. Racchiuso tra virgolette singole '... '(cioè in una stringa): significant'ignored'significant(Questo vale per #troppo: '#'significant)

  3. A destra di una citazione non 'abbinata (accoppiamento virgolette da sinistra):significant'ignored

In parentesi graffa livello uno (ovvero escludendo parentesi graffe annidate):

  • Le droghe diadiche contengono la frase ininterrotta ww

  • Le droghe monadiche non contengono ww, ma contengonoaa

  • I file DNS non contengono wwnéaa

Casi test

Dops di Dyadic

{ww}
{
    www
}
{
''ww'
}
{aa

ww}
{'#''#'ww?aa}

Dops monadiche

{aa}
{aaaa}
{aa{ww}'ww'}
{w#w'
aa'
}
{aaw*w}
{w'\'aa\''}

Dfns

{}
{a a}
{aA}
{
{aa}
}
{w
w''w#
w}
{{
}}
{w\'aa\'}

Altro

{}{}
{{}
{}}
{ww}}
{}
{}
{ww}{}
{#}
{'
'}

@LuisfelipeDejesusMunoz Dfn. Se vedi un motivo per pensare diversamente, fammi sapere.
— Adám,

1
È possibile evitare le virgolette di stringa e, in tal caso, è necessario gestirle? (es: {'#\'ww?aa'}-> altro?)
— Οuroso

1
@ Οurous No, le specifiche sono quelle indicate: qualsiasi cosa tra virgolette è insignificante. (In effetti, le stringhe APL non hanno alcun meccanismo di escape.) Aggiungerò un caso.
— Adám,

Hm, possiamo supporre che le stringhe non conterranno ''(apostrofo nella stringa, che può anche essere analizzato come due stringhe adiacenti per questa sfida)?
— Erik the Outgolfer,

@EriktheOutgolfer Potrebbe verificarsi. Aggiungerò un caso, ma come dici tu, non importa se 'abc''def'viene analizzato come una o due stringhe per questa sfida.
— Adám,

Risposte:


9

JavaScript (ES6),  145 ... 138  136 byte

0123

s=>[...s].map(c=>s=(n=`
aw}{#'`.indexOf(c))?n>5?i^=2:i?0:n>4?i=1:n>3?d++:n>2?x+=!d--:(o|=n<0|d|s!=c?0:n,c):i=0,o=i=0,x=d=-1)|x|~d?3:2>>o

Provalo online!

Versioni alternative

  • 131 byte prendendo una matrice di caratteri come input
  • 132 byte utilizzando Buffer () (Node.js)

Come?

La stringa di input viene analizzata carattere per carattere.

Traduzione di caratteri in codici

cn

 character | code | triggered operation
-----------+------+---------------------------------------------------------
    \n     |   0  | i = 0
     a     |   1* | o |= n < 0 | d | s != c ? 0 : n
     w     |   2* | o |= n < 0 | d | s != c ? 0 : n
     }     |   3* | x += !d--
     {     |   4* | d++
     #     |   5* | i = 1
     '     |   6  | i ^= 2
   other   |  -1* | same as 'a' or 'w', but always fails because of 'n < 0'

*io≠0

Variabili che descrivono lo stato del parser

Le seguenti variabili vengono utilizzate durante l'analisi:

  • o

    • bit 0: aaè stata trovata una frase valida
    • bit 1: wwè stata trovata una frase valida
  • io

    • bit 0: al momento ci troviamo all'interno di un commento
    • bit 1: attualmente ci troviamo all'interno di una stringa (questo bit è ancora aggiornato all'interno di un commento, ma questo è innocuo)
  • S

  • d-1
  • X0-11

Risultato finale

3X0d-1012o


6

Gelatina ,  50 48 46  45 byte

Ỵµṣ”'m2Kṣ”#Ḣ)KµċⱮƤØ{IF©<-oµ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤

Un collegamento monadico che accetta un elenco di caratteri che produce:

5 - Dyadic dop
4 - Monadic dop
3 - Dfn
0 - Other

Provalo online! O vedi una suite di test .
usa le quotazioni di Python per evitare la possibilità di valutare l'input come set o dizionario Python

Come?

Ỵµṣ”'m2Kṣ”#Ḣ)KµċⱮƤØ{IF©<-oµ⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ - Link: list of characters
                                              - breaking long Link up...
Ỵµṣ”'m2Kṣ”#Ḣ)K      - Replace any strings or comments with (single) spaces
Ỵ                   - split at newline characters
 µ          )       - monadic chain for each:
  ṣ”'               -   split at apostrophe characters
     m2             -   modulo 2 slice (i.e. every other part starting with the first
                    -   - that is, non-string code. Will remove strings from within comments)
       K            -   join with spaces
        ṣ”#         -   split at octothorp characters
           Ḣ        -   head (i.e. non-comment code)
             K      - join with spaces

µċⱮƤØ{IF©<-oµ       - Replace characters of code at depth > 1 with the integer 1
µ           µ       - monadic chain, call previous result A:
    Ø{              -   literal ['{','}']
   Ƥ                -   for prefixes of A:
  Ɱ                 -     map across right argument with:
 ċ                  -       count
      I             -   deltas (i.e. [count('}') - count('{')] for each prefix)
       F            -   flatten (i.e. count('}') - count('{') for each prefix)
                    -   -- i.e -1*depth of each character of A; closing braces at depth+1
        ©           -   (copy this list of depths to the register for later use)
         <-         -   less than -1? (vectorises)
           o        -   logical OR with A (vectorises, replacing deep code with 1s)

⁾waż¤ẇ€‘Ḅ«5×®¬Ḅ⁼1¤ - Categorise the result, R
    ¤              - nilad followed by link(s) as a nilad:
⁾wa                -   literal ['w', 'a']
   ż               -   zip with itself = [['w','w'],['a','a']]
     ẇ€            - for €ach: is a sublist of R?  i.e. one of: [0,0] [1,0] [0,1] [1,1]
       ‘           - increment (vectorises)                     [1,1] [2,1] [1,2] [2,2]
        Ḅ          - unbinary                                     3     5     4     6
         «5        - minimum with five                            3     5     4     5
                 ¤ - nilad followed by link(s) as a nilad:
            ®      -   recall depths from the register
             ¬     -   logical NOT (vectorises) (0->1, other depths->0)
              Ḅ    -   unbinary
               ⁼1  -   equal one -- i.e. depths ends with a 0 and contains no other zero 
           ×       - multiply

3

Clean , 309 293 284 byte

Siamo in grado di farla franca usando solo 3 nomi di variabili alla volta, così li chiameremo a, pe l.

import StdEnv,Text,Data.List
a=isInfixOf o zip2[2,2]
@ =['\'']
$p#p=join@[foldl((\[a:p]_|p>[]=a++[';':join@(tl p)]=split['#']a!!0)o split@)l l\\l<-mklines p]
#l=[(?a- ?l,p)\\a<-inits p&[p:l]<-tails p]
|{p\\(a,p)<-l|a<2}<>"{}"=0|a['ww']l=1|a['aa']l=2=3
?l=sum[1\\'{'<-l]-sum[1\\'}'<-l]

Provalo online!

Definisce la funzione $ :: [Char] -> Inte alcuni helper, fornendo la mappatura:

  • 0: Altro
  • 1: Dyadic dop
  • 2: Dop monadico
  • 3: Dfn

Espanso (prima versione) e con più di 3 nomi di variabili:

$ s
    # s // remove strings and comments
        = join [';'] [ // join the second argument with semicolons
            limit ( // take the first repeated element of
                iterate // an infinite list of applications of the first argument
                    (
                        (
                            \(p, q) = p ++ case q of // join the first half with a modified second half
                                ['\'\'': q] = [';': q] // replace two quotes with a semicolon
                                [c, _: q] = [c: q] // drop the character after a quote or hash
                                _ = [] // leave unmatched strings unchanged
                        ) o span // split the string on the first occurrence of
                            \c = c <> '\'' && c <> '#' // a quote or hash
                    ) l // applied to l
                )
            \\ l <- mklines s // for line l in s split at newlines
        ]
    # b // generate a map of nesting levels
        = [
            ( // the pair of
                ?i - ?t, // the nesting level
                c // the character c
            ) 
            \\ i <- inits s // for init i of s
            & // synchronously iterated with 
                [c: t] <- tails s // character c at the start of tail [c:t] of s
        ]
    // determine what the code is
    | {c \\(n, c) <- b | n < 2} // if the string made of characters with nesting level of less than 2
        <> "{}" // is not the same as the paired braces at the beginning and end
        = 0 // return zero
    | m ['ww'] b // if there are two consecutive 'w's at nesting level 2
        = 1 // return 1
    | m ['aa'] b // if there are two consecutive 'a's at nesting level 2
        = 2 // return 2
    = 3 // otherwise return 3

0

Retina 0.8.2 , 91 byte

m`'.*?('|$)|#.*
¶
s(+`(?!^)\{[^{}]*\}(?!$)
¶
^(?!\{[^{}]*\}$).+
3
^.+ww.+
2
^.+aa.+
1
..+
0

Provalo online! Il link include la suite di test. Spiegazione:

m`'.*?('|$)|#.*
¶

Rimuovi stringhe e commenti.

s(+`(?!^)\{[^{}]*\}(?!$)
¶

Rimuovi le parentesi corrispondenti, allenandoti dal più interno, ma lascia la prima e l'ultima parentesi.

^(?!\{[^{}]*\}$).+
3

Se non abbiamo parentesi corrispondenti, questo è Altro.

^.+ww.+
2

Altrimenti se abbiamo wwallora questo è Dyadic Dop.

^.+aa.+
1

Altrimenti se abbiamo aaallora questo è Monadic Dop.

..+
0

Altrimenti se questo non è qualcosa di cui sopra, allora questo è Dfn.

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.