Crea onde di stringa


19

Data una stringa come input, genera la stringa con il seguente algoritmo applicato:

1. Split the String by " " (find the words): "Hello World" -> ["Hello","World"]
2. Find the vowel count of each component: [2,1]   ( ["H[e]ll[o]","W[o]rld"] )
3. For each of the components, output the first n letter where n is the number 
   of vowels it contains: ["He","W"]
4. Join the list to a single string and reverse it: "HeW" -> "WeH"

Specifiche

  • È possibile accettare input e fornire output in qualsiasi formato standard e l'unico tipo di dati consentito sia per Input che per Output è il tipo String nativo della propria lingua. Non è consentito inserire direttamente un elenco come singole parole.

  • Hai la garanzia che non ci saranno spazi consecutivi.

  • Le vocali sono "a","e","i","o","u","A","E","I","O","U", ma "y","Y" non sono considerate vocali .

  • Si garantisce che nell'input appariranno solo lettere e spazi, ma senza nuove righe.

  • L'output deve essere sensibile al maiuscolo / minuscolo.

  • Non è garantito che ogni parola contenga una vocale. Se non appaiono vocali in quella parola, non devi produrre nulla per essa.

Casi test

Input -> Output
---------------

""                                  -> ""
"Hello World"                       -> "WeH"
"Waves"                             -> "aW"
"Programming Puzzles and Code Golf" -> "GoCauPorP"
"Yay Got it"                        -> "iGY" 
"Thx for the feedback"              -> "eeftf"                  
"Go Cat Print Pad"                  -> "PPCG"   
"ICE CREAM"                         -> "RCCI"

punteggio

Vince l'invio valido più breve per ogni lingua, questo è . Buona fortuna e buon divertimento!


Sandbox per coloro che possono vedere i post eliminati.


Ci scusiamo per la cancellazione temporanea!
Mr. Xcoder,

6
Non so perché pensavo che questo sarebbe stato un PCG sulle onde di stringa (come nella teoria delle stringhe ) (come nelle oscillazioni in un campo). Forse è ora di andare a dormire.
Marc.2377,

2
@ Mr.Xcoder: aggiungi un caso di test con vocali maiuscole. Grazie!
nimi,

@nimi aggiunto. È solo lo stesso algoritmo, non importa il caso.
Mr. Xcoder,

1
@ Mr.Xcoder: sì, ma almeno due risposte hanno sbagliato (entrambe risolte ora).
nimi,

Risposte:


7

Haskell, 59 byte

map fst.reverse.(>>=zip<*>filter(`elem`"aeiouAEIOU")).words

Provalo online!

       words     -- split into a list of words
  (>>=      )    -- apply a function to every word and collect the results in a
                 -- single list
     zip<*>filter(`elem`"aeiouAEIOU")
                 -- f <*> g x = f x (g x), i.e. zip x (filter(...)x)
                 -- we now have a list of pairs of (all letters of x, vowel of x)
                 -- with the length of number of vowels
 reverse         -- reverse the list
map fst          -- drop vowels from the pairs

6

V , 31 byte

Í /ò
òÄøã[aeiou]
|DJ@"|D-òÍî
æ

Provalo online!

00000000: cd20 2ff2 0af2 c4f8 e35b 6165 696f 755d  . /......[aeiou]
00000010: 0a01 7c44 4a40 227c 442d f2cd ee0a e6    ..|DJ@"|D-.....

E spiegazione:

Í               " Substitute Every space
  /             " With
   ò            " Newlines
                " This puts us on the last line of the buffer
ò               " Recursively:
 Ä              "   Duplicate the current line
  ø             "   Count:
   ã            "   Case insensitive
    [aeiou]     "   The number of vowels
<C-a>           "   Increment this number
     |          "   Go to the beginning of this line
DJ              "   Delete the number of vowels, and remove a newline that was accidentally made.
                "   Also, my name! :D
  @"            "   Run the unnamed register, which is the number of vowels that we deleted
    |           "   And move to the n'th column in this line
     D          "   Delete everything on this line after the cursor, keeping the first *n* characters
      -         "   Move up a line
       ò        " End the loop
        Íî      " Remove all newlines
æ               " And reverse:
                "   (implicit) The current line

Questo è sorprendentemente leggibile ... Puoi aggiungere qualche parola su come funziona?
Mr. Xcoder,

Sono impressionato da quanto spesso lo vedo æusato, mi sembra di ricordare che è stato aggiunto di recente ed è uno dei comandi più utili.
nmjcman101,

@ nmjcman101 Sì, sono totalmente d'accordo. æè estremamente utile. Avrei dovuto aggiungerlo molto tempo fa. øè anche molto bello, è bello che questa risposta usi entrambi.
DJMcMayhem

