Finde meine Polyphthongs!

19

Für die Zwecke dieser Herausforderung wird ein Polyphthong als zusammenhängendes Stück eines Strings definiert, das nur Vokale enthält und eine Länge von mindestens 2 hat. Wenn Sie einen nicht leeren String als Eingabe verwenden, müssen Sie alle darin enthaltenen Polyphthongs ausgeben .

Hat beispielsweise "abeoic"die folgenden zusammenhängenden Segmente (durch Leerzeichen getrennt):

a b e o i c ab be eo oi ic abe beo eoi oic abeo beoi eoic abeoi beoic abeoic

Wenn wir diejenigen entfernen, die etwas anderes als Vokale enthalten oder eine Länge von weniger als 2 haben, erhalten wir unsere gewünschten Polyphthongs:

eo oi eoi

Ihre Einsendungen müssen die folgenden Regeln einhalten:

  • Sie können für E / A entweder Klein- oder Großbuchstaben wählen, der Ausgabefall muss jedoch mit dem Eingabefall übereinstimmen.

  • Die Vokale sind aeiou(für Kleinbuchstaben) und AEIOU(für Großbuchstaben). yIch werde Ynicht als Vokal betrachtet.

  • Die Eingabe enthält nur druckbare ASCII-Daten.

  • Wenn ein Polyphthong mehrmals vorkommt, können Sie ihn entweder nur einmal oder alle seine Vorkommen ausgeben.

  • Jedes sinnvolle E / A-Format und -Verfahren ist zulässig (auch die Eingabe- und Ausgabelisten sind in Ordnung).

Testfälle

Eingabe -> Ausgabe (Kleinbuchstaben)

r67 ^^ () * 6536782! 87 -> []
Programmieren von Rätseln und Code Golf -> []
und ... ich habe gewonnen! -> ['aa', 'aa', 'aaa']
abeoic -> ['eo', 'oi', 'eoi']
yah eioo ala -> ['ei', 'io', 'oo', 'eio', 'ioo', 'eioo']
@yabeeeayio__e -> ['ee', 'ee', 'ea', 'io', 'eee', 'eea', 'eeea']
0ioen0aaiosnjksd -> ['io', 'oe', 'aa', 'ai', 'io', 'ioe', 'aai', 'aio', 'aaio']

Beachten Sie, dass für Testfälle 3 und 6, können Sie Ausgang 'aa'und 'ee'jeweils nur einmal (die vierte Regel sehen).

Dies ist , die kürzeste Einsendung in Bytes in jeder Sprache gewinnt!

Mr. Xcoder
quelle
Beachten Sie, dass dies ursprünglich als CMC (Chat Mini Challenge) im neunzehnten Byte gepostet wurde , aber Adám sagte, dass es für Main geeignet ist , so dass ich dies am Ende gepostet habe.
Mr. Xcoder
Ich habe Ihren dritten Testfall, 'aa'erscheint zweimal. Muss ein String mehrfach ausgegeben werden, wenn er an verschiedenen Stellen vorkommt, oder kann man nur eindeutige Polyphtongs ausgeben?
Jonathan Frech
@ JonathanFrech Ok, ich denke, die Ausgabe der einzigartigen Polyphtongs ist in Ordnung. Wird bearbeiten.
Mr. Xcoder
Ist die Reihenfolge der Ausgabe wichtig?
Ovs
1
@Xophmeister Für die Zwecke dieser Herausforderung wird ein Polyphthong definiert als - ich weiß, dass dies nicht die richtige sprachliche Definition ist :-)
Mr. Xcoder

Antworten:

7

Python 2 , 102 97 Bytes

danke an @JonathanFrech für -5 Bytes

w=input();l=range(len(w)+1)
print{w[a:b]for a in l for b in l if b-a>1<set(w[a:b])<=set('aeiou')}

Probieren Sie es online!

Kleinbuchstaben I / O

ovs
quelle
1
Ich denke das brauchst du nicht ...AEIOU', da du nur Kleinbuchstaben als Eingabe nehmen darfst.
Jonathan Frech
@ JonathanFrech print([w[a:b]for a in l for b in l[a+2:]if{*w[a:b]}<={*'aeiou'}])arbeitet für 93.
Lynn
@Lynn Und Ihre Lösung produziert 96 Python 2 Bytes .
Jonathan Frech
6

JavaScript (ES6), 77 bis 75 Byte

Erwartet Eingaben in Kleinbuchstaben. Gibt eindeutige Polyphthongs aus, ohne sie zu wiederholen.

w=>(r=[],g=s=>w.match(s)&&[...'aeiou'].map(c=>g(s+c),s[1]&&r.push(s)))``&&r

Testfälle

Wie?

Wir bauen rekursiv den Baum aller möglichen Polyphthongs auf, kürzen Zweige, sobald der aktuelle Knoten nicht mehr in der Eingabe enthalten ist, und speichern alle übereinstimmenden Knoten mit mindestens 2 Zeichen.

w => (                      // given the input w
  r = [],                   // r = array of results
  g = s =>                  // g = recursive function taking s
    w.match(s) &&           // if w contains s:
    [...'aeiou'].map(c =>   //   for each vowel c:
      g(s + c),             //     do a recursive call with s + c
      s[1] &&               //     if s is at least 2-character long:
      r.push(s)             //       push it into r
    )                       //   end of map()
)``                         // initial call to g() with s = ''
&& r                        // return r
Arnauld
quelle
6

Netzhaut , 23 bis 20 Bytes

M!&`[aeiou]+
r!&`..+

Probieren Sie es online!

Dies druckt alle Vorkommen eines Polyphthongs.

Erläuterung

Retina kann zwar alle überlappenden Übereinstimmungen ermitteln, dies bedeutet jedoch, dass von jeder Position aus nach einer Übereinstimmung gesucht wird. Wenn es also mehrere Übereinstimmungen von derselben Position gibt, wird nur eine davon zurückgegeben. Die einzige Möglichkeit, um wirklich alle überlappenden Übereinstimmungen zu erhalten, besteht darin, diese Funktion zweimal zu verwenden, und zwar einmal von links nach rechts und einmal von rechts nach links (so dass wir von jeder möglichen Startposition aus die längstmögliche Übereinstimmung erhalten und dann auch alle Übereinstimmungen für die möglichen Endpositionen).

Also das eigentliche Programm:

M!&`[aeiou]+

Holen Sie sich alle überlappenden Läufe von Vokalen. Was dies wirklich bedeutet, ist, alle Suffixe aller Vokalläufe zu erhalten.

r!&`..+

Erhalten Sie nun alle Präfixe, die mindestens die Länge 2 haben, indem Sie von rechts nach links übereinstimmen. Das Mist hier implizit, weil es die letzte Zeile des Programms ist.

Martin Ender
quelle
Kannst du den Code erklären?
Adám
!&`[aeiou]{2,}ist so nah an richtig , ist es eine Möglichkeit , es gieriger zu bekommen , damit es gegen Spiele io?
AdmBorkBork
1
@ Adám Hinzugefügt eine Erklärung.
Martin Ender
@AdmBorkBork Meine Erklärung deckt ab, warum das nicht funktioniert. Retina spielt nicht mit der eigentlichen Regex-Engine. &Sie können also von jeder Position aus versuchen, eine Übereinstimmung zu erzielen. Sie können also nicht mehrere Übereinstimmungen unterschiedlicher Länge von derselben Position aus haben. Deshalb brauche ich eine zweite Stufe.
Martin Ender
Gute Erklärung, danke.
AdmBorkBork
5

QuadS , 20 + 1 = 21 Bytes

⊃,/⍵
[aeiou]+
1↓,\⍵M

mit der oFlagge

Probieren Sie es online!

In der Reihenfolge, in der die Dinge geschehen:

[aeiou]+ bei jedem Spiel dieser PCRE

,\⍵M Präfixe des Spiels

1↓ Lass den ersten fallen (der einen Vokal hat)

,/⍵ Verketten Sie alle Listen der Präfixe

 offen legen (weil Ermäßigungen enthalten /)


Dies entspricht der stillschweigenden Dyalog APL-Funktion:

{⊃,/⍵}'[aeiou]+'S{1↓,\⍵.Match}⍠'OM'1

Probieren Sie es online!

Adam
quelle
4

Mathematica, 92 Bytes

Select[Join@@Partition[r,i,1]~Table~{i,2,Length[r=(S=Characters)@#]},SubsetQ[S@"aeiou",#]&]&


Probieren Sie es online!

J42161217
quelle
4

Java (OpenJDK 8) , 138 135 134 Bytes

s->{String e,x="";for(int i=0,j,y=s.length();i<=y;i++)for(j=y;j>i;x+=e.matches("[aeiou]{2,}")?e+" ":"")e=s.substring(i,j--);return x;}

Probieren Sie es online!

Roberto Graham
quelle
i<y-1kann sein i<=yund String#matchesprüft implizit den gesamten String, so dass Sie das ^ und nicht benötigen $. +1 dafür, dass du mich geschlagen hast. Ich wollte gerade meine eigene 138-Byte-Antwort veröffentlichen (aber mit diesen Änderungen, die ich vorgeschlagen habe, ist Ihre kürzer). :)
Kevin Cruijssen
3

Gelee , 9 Bytes

ẆḟÐḟØcḊÐf

Probieren Sie es online!

Erläuterung

ẆḟÐḟØcḊÐf  Main Link
Ẇ          Get all (contiguous) sublists
  Ðḟ       Filter; remove all elements where the result is truthy:
 ḟ  Øc     Filter; remove all vowels; if it's truthy, then it contains non-vowels
       Ðf  Filter; keep elements where the result is truthy:
      Ḋ    Dequeue; return all but the first element (truthy if the length was at least 2)

-4 Bytes dank Mr. Xcoder

HyperNeutrino
quelle
11 bytes by replacing L>1$$ with L’$.
Mr. Xcoder
Actually you can replace L’$ with for 9 bytes. An equivalent would be ẆṫLḊḟÐḟØc.
Mr. Xcoder
3

C (gcc), 104 bytes (99 bytes with lowercase only or uppercase only)

Yeah, it leaks - so what?

#include<string.h>
a;f(char*s){*s&&f(s+1);for(a=strspn(s=strdup(s),"AEIOUaeiou");a>1;)s[a--]=0,puts(s);}

Try it online!

Hagen von Eitzen
quelle
3
Seems to work without the #include, and you only need to handle one letter case, so you can shorten it to 80 bytes.
Steadybox
79 bytes
ceilingcat
3

R, 137 bytes

outgolfed by Mark!

function(S)(x=unlist(sapply((s=el(strsplit(S,"[^aeiou]")))[nchar(s)>1],function(x)substring(x,1:(n=nchar(x)),rep(n:1,e=n)))))[nchar(x)>1]

Try it online!

function(S){
 s <- el(strsplit(S,"[^aeiou]"))            # split on non-vowels
 s <- s[nchar(s)>1]                         # vowel groups of length at least 2
 p <- function(x){                          # generates all substrings of inputs
  n <- nchar(x)
  start <- 1:n
  stop <- rep(n:1, n)                       # this will generate dups
  substring(x, start, stop)
} q <- unlist(sapply(s, p)) # all substrings q <- q[nchar(q)>1] # all length-2 or more substrings }

Giuseppe
quelle
You do not need unique.
Mr. Xcoder
"Any reasonable I/O format and method is allowed (lists of characters are also fine, for both input and output)." I've not tried it out, but I suspect this could be quite a lot shorter if you use character lists from the start.
user2390246
@user2390246 perhaps. I'm not convinced that it would help necessarily, but that's probably just because the approach to isolate runs of vowels would be quite different and I can't wrap my head around it right now.
Giuseppe
2

Perl 5, 53 +1 (-p)

/[aeiou]{2,}(?{$h{$&}++})(?!)/g;$_=join$",sort keys%h

Try It Online

Nahuel Fouilleul
quelle
2

PowerShell, 93 88 bytes

param($a)0..($b=$a.count-1)|%{($i=$_)..$b|%{-join$a[$i..$_]}}|?{$_-match'^[aeiou]{2,}$'}

Try it online!

Uses lowercase or uppercase I/O (or a mix!).

Borrows code from my answer on Exploded Substrings to get all the substrings, then pulls out those that regex -match against ^[aeiou]{2,}$ -- i.e., those that are at least two vowels in length and only vowels. Those strings are left on the pipeline and output is implicit.

AdmBorkBork
quelle
2

Haskell, 148 137 130 123 118 bytes

Thanks to @Laikoni for -11 bytes, further -7 bytes by pointing me to golfing tips, another -7 bytes, and yet another -5 bytes, for a total of whopping -30 bytes.

This looked like a good fit for Haskell but the result doesn't seem to agree. I guess Haskell was an OK-ish choice after all. I'm still annoyed by the way subsequences works though.

import Data.List
v=(`elem`"aeiou")
p s=nub$do x<-groupBy((.v).(&&).v)s;[y|y@(c:_:_)<-subsequences x,v c,y`isInfixOf`x]

Try it online!

Xiyng
quelle
1
Welcome to Haskell golfing! You might be interested in our collection of golfing tips, the guide to golfing rules and Of Monads and Men, our Haskell chat room.
Laikoni
1
Some notes on your answer: Newlines have the same byte count as ;, but increase the readability of the code. You always use e together with v, so you can directly declare e=(elem"aeiou"). y!!0 is shorter than head y. There is concatMap instead of concat.map, but even shorter is (=<<) from the list monad wich has the same effect.
Laikoni
1
You can import Data.Lists instead of Data.List. The former has all functions of the latter, but also additional stuff like powerslice, which gives a list of all continuous subsequences.
nimi
1
In the list comprehension, you can match on y@(h:_:_) to drop length y>1 and shorten v(y!!0) to v h.
Laikoni
1
I have two more aces up my sleeve: (1) (\x y->v x&&v y) can be shortened by converting to point-free, either manually using this tip or by using pointfree.io. (2) The list monad can also be used with the do notation, that is do x<-l;[...] is the same as l>>=(\x->[...]). Btw, on TIO you can put your main into the header or footer field to have the byte count match the actual submission.
Laikoni
2

Perl, 45 bytes

local $,=" ";print $_=~/(?=([AEIOU]{2,}))/ig;
Gynn Rickerby
quelle
Welcome to PPCG! Nice first post!
Rɪᴋᴇʀ
1
In case you're wondering about the downvote, that was automatically placed by the Community bot account because your post was edited. Sorry, nothing we can really do about it, it's dumb behaviour. Hopefully the upvotes should trigger automatic downvote retraction.
HyperNeutrino
2

R, 120 bytes 110 bytes

function(x){k=nchar(x);i=k:1;e=expand.grid(i,i[-1]);grep("^[aeiou]+$",mapply(substr,x,e[,2],e[,2]+e[,1]),v=T)}

Try it online!

How it works

function(x){                  #initalize the anonymous function where input is stored in x
  k=nchar(x)                  #set k to the number of characters in x
  i=k:1                       #create vector of integers from k to 1
  e=expand.grid(i,i[-1])      #create matrix of full outer join on i 
                              #except in the second column, limit i to being less than k
  grep("^[aeiou]+$",          #search for strings made of only vowels
       mapply(substr,         #map the substring function
              x,              #with x as the string to subset
              e[,2],          #start at the second column of the outer join
              e[,2]+e[,1]     #end at the sum of the sum of the first and second columns
       ),
       v=T                    #if a match is found, return it's value
  )
}                             #by default, R returns the last line of a function
Mark
quelle
105 bytes nice approach, I'll add a comment to my solution noting that you have outgolfed me :)
Giuseppe
I'll be honest, I was very pleased that I was able to come up with an alternate solution to yours :) Normally you're already light years ahead of me or figuring out all the code I left on the table.
Mark
1

C, 119 bytes

f(char*s){*s&&f(s+1);char*t,*b=calloc(strlen(s),1);for(t=b;*s==65|*s==69|*s==73|*s==79|*s==85;b[1]&&puts(b))*t++=*s++;}

Try it online!

Steadybox
quelle
1

JavaScript (ES6), 105 bytes

s=>eval('a=[];l=i=s.length;while(i--){j=l;while(j--)if(/^[aeiou]{2,}$/.test(t=s.slice(i,j)))a.push(t)}a')

Probably has a lot of golfing left to do.

let f=
s=>eval('a=[];l=i=s.length;while(i--){j=l;while(j--)if(/^[aeiou]{2,}$/.test(t=s.slice(i,j)))a.push(t)}a')
console.log(JSON.stringify(f('r67^^()*6536782!87')))
console.log(JSON.stringify(f('programming puzzles and code golf')))
console.log(JSON.stringify(f('aaand... i won!')))
console.log(JSON.stringify(f('abeoic')))
console.log(JSON.stringify(f('yah eioo ala')))
console.log(JSON.stringify(f('@yabeeeayio__e')))
console.log(JSON.stringify(f('0ioen0aaiosnjksd')))

Patrick Roberts
quelle
1

Perl 5, 44 + 1 (-n) = 45 bytes

map{say}/(?=([aeiou]{$.}))/g while$.++<y///c

Try it online!

Xcali
quelle
1

05AB1E, 10 bytes

Œʒg≠}ʒžMм_

Try it online!

Explanations:

Œʒg≠}ʒžMм_  
Π           Push all substrings (abeoic => a, b, e, ..., eoi, eoc, ... abeioc)
 ʒ  }        Filter elements for which result is 1
  g≠            Push 1 if length is != 1, 0 otherwise
     ʒ       Filter elements for which result is 1
      žMм       Remove all occurences of 'aeiou' from element
         _      Negative bool: push 1 if length == 0, 0 otherwise
scottinet
quelle
Nice answer! I had ŒʒžMм_}ʒg≠
Mr. Xcoder
@Mr.Xcoder Thanks. I also had ŒD1ùKʒžMм_ for 10 bytes. I'm trying to find a way to golf it down though
scottinet
1

C, 105 75 bytes

A function accepting a pointer to lowercase input, and producing space-separated strings on standard output:

i;f(char*p){for(i=strspn(p,"aeiou");i>1;)printf("%.*s ",i--,p);*p&&f(p+1);}

Test program

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 1;  i < argc;  ++i) {
        char *in = argv[i];
        printf("'%s' -> [ ", in);
        f(in);
        puts("]");
    }
}

Demo

'r67^^()*6536782!87' -> [ ]
'programming puzzles and code golf' -> [ ]
'aaand... i won!' -> [ aaa aa aa ]
'abeoic' -> [ eoi eo oi ]
'yah eioo ala' -> [ eioo eio ei ioo io oo ]
'@yabeeeayio__e' -> [ eeea eee ee eea ee ea io ]
'0ioen0aaiosnjksd' -> [ ioe io oe aaio aai aa aio ai io ]

Explanation

#include <string.h>
#include <stdio.h>

void find_polyphthongs(char *p)
{
    /* from longest polyphthong substring down to 2 */
    for (int i = strspn(p,"aeiou");  i >= 2;  --i) {
        /* print exactly [p .. p+i] */
        printf("%.*s ", i, p);
    }

    /* tail-recurse to next char */
    if (*p) {
        find_polyphthongs(p+1);
    }
}

Using GCC on Debian Linux, I seem to get away with the incompatible implicit declarations of strchr() and printf(). Other platforms may require <stdio.h> and <string.h> to be included.

Try it online (requires Javascript).

Toby Speight
quelle
Can f(p)char*p; not be f(char*p)?
Jonathan Frech
Quite right - I originally had output to caller-allocated storage: f(s,d)char*s,*d.
Toby Speight
102 bytes.
Jonathan Frech
1

APL (Dyalog), 53 bytes

This is a Dfn (direct function). Usage is p '<argument>'. Fair warning: this is not very efficient and times out for input > 8 characters on TIO, but works normally when given enough time.

p←{(G∊⊃,/⌽,\∘⌽¨,\⌽⍵)/G←⊃,/{(,v∘.,⊢)⍣⍵⊢v'aeiou'}¨⍳≢1↓⍵}

Try it online!

Thanks to @Adám for 16 bytes!

How it works:

This is easier to understand if we break the code in smaller portions:

  • Part 1 - G←⊃,/{(,v∘.,⊢)⍣⍵⊢v←'aeiou'}¨⍳≢1↓⍵: This part of the function takes the length of the (right) argument and mixes the vector aeiou to itself that many times, yielding every possible combination of [2, length(right arg)] vowels.
  • Part 2 - (G∊⊃,/⌽,\∘⌽¨,\⌽⍵)/: This part checks which element(s) of G are members of the substrings of the input. This returns a boolean vector, with 1's at the indices of the vowel combinations that are present in the input and 0's where they're not. The resulting vector is then mapped (/) over G, returning the elements corresponding to the truthy values.

The whole thing is then assigned to p. p← is not included in the byte count because it's not necessary, it just makes using the function easier.

J. Sallé
quelle
Golfed further. Also, you shouldn't use to filter. Use /.
Adám
1

Haskell, 74 bytes

f[]=[]
f(h:t)=filter(all(`elem`"aeiou"))[h:take i t|i<-[1..length t]]++f t

Try it online!

totallyhuman
quelle
1

Ruby 2.4, 100 bytes

(2..(b=(a=gets).size-1)).to_a.flat_map{|i|(0..(b-i)).to_a.map{|j|a[j,i]}}.select{|k|k=~/^[aeiou]+$/}

This is my first attempt at golfing, and I'm sure there are lots of ways to shorten this code.

Alex
quelle
0

Ruby, 80 bytes

->s{[*0..z=s.size-2].product([*2..z]).map{|v|s[*v][/[aeiou]{2,}/]}.uniq.compact}

Try it online!

Reinstate Monica iamnotmaynard
quelle
.compact can be -[nil]
Snack
0

Pyth, 15 bytes

f&tT!-T"aeoi".:

Try it online!

Definitely golfable, I want to get it better before writing out explanation.


Dave
quelle
0

T-SQL (SQL Server 2014), 281 bytes

;with s as(select substring(@,1,1)C,stuff(@,1,1,'')D,1 R union all select substring(D,1,1),stuff(D,1,1,''),R+1from s where len(D)>0),c as(select R i,C w from s where C LIKE'[aeiou]'union all select R,w+C from c join s ON i+1=R where s.C LIKE'[aeiou]')select w from c where len(w)>1

Input give by

declare @ varchar(max) = 'abeoic'

Uses a common table expression s to blow the input apart into ordered individual letters, and then a second common table expression c to generate all ordered combinations, throwing out non vowels.

SQL Fiddle

Brian J
quelle
0

PHP, 139 bytes

function y($s){$p=[];$l=strlen($s);for($i=2;$i<=$l;$i++)for($j=0;$j<=$l-$i;$j++)strspn($a=substr($s,$j,$i),'aeiou')==$i&&$p[]=$a;return$p;}

Online demo

function yreadable($s)
{
    $p = [];
    $l = strlen($s);
    for($i=2; $i<=$l; $i++)
        for($j=0; $j<=$l-$i; $j++)
            strspn($a=substr($s,$j,$i),'aeiou')==$i
            && $p[] = $a;
    return $p;
}

How it works

Select sub-strings (beginning with the length of 2) consisting of adjacent characters and move along string. Collect any sub-strings that only contain vowels. Repeat with longer sub-strings.

For string 'abcdef' these are the substrings generated and checked:

'ab','bc','cd','de','ef'
'abc','bcd','cde','def'
'abcd','bcde','cdef'
'abcde','bcdef',
'abcdef'
Progrock
quelle