Costruiamo una scala


19

Non abbiamo abbastanza (semi) facili sfide per i principianti. Sempre più di quelli facili sono già stati presi. Quindi ho cercato di trovare qualcosa che potesse essere realizzabile dai principianti, ma non è un duplicato.

Ingresso:

Una singola stringa separata con la nuova riga del sistema operativo (ovvero \r\n)
o un array con più stringhe.

Uscita - Le scale :

Rimuovi tutti i simboli non alfabetici e non numerici. Quindi non rimane altro [A-Za-z0-9]. E poi 'costruisci una scala'; fondamentalmente ordinandoli in lunghezza con il più piccolo in alto e il più largo in basso.

Regole della sfida:

  1. Quando due stringhe hanno la stessa lunghezza, le uniamo le une con le altre come un'unica grande stringa (l'ordine non ha importanza, quindi potrebbe essere dal primo all'ultimo o dall'ultimo al primo, qualunque dei due che preferisci).
  2. La regola sopra può impilare quando le stringhe unite sono di nuovo di uguale lunghezza (vedi caso di test 2).

Regole generali:

  • L'input è STDIN e contiene solo caratteri ASCII. E l'output è STDOUT.
  • Il caso dell'output deve essere uguale all'input.
  • Ogni invio deve essere un programma completo in grado di compilare ed eseguire, quindi non solo un metodo / funzione. EDIT: Sono piuttosto nuovo, quindi forse è meglio usare il default da ora in poi, anche se preferisco un programma completo da solo. Ci scusiamo per tutti coloro che hanno già pubblicato un programma completo. Sentiti libero di modificare e proverò a non cambiare la posta a metà sfida la prossima volta.
  • Questo è , quindi vince la risposta più breve in byte. Probabilmente accetto la risposta più breve tra un anno.
    Non lasciare che le risposte del code-golf ti scoraggino dal pubblicare lingue non codegolf giocate a golf come C # e simili! Prova a trovare la risposta più breve per qualsiasi linguaggio di programmazione.
  • Sentiti libero di usare lingue più recenti di questa domanda.

Casi test:

Ingresso 1:

This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do

Uscita 1:

Okthatwilldo
Thisisasampletext
Blablablasomemoretext
Thewoodmaybeofexcellentquality
thatyouwillhavetousetobuildstairs
orprettycrappyalmostfallingapartandfilledwithtermites

Ingresso 2:

A
small
one
that
contains
equal
length
strings
for
the
special
rule

Uscita 2:

A                   Or alternatively:       A
length                                      length
oneforthe                                   theforone
smallequal                                  equalsmall
stringsspecial                              specialstrings
thatrulecontains                            containsrulethat

Passaggi spiegati di 2:

Primo ordine sulla lunghezza:

A
one
for
the
that
rule
small
equal
length
strings
special
contains

Prima unione:

A
oneforthe
thatrule
smallequal
length
stringsspecial
contains

Secondo ordine sulla lunghezza:

A
length
thatrule
contains
oneforthe
smallequal
stringsspecial

Seconda unione:

A
length
thatrulecontains
oneforthe
smallequal
stringsspecial

Terzo ordine sulla lunghezza:

A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

Ingresso 3:

Test,
test.
This
is
a
test.

Uscita 3:

a                   Or alternatively:       a
is                                          is
TesttestThistest                            testThistestTest

Ingresso 4:

a
bc
d!
123

Uscita 4:

123     Or alternatively:    123
adbc                         dabc

1
containsnon dovrebbe essere nell'output 2. Viene unito athatrule
Keatinge

2
Hai praticamente ottenuto l'esatto contrario di quello che volevi, è piuttosto difficile farlo.
Bálint,

"Sentiti libero di usare lingue più recenti di questa domanda" - Quindi, se creo una lingua, solo per risolvere questa sfida in 0 byte, è tecnicamente legale, non è vero?
Bálint,

Questa sfida è stata nella sandbox?
Bálint,

1
@nimi Personalmente preferisco davvero un programma completo, ma se insisti davvero posso rimuoverlo ora e tutti possono usare il default .. Sono piuttosto nuovo, quindi forse è meglio usare il default da ora in poi. Ci scusiamo per tutti coloro che hanno già pubblicato un programma completo. Sentiti libero di modificare e proverò a non sbagliare le regole a metà sfida la prossima volta.
Kevin Cruijssen,

Risposte:


4

Buccia , 11 byte

ωȯmΣġLÖLmf□

Provalo online!

Husk è più giovane di questa sfida (che non fa alcuna differenza ufficialmente, ma comunque).

Spiegazione

ωȯmΣġLÖLmf□  Implicit input (list of strings), say ["a","bc","d!","123"]
        mf□  Keep only alphanumeric chars of each: ["a","bc","d","123"]
ωȯ           Repeat until fixed point is reached:
      ÖL       Sort by length: ["a","d","bc","123"]
    ġL         Group by length: [["a","d"],["bc"],["123"]]
  mΣ           Concatenate each group: ["ad","bc","123"]
             Final result ["123","adbc"], print implicitly separated by newlines.

Quando "mantieni solo i caratteri alfanumerici di ciascuno" mf□, dovresti essere geloso. Quando "gruppo per lunghezza" è ġL, dovresti essere stupito.
Erik the Outgolfer,

Ho accettato la tua risposta ora. La nuova meta è che si possono usare lingue più recenti della sfida (e l'ho già menzionato nella mia sfida quando l'ho pubblicata). Come ho detto prima, bella risposta!
Kevin Cruijssen,

4

Python 3, 264 byte

Non sono bravo nel code golf, quindi sono sicuro che questa non sarà la migliore risposta di Python 3. Questo utilizza la ricorsione e un dict ordinato con tutte le parole per ogni lunghezza.

from collections import*
def f(i):
 d = defaultdict(list)
 for l in i: x = "".join(c for c in l if c.isalnum());d[len(x)].append(x)
 n = (sorted(["".join(d[z]) for z in d.keys()], key=len))
 if n == i:return "\n".join(n)
 return f(n)
print(f(eval(input())))

Prende input da stdin come elenco, ad esempio, testarlo con questo elenco:

['A', 'small', 'one', 'that', 'contains', 'equal', 'length', 'strings', 'for', 'the', 'special', 'rule']

Uscita:

A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

1
Bella risposta! Un paio di consigli sul golf: 1) Non hai bisogno di spazi attorno a = segni o == segni. 2) Python può rilevare le parole chiave se sa che non può essere un altro nome di variabile, come quello che hai fatto con "import *" (es. ") Per", "return" \ n ""). 3) Sono abbastanza sicuro (non positivo) che non hai bisogno delle parentesi attorno a Sort (). Buona programmazione!
Blu,

puoi usare al filter(str.isalnum, l)posto della "".joinparte
njzk2

4

Retina, 69 63 byte

[^ \ W¶] | _

{ `\ B ((.) +) ¶ ((?.) +) \ B (? (2) (?!))
$ 1 $ 3
O $ `(.) +
$ # 1 $ *

Provalo online!


Penso che puoi cambiare la prima riga in [^\w¶]|_. Anche se non sono ancora sicuro che sia ottimale.
FryAmTheEggman,

3

Oracle SQL 11.2, 346 byte

Le righe nella stringa di input sono separate da '¤'. In questo modo non è necessario creare una tabella da utilizzare come input.

This is a sample textthat you will have to use to build stairsThe wood may be of excellent qualityor pretty crappy almost falling apart and filled with termitesBla bla bla - some more text¤Ok, that will do
A¤small¤one¤that¤contains¤equal¤length¤strings¤for¤the¤special¤rule
TesttestThis¤is¤a¤test         

Query:

WITH v AS(SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))),r(s,i,l)AS(SELECT s,1,1 FROM v UNION ALL SELECT LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s)),ROW_NUMBER()OVER(PARTITION BY LENGTH(s)ORDER BY s),l+1 FROM r WHERE l<LENGTH(:1)AND i=1)SELECT s FROM r WHERE l=LENGTH(:1);  

Un-golfed

WITH v AS
( 
  -- Splits on ¤ and keeps only alphanum characters 
  SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))
)
-- Recursive view 
-- s : string
-- i : index of the string in case of duplicates
-- l : exit condition
,r(s,i,l)AS
(
  -- Start with every element of the input
  SELECT s,1,1 FROM v
  UNION ALL
  SELECT -- Concatenate elements of the same lengths
         LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s))
         -- Index of elements of the same length (listagg with over generates duplicates)
        ,ROW_NUMBER()OVER(PARTITION BY LENGTH(s) ORDER BY s)
        -- exit condition
        ,l+1 FROM r WHERE l<LENGTH(:1) AND i=1
)
-- Keep only the elements from the last iteration (automaticaly sorted on my system)
SELECT s FROM r WHERE l=LENGTH(:1)  

Puoi sostituire il tuo regex con[\W_]
FliiFe

@FliiFe non rimuove ',' e '.' nell'ultimo caso di prova
Jeto,

Strano ... Ma si potrebbe ancora sostituirlo 0-9con \d. Forse le regole regex sono diverse in sql rispetto a python / php / javascript? (js è ancora un caso speciale a causa di lookbehinds)
FliiFe

2

Haskell, 129 byte

import Data.List
import Data.Char
l=length
print.(foldl(const.map concat.groupBy((.l).(==).l).sortOn l)=<<(filter isAlphaNum<$>))

Accetta e stampa una serie di stringhe. Se il risultato può essere restituito dalla funzione (al contrario di stampato su stdout), è possibile omettere print.e salvare 6 byte.

Come funziona (nota, io uso xper il parametro di input che ovviamente non appare nella versione pointfree sopra):

 (    )=<<(     )          -- (f =<< g) x is f (g x) x, so we fold over x with a
                           -- starting value of:
     filter isAlphaNum<$>x -- keep only alphanumeric chars in every line of x

                           -- during folding, I ignore the the elements of x.
                           -- However folding stops the repeatedly applied function
                           -- after (length x) steps, which is enough for combining
                           -- lines of equal length

 const                     -- ignore elements from x, deal only with start value
                sortOn l   -- sort lines from shortest to longest
      groupBy((.l).(==).l) -- group lines of equal length
    map concat             -- concatenate each group      

print                      -- print result after (length x) iterations

2

Python 3, 184 180 byte

def f(x):l=len;m=filter;y=sorted([''.join(m(str.isalnum,i))for i in x],key=l);*z,=m(l,[''.join(i for i in y if-~j==l(i))for j in range(l(y[-1]))]);y==z and+print(*z,sep='\n')or f(z)

Una funzione che accetta input, per argomento, come un elenco di stringhe e stampa il risultato su STDOUT. L'esecuzione genera un errore (dovuto all'uso dell'operatore + prima dell'istruzione print), ma non prima della stampa dell'output.

Come funziona

def f(x):                              Function with input of list of strings
l=len;m=filter                         Redefine much-used functions: len gives the length
                                       of an object and filter chooses those items from an
                                       iterable for which a function is true
[''.join(m(str.isalnum,i))for i in x]  Strip to leave only alphanumeric characters...
y=sorted(...,key=l)                    ...and sort by length, into y
''.join(i for i in y if-~j==l(i))      Concatenate equal length strings...
[...for j in range(l(y[-1]))]          ...for all possible string lengths...
*z,=(m(l,...))                         ...and remove empty strings by filtering by length
                                       (the empty string has length 0, and is thus false),
                                       into z
y==z and+print(*z,sep='\n')...         If no change after concatenation, no more equal
                                       length strings exist, so print result to STDOUT...
...or f(z)                             ...else pass new list to function

Provalo su Ideone


2

J , 48 byte

[:(/:#&>)[:(#&>,&.>//.])^:_(#~e.&AlphaNum_j_)&.>

Provalo online!

ungolfed

[: (/: #&>) [: (#&> ,&.>//. ])^:_ (#~e.&AlphaNum_j_)&.>

spiegazione

  • (#~e.&AlphaNum_j_)&.> rimuovere non alfano
  • (#&> ,&.>//. ]) combina articoli della stessa lunghezza
  • ^:_ continua a combinare fino a quando non smette di cambiare
  • (/: #&>) ordina per lunghezza

1

Javascript 198 188 186 179 byte

Questo è il mio secondo programma javascript golfizzato più lungo

s=>s.replace(/[^\w]|_/g,``,l=0).split(/\s/g).sort(g=(a,b)=>a[m=`length`]-b[m]).reduce((a,b,c)=>a+(a.split(/\s/g)[c-1][m]<b[m]?`
`:` `)+b).replace(/ /g,``).split`
`.sort(g).join`
`

Probabilmente può essere ulteriormente giocato a golf


Per cosa usi la tvariabile?
gcampbell,

Ok, puoi giocare a golf dichiarando y = "split" e poi invece di usarlo .split()puoi usare[y]()
Bald Bantha,

@gcampbell Era solo un residuo dei test
Bálint,

@BaldBantha Non credo che lo renderebbe più breve
Bálint

@BaldBantha L'ho fatto a lungo però
Bálint

1

Perl 5 , 112 byte

@F=<>;while($n-@F){$n=@F;%k=();s/[^a-z0-9]//gi,$k{y///c}.=$_ for@F;@F=values%k}say $k{$_}for sort{$a<=>$b}keys%k

Provalo online!


1

Gelatina , 17 byte

f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY

Provalo online!

Non so perché Ẏf¥€ØWṖ¤L€ĠịµÐLYnon funziona ...

Spiegazione:

f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY Full program
             µÐL  Execute the following until we get a result a second time
     ¤              The following as a nilad
  ØW                  [A-Za-z0-9_]
    Ṗ                 Remove last element (_)
f€                  Filter the left argument (current result) with the above nilad
       €            Left map
      L               Length
        Ġ           Group indices of same values, sort values
          ⁸         Left argument
         ị          Index on ^^ and ^
            €       Left map
           Ẏ          Concatenate elements
                Y Join on newlines (full program will display correctly)

1

Pyth, 22 byte

jlDusM.glkG@Ls++GrG1UT

Provalo qui.

Spiegazione:

jlDusM.glkG@Ls++GrG1UT
j                      join on newlines
 lD                     sort by length
   u                     run until duplicate result, return result (argument G, iteration number H)
    sM                    map concatenate elements
      .g                   group elements by function (argument k)
        l                   length
         k                   k
          G                 G
           @L             left map filter on presence (extra argument first)
             s             concatenate elements
              +             concatenate two items
               +             concatenate two items
                G             G (default = lowercase alphabet)
                 r 1          to uppercase
                  G            G
                    U        unary range [0..n)
                     T        T (default = 10)

1

Pyth, 39 byte

Ritorno al golf!

C'è il programma:

=Qm:d"[\W_]"kQKYLmsd.glkolNb;WnKQ=KQ=yQ;jQ

=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j

Provalo qui!

spiegazioni

=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j       (Implicit) Assign evaluated imput to Q (In this case, an array)
=Q                                            Reassign a value to Q
  m          Q                                map a function over Q
   :d"[\W_]"k                                 Replace any special character with an empty string
              L           ;                   Declare a function y(b)
                      olNb                      Sort b by length
                  .glk                          Group strings of same length in arrays
               msd                              Concat each inner array
                           WnYQ      ;        While Y != Q (previous array is not equal to current array)
                               =YQ              Assign the current array to Y (Y=Q)
                                  =yQ           Assign y(Q) to Q (Q=yQ). Here, the assigned variable name is implicit
                                      j       Display the resulting array

Cerca di usare Re Linvece dim
Leaky Nun,

1

Java 8, 268 byte

Un lambda vuoto che accetta un mutevole List<String>(cioè strumenti adde remove; ad esempio ArrayList). L'output viene stampato su standard out, delimitato da newline, con una nuova riga finale. Cast to Consumer<List<String>>.

l->{int i=0,z;while(i<l.size())l.set(i,l.get(i++).replaceAll("\\W| ",""));while(l.size()>0){l.sort((s,t)->s.length()-t.length());String s=l.remove(0);for(i=0,z=s.length();l.size()>0&&l.get(0).length()==z;i++)s+=l.remove(0);if(i<1)System.out.println(s);else l.add(s);}}

Provalo online

Questo ha finito per essere molto più lungo di quanto mi aspettassi. Come ha osservato Kevin, è più complicato di quanto sembri a prima vista.

Lambda ungolfed

l -> {
    int i = 0, z;
    while (i < l.size())
        l.set(i, l.get(i++).replaceAll("\\W| ", ""));
    while (l.size() > 0) {
        l.sort((s, t) -> s.length() - t.length());
        String s = l.remove(0);
        for (
            i = 0, z = s.length();
            l.size() > 0 && l.get(0).length() == z;
            i++
        )
            s += l.remove(0);
        if (i < 1)
            System.out.println(s);
        else
            l.add(s);
    }
}

Innanzitutto, riduco l'input in atto a lettere e numeri. Quindi elaboro gli input in gruppi per lunghezza. Aggiungo gli elementi al primo nell'elenco fino a raggiungere la lunghezza successiva, rimuovendoli mentre procedo. Se è stato utilizzato solo il primo elemento, questa sarà l'unica stringa di quella lunghezza, quindi viene stampata. Altrimenti, la stringa unita viene aggiunta all'elenco per un'altra iterazione. Ordino l'elenco per lunghezza ogni iterazione prima dell'uso.

Ho iniziato con una soluzione adorabile che utilizzava una coda prioritaria per tenere traccia delle stringhe intermedie. Sfortunatamente, java.util.PriorityQueue<String>è piuttosto lungo (e l'uso del tipo raw era più lungo), quindi doveva andare.


1

Japt v2.0a1-h , 11 byte

Input e output come array di stringhe.

£=mk\W üÊmq

Provalo

£=mk\L üÊmq
                :Implicit input of string array U
£               :Map
  m             :  Map U
   k            :    Remove
    \W          :    /[^A-Z0-9]/gi
       ü        :  Sort & partition by
        Ê       :    Length
         m      :  Map
          q     :    Join
 =              :  Reassign to U for next iteration
                :Implicit output of last element

Anche se al momento ho dimenticato di aggiungere dei casi di test (ne aggiungerò uno ora), le cifre dovrebbero essere mantenute nelle stringhe (quindi [a-zA-Z0-9]anziché [a-zA-Z]).
Kevin Cruijssen,

@KevinCruijssen, risolto
Shaggy

1

JavaScript, 119 byte

Penso che questo dovrebbe essere molto più breve ...

Include 2 newline principali nell'output.

f=s=>s==(s.replace(/[^\w\n]|_/g,t=``).split`
`.sort((x,y)=>x[l=`length`]-y[l]).map(x=>t+=s==(s=x[l])?x:`
`+x),t)?t:f(t)

Provalo online


Un intervallo di caratteri negativo sembra assumere un flag globale, in modo da poter eliminare il gper 118
gen

@ Jan, guarda qui
Shaggy

Allora deve essere la ricorsione, ancora è possibile eliminare il flag globale
gen


1

Perl 6 , 85 byte

{.&([o] {my@a;@a[+.comb]~=$_ for $_;@a.grep(~*)}xx$_).sort(+*.comb)}o*.map:{S:g/\W//}

Provalo online!

Input e output come elenchi di stringhe.


1

Pyth, 21 byte

jusM.glkG:R"[^\w\d]"k

L'input è un elenco di stringhe. Provalo online qui o verifica tutti i casi di test qui .

jusM.glkG:R"[^\w\d]"kQ   Implicit: Q=eval(input()), k=""
                         Trailing Q inferred
          R          Q   For each string in Q...
         : "[^\w\d]"     ... replace non-alphanumerics...
                    k    ... with k (empty string)
 u                       Repeat the following until a fixed point occurs, current as G:
    .g  G                  Group the elements of G...
      lk                   ... by length
                             Groups ordered by the result of the inner function, i.e. length
                             This means that, in the final iteration, this acts as a sort by length
  sM                       Concatenate each group back into a string
j                        Join the resulting list on newlines, implicit print

0

05AB1E , 16 byte

εžKÃ}»Δ¶¡é.γg}J»

Inserisci come un elenco di stringhe.

Provalo online o verifica tutti i casi di test .

Avrebbe potuto essere 14 byte con εžKÃ}Δé.γg}J}» se Δavrebbe funzionato anche con un elenco di stringhe ..

Spiegazione:

ε   }            # Map the (implicit) input-list of strings:
 žjà             #  Leave only the letters and digits of each string
                 #   i.e. ["a","bc","d!","123"] → ["a","bc","d","123"]
     »           # Join the list by newlines to a single string
                 #  i.e. ["a","bc","d","123"] → "a\nbc\nd\n123"
      Δ          # Loop until the string no longer changes:
       ¶¡        #  Split by newlines
                 #   i.e. "a\nbc\nd\n123" → ["a","bc","d","123"]
          }    #  Group the strings by:
           g     #   Their length
                 #    i.e. ["a","bc","d","123"] → [["a,"d"],["bc"],["123"]]
             J   #  Join each group-list to a single string
                 #   i.e. [["a,"d"],["bc"],["123"]] → ["ad","bc","123"]
              »  #  Join this list by newlines again
                 #   i.e. ["ad","bc","123"] → "ad\nbc\n123"
                 # (and the result is output implicitly after the loop)
                 #  i.e. "123\nadbc"

-1

Powershell, Windows 10, 63 byte

Quindi input ...

$n = @"
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do
"@

e codice ...

((($n -Split '\n').Replace(" ","")) -Replace '[\W]','')|Sort *h

Che copre input / output 1, lavorando su 2 e 3 ...


Benvenuti in PPCG! Di solito non consentiamo l'input impostando una variabile. Dovresti creare una funzione che accetta un argomento o prendere l'input da STDIN, un arg della riga di comando o simile.
Stephen,

1
Benvenuti in PPCG! Oltre a quanto affermato da @StepHen, la risposta corrente non riesce per il caso speciale. Mette tutto insieme e ordina una volta, ma non unisce linee di uguale dimensione e riordina di nuovo. (Vedi test case 2.)
Kevin Cruijssen,
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.