Sembra funzionare senza il primo |( provalo online! ), Che non è nella tua spiegazione. Ma non conosco V; è necessario?
CAD97

@ CAD97 Ah, mi è mancato nella mia spiegazione. Questo funziona per tutti i casi di test, ma si interrompe quando ci sono 10 o più vocali in una parola (perché <C-a>posiziona il cursore alla fine della parola). tio.run/##K/v//3Cvgv7hTVyHNx1uObzj8OLoxNTM/…
DJMcMayhem

5

Brachylog , 17 byte

ṇ₁{{∋ḷ∈Ṿ}ᶜ}ᶻs₎ᵐc↔

Provalo online!

Spiegazione

Questa è una traduzione diretta del problema:

Example input: "Hello World"

ṇ₁                  Split on spaces:         ["Hello", "World"]
  {       }ᶻ        Zip each word with:      [["Hello",2],["World",1]]
   {    }ᶜ            The count of:
    ∋ḷ∈Ṿ                Chars of the words that when lowercased are in "aeiou"

            s₎ᵐ     Take the first substring of length <the count> of each word: ["He","W"]
               c    Concatenate:             "HeW"
                ↔   Reverse:                 "WeH"

4

Perl 6 , 57 byte

{flip [~] .words.map:{.substr(0,.comb(rx:i/<[aeiou]>/))}}

4

Alice , 32 byte

/.'*%-.m"Re.oK"
\iu &wN.;aoi$u@/

Provalo online!

Spiegazione

/....
\...@/

Questo è solo un framework per il codice lineare in Ordinal (modalità di elaborazione delle stringhe). Spiegando il programma, otteniamo:

i' %w.."aeiou".u*&-Nm;Ro.$K@

Ecco cosa fa:

i           Read all input.
' %         Split the input around spaces.
w           Push the current IP address to the return address stack to mark
            the beginning of the main loop. Each iteration will process one
            word, from the top of the stack to the bottom (i.e. in reverse 
            order).

  ..          Make two copies of the current word.
  "aeiou"     Push this string.
  .u*         Append an upper case copy to get "aeiouAEIOU".
  &-          Fold substring removal over this string. What that means is that
              we push each character "a", "e", ... in turn and execute -
              on it. That will remove all "a"s, all "e"s, etc. until all
              vowels are removed from the input word.
  N           Compute the multiset complement of this consonant-only version
              in the original word. That gives us only the vowels in the word.
              We now still have a copy of the input word and only its vowels
              on top of the stack.
  m           Truncate. This reduces both strings to the same length. In particular,
              it shortens the input word to how many vowels it contains.
  ;           Discard the vowels since we only needed their length.
  R           Reverse the prefix.
  o           Print it.
  .           Duplicate the next word. If we've processed all words, this
              will give an empty string.

$K          Jump back to the beginning of the loop if there is another word
            left on the stack.
@           Otherwise, terminate the program.

4

JavaScript (ES6), 76 byte

s=>s.split` `.map(w=>w.split(/[aeiou]/i).map((_,i)=>o=i?w[i-1]+o:o),o='')&&o

Casi test



3

JavaScript (ES6), 96 byte

s=>[...s.split` `.map(w=>w.slice(0,(m=w.match(/[aeiou]/gi))&&m.length)).join``].reverse().join``


Le parole senza vocali ( Thx) non dovrebbero avere output; il tuo test case restituisce l'intera parola.
Justin Mariner,

@JustinMariner Fixed!
darrylyeo,

3

Pyth - 19 byte

_jkm<dl@"aeiou"rd0c

Provalo qui

Spiegazione:

_jkm<dl@"aeiou"rd0c
                  c  # Split implicit input on whitespace
   m                 # For each word d...
               rd0   # ...take the lower-case conversion...
       @"aeiou"      # filter it to only vowels...
      l              # and find the length of this string (i.e., the number of vowels in the word)
    <d               # Take the first # characters of the word (where # is the length from above)
 jk                  # Join on empty string (can't use s, because that will screw up when the input is the empty string)
_                    # Reverse the result (and implicitly print)

Potrei avere 18 byte se non per la stringa vuota:

_sm<dl@"aeiou"rd0c

1
@DigitalTrauma: ho appena aggiunto una spiegazione
Maria,

1
@- qui l'intersezione è molto meglio della regex. Oh, capisco - hai solo una lambda / mappa rispetto alla mia 2.
Digital Trauma,

3

Pyth, 31

Mi ci è voluto molto tempo per scrivere e sento che probabilmente c'è un approccio migliore, ma ecco cosa ho:

_jkm<Fd.T,cQ)ml:d"[aeiou]"1crQ0

Test online .

                             Q     # input
                            r 0    # to lowercase   
                           c       # split by whitespace
               :d"[aeiou]"1        # lambda: regex to find vowels in string
              l                    # lambda: count the vowels in string
             m                     # map lambda over list of words
          cQ)                      # split input by whitespace
         ,                         # list of (input words, vowel counts)
       .T                          # transpose
    <Fd                            # lambda to get first n chars of string
   m                               # map lambda over list of (input words, vowel counts)
 jk                               # join on on empty strings
_                                 # reverse

> Sento che probabilmente c'è un approccio migliore - ne ho 19 in Pyth
Maria il

1
@Svetlana lì ho risolto. Grazie per il jksuggerimento.
Digital Trauma,

3

Ohm, 13 byte

z:αv_K_σh;0JR

Spiegazione

  • Innanzitutto, l'input (implicito) viene suddiviso in spazi per z.
  • Quindi viene avviato un ciclo foreach ( :) con il blocco codice associato associato αv_K_σh.
    • av spinte aeiou
    • _ spinge l'elemento iterato corrente
    • Kconta le occorrenze di aeiouin_
    • _ di nuovo l'elemento
    • σh Divide l'elemento in sezioni di lunghezza occurences e prende il primo elemento.
      • In effetti questo richiede i primi occurencescaratteri
  • 0J Spinge lo stack unito ''
    • Il 0occorre perché richiede un argomento che verrà unito. Se tale argomento non è un array, si unisce allo stack
  • R inverte il risultato
  • stampa implicita del TOS


3

Japt v2.0a0, 12 10 byte

¸®¯Zè\vìw

Provalo


Spiegazione

Praticamente fa esattamente ciò che le specifiche descrivono!

        :Implicit input of string U.
¸       :Split to array on spaces.
®       :Map over the array, replacing each element with itself ...
¯       :  sliced from the 0th character to ...
Zè\v    :  the count (è) of vowels (\v) in the element (Z).
à      :End mapping.
¬       :Join to a string.
w       :Reverse.
        :Implicit output of result.

Meno

A parte: in Japt 2.0 potresti teoricamente passare "%v"a \v(un regex letterale di una classe, equivalente a /\v/). Non ancora utile, ovviamente, poiché non ho ancora implementato la v2.0;)
ETHproductions

@ETHproductions, mi stavo preparando a correre fuori dalla porta quando questa sfida è spuntata, quindi l'ho appena scritta velocemente, accettandola letteralmente. Potrebbe esserci un modo più breve per farlo in modo meno letterale, forse? Tali modifiche al RegEx saranno utili per il salvataggio di alcuni byte; in attesa di loro
Shaggy


2

05AB1E , 14 byte

#RʒDžMDu«Ãg£R?

Provalo online!

Darn 05AB1E non ha builtin per AEIOUaeiou ಠ_ಠ


1
Aspetta ... 05AB1E battuto da Japt?
Mr. Xcoder,

@ Mr.Xcoder Succede più spesso di quanto pensi.
Erik the Outgolfer,

1
#RʒDlžMÃg£R?per 12, puoi praticamente minuscolare il duplicato rimuovendo la necessità di AEIOUaeiou. Inoltre, perché diamine non funzionerà senza il ?? Puoi pubblicare una spiegazione, non ho familiarità conʒ
Magic Octopus Urn,

@carusocomputing Purtroppo l'output deve essere sensibile al maiuscolo / minuscolo.
Erik the Outgolfer,

2

Mathematica, 145 byte

(s=StringCount[#,{"a","e","i","o","u","A","E","I","O","U"}]&/@(x=StringSplit@#);StringReverse[""<>Table[StringTake[x[[i]],s[[i]]],{i,Tr[1^s]}]])&

Non ho molta familiarità con Mathematica, ma lo spazio tra s[[i]]],e non può {i,Length@s}essere rimosso?
Mr. Xcoder,

si certo, l'ho perso. Devo giocare anche a golf di più
J42161217,

C'è un modo per lanciare una stringa in un elenco in Mathematica? Qualcosa del genere "aeiouAEIOU".ToCharArray()?
caird coinheringaahing

intendi Personaggi []?
J42161217

2

Retina , 49 46 byte

i`(?=(([aeiou])|\w)+)((?<-2>.)+)\w* ?
$3
O^$`.

Provalo online! Il link include la suite di test. Spiegazione: Questa è un'applicazione dei gruppi di bilanciamento di .NET. Il lookahead cerca le vocali per le parole, che sono catturate nel gruppo 2. Il gruppo viene quindi spuntato quando ogni lettera è abbinata, catturando così il numero di lettere uguale al numero di vocali nella parola. Il resto della parola e qualsiasi spazio finale vengono quindi ignorati in modo che il processo possa ricominciare con la parola successiva. Alla fine le lettere rimanenti vengono invertite.


2

C # (.NET Core) , 144 byte

using System.Linq;s=>new string(string.Join("",s.Split(' ').Select(e=>e.Substring(0,e.Count(c=>"aeiouAEIOU".Contains(c))))).Reverse().ToArray())

Provalo online!

La parte peggiore è che l'inversione di a stringin C # restituisce a IEnumerable<char>che devi riconvertire in a string.



2

Python 3 , 83 81 79 77 byte

lambda z:''.join(i[:sum(y in'aeiouAEIOU'for y in i)]for i in z.split())[::-1]

Provalo online!



1
cambia in python 2 e non è necessario ()per la stampa
Griffin,

1
@Griffin In Python 2, raw_input()invece , avresti bisogno di input()perdere 4 byte.
Mr. Xcoder,

1
@ Mr.Xcoder perché non puoi semplicemente inserire le virgolette?
Griffin,

1
@Griffin Ah, giusto. Ciò alla fine salverebbe 2 byte.
Mr. Xcoder,

2

Java 8 , 171 151 byte

-20 byte grazie a @Lukas Rotter

Sento che ha ancora bisogno di golf ... fammi sapere nei commenti se hai qualche suggerimento.

s->{String z="";for(String w:s.split(" "))z+=w.substring(0,w.replaceAll("(?i)[^aeiou]","").length());return new StringBuilder(z).reverse().toString();}

Provalo online!


Java supporta (?i)per ignorare case in regexs. Quindi (?i)[aeiou]dovrebbe funzionare anche.
Lukas Rotter,

Puoi anche rimuovere le {}parentesi del ciclo for, poiché in essa è contenuta solo un'istruzione.
Lukas Rotter,

Invece di sottrarre la lunghezza della stringa regex puoi anche solo usare ^per trovare la quantità di vocali: z+=w.substring(0,w.replaceAll("(?i)[^aeiou]","").length());
Lukas Rotter,


1

Lisp comune, 218 byte

(defun p(s &aux(j 0)c(v 0)r)(dotimes(i(1+(length s))(apply'concatenate'string r))(cond((or(= i(length s))(eql(setf c(elt s i))#\ ))(setf r(cons(reverse(subseq s j(+ j v)))r)v 0 j(1+ i)))((find c"AEIOUaeiou")(incf v)))))

Spiegazione

(defun p(s &aux (j 0) c (v 0) r)               ; j start of word, c current char, v num of wovels, r result
  (dotimes (i                                  ; iteration var
            (1+ (length s))                    ; iteration limit
            (apply 'concatenate 'string r))    ; iteration final result
    (cond ((or (= i (length s))                ; if string is terminated   
               (eql (setf c (elt s i)) #\ ))   ;  or, set current char, and this is a space, then
           (setf r (cons (reverse (subseq s j (+ j v))) r) ; push on result from current word chars as number of vowels
                 v 0                           ; reset number of vowels to 0
                 j (1+ i)))                    ; reset start of current word to next char
          ((find c "AEIOUaeiou")               ; if current char is a wovel
           (incf v)))))                        ;   then increment num of vowels

1

sed, 133 (132+1) bytes

sed is called with the -E flag, which apparently means I add one byte.
Note: I have not really attempted to golf this yet.

s/$/\n/
:l
s/(.)(\n.*)/\2\1/
tl
s/\n/ /
h
s/[aoeui]//g
G
:r
s/^(\S*) \S(.*\n\S* )\S/\1 \2/
tr
s/^ //
s/(\n\S*) /\1/
/^\n/!br
s/\s//g

Try it online!


1

Clojure, 96 94 bytes

#(apply str(mapcat(fn[i](take(count(filter(set"aeiouAEIOU")i))i))(reverse(re-seq #"[^ ]+"%))))

Well this length is quite ridiculous. mapcat saved two bytes.


1

Swift 3, 240 bytes

This is a function that can be used with f(s:"Input"). Surprisingly, I don't think it can be golfed further:

import Foundation
func f(s:String){var c=s.components(separatedBy:" "),r="";for i in c{let b=i.startIndex;r+=i[b...i.index(b,offsetBy: i.characters.filter{"aeiouAEIOU".contains(String($0))}.count-1)]};print(String(r.characters.reversed()))}

Try it at IBM Sandbox!


2
Indeed, it seems like you have the shortest Swift code possible for this submission. I have solved it in Swift as well, and also got 240 bytes! Well done!
Mr. Xcoder
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.