# Make String Waves

Given a string as input, output the string with the following algorithm applied:

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"


## Specs

• You may take input and provide output by any standard form, and the only data type allowed for both Input and Output is your language's native String type. Taking input directly as a list of individual words is not permitted.

• You are guaranteed that there will be no consecutive spaces.

• The vowels are "a","e","i","o","u","A","E","I","O","U", but "y","Y" are not considered vowels.

• You are guaranteed that only letters and spaces will appear in the input, but without any newlines.

• Output must be case-sensitive.

• You are not guaranteed that each word contains a vowel. If no vowels appear in that word, you do not have to output anything for it.

## Test Cases

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"


## Scoring

The shortest valid submission for each language wins, this is . Good luck and have fun!

Sandbox for those who can see deleted posts.

• Sorry for the temporary deletion! Jun 16, 2017 at 16:40
• Don't know why I thought this was going to be a PCG about string (as in String Theory) waves (as in oscillations in a field). Maybe it's time to go sleep. Jun 17, 2017 at 4:56
– nimi
Jun 18, 2017 at 8:10
• @nimi Added. It's just the same algorithm, no matter the case. Jun 18, 2017 at 12:47
• @Mr.Xcoder: yes, but at least two answer got it wrong (both fixed now).
– nimi
Jun 18, 2017 at 15:08

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


Try it 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


# V, 31 bytes

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


Try it online!

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


And explanation:

Í               " 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

• This is surprisingly readable... Can you add some words on how it works? Jun 16, 2017 at 16:55
• I'm impressed with how often I see æ used, I seem to remember it being added very recently and it's one of the more useful commands. Jun 16, 2017 at 17:03
• @nmjcman101 Yeah, I totally agree. æ is extremely useful. I should have added it a long time ago. ø is also really nice, it's cool that this answer uses both. Jun 16, 2017 at 17:16
• It seems to work without the first | (Try it online!), which is not in your explanation. But I don't know V; is it needed? Jun 16, 2017 at 18:26
• @CAD97 Ah, I did miss that in my explanation. That does work for all of the test cases, but it breaks when there are 10 or more vowels in a word (because <C-a> puts the cursor at the end of the word). tio.run/##K/v//3Cvgv7hTVyHNx1uObzj8OLoxNTM/… Jun 16, 2017 at 18:29

# Brachylog, 17 bytes

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


Try it online!

### Explanation

That's a direct translation of the problem:

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"


# Perl 5 + -p040F, 35 bytes

$\=$_.$\for@F[0..lc=~y/aeiou//-1]}{  Try it online! • Does it work with upper case vowels, e.g. "Alabama"? – nimi Jun 18, 2017 at 8:05 • @nimi oooh, didn't think about that, updated for +1. Jun 18, 2017 at 9:58 # Perl 6, 57 bytes {flip [~] .words.map:{.substr(0,.comb(rx:i/<[aeiou]>/))}}  ## Alice, 32 bytes /.'*%-.m"Re.oK" \iu &wN.;aoi$u@/


Try it online!

### Explanation

/....
\...@/


This is just a framework for linear code in Ordinal (string-processing mode). Unfolding the program, we get:

i' %w.."aeiou".u*&-Nm;Ro.$K@  Here's what it does: 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.


## JavaScript (ES6), 76 bytes

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


### Test cases

let f =

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

console.log(f(""                                 )) // -> ""
console.log(f("Hello World"                      )) // -> "WeH"
console.log(f("Waves"                            )) // -> "aW"
console.log(f("Programming Puzzles and Code Golf")) // -> "GoCauPorP"
console.log(f("Yay Got it"                       )) // -> "iGY"
console.log(f("Thx for the feedback"             )) // -> "eeftf"
console.log(f("Go Cat Print Pad"                 )) // -> "PPCG"

# Ruby, 54 59+1 = 55 60 bytes

Uses the -p flag for +1 byte.

$_=$_.split.map{|w|w[0,w.count("aeiouAEIOU")]}.join.reverse


Try it online!

• @nimi It does now. Jun 18, 2017 at 8:19
• Just curious, why is -p worth a byte? Jun 18, 2017 at 14:18
• @EricDuminil See this meta post but basically, because ruby -pe '...' is only one more byte than ruby -e '...' and -e is a valid way to execute the script. Jun 19, 2017 at 6:48

# Japt v2.0a0, 12 10 bytes

¸®¯Zè\vÃ¬w


Try it

## Explanation

Pretty much does exactly what the spec describes!

        :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.

• Good thing I checked the existing answers before writing my own :P Nice one, I don't think it will get any shorter (though of course I could be wrong...) Jun 16, 2017 at 17:11
• Aside: in Japt 2.0 you could theoretically change "%v" to \v (a single-class regex literal, equivalent to /\v/). Not helpful yet, of course, since I haven't implemented v2.0 yet ;) Jun 16, 2017 at 17:13
• @ETHproductions, I was getting ready to run out the door when this challenge popped up so I just wrote it up quickly, taking it literally. There might be a shorter way to do it less literally, maybe? Those changes to the RegEx will be handy for saving a few bytes; looking forward to them Jun 16, 2017 at 17:17

# JavaScript (ES6), 96 bytes

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


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

console.log(
f(''),
f('Hello World'),
f('Waves'),
f('Programming Puzzles and Code Golf'),
f('Yay Got it'),
f('Thx for the feedback'),
)

• Words with no vowels (Thx) should have no output; your test case outputs the whole word. Jun 16, 2017 at 20:58
• @JustinMariner Fixed! Jun 16, 2017 at 22:36

# Python 3, 838179 77 bytes

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


Try it online!

• 81 bytes Jun 16, 2017 at 17:02
• change to python 2 and you don't need the () for print Jun 16, 2017 at 18:10
• @Griffin In Python 2, you would need raw_input() instead of input() which would waste 4 bytes. Jun 16, 2017 at 18:44
• @Mr.Xcoder why can't you just input with quotes? Jun 16, 2017 at 18:48
• @Griffin Ah, right. That would eventually save 2 bytes. Jun 16, 2017 at 18:50

# Pyth - 19 bytes

_jkm<dl@"aeiou"rd0c


Try it here

Explanation:

_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)


I could have 18 bytes if not for the empty string:

_sm<dl@"aeiou"rd0c

• @DigitalTrauma: I just added an explanation Jun 17, 2017 at 2:15
• @ - intersection is much better than regex here. Oh, I see - you just have one lambda/map compared to my 2. Jun 17, 2017 at 2:19

# Pyth, 31

This took me a long time to write, and I feel like there is probably a better approach, but here is what I have:

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

                             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

• > I feel like there is probably a better approach -- I got 19 in Pyth Jun 17, 2017 at 2:07
• @Svetlana there I fixed it. Thanks for the jk tip. Jun 17, 2017 at 3:50

# Ohm, 13 bytes

z:αv_K_σh;0JR


## Explanation

• First the (implicit) input is split on spaces by z.
• Then a foreach loop is started (:) with it's associated codeblock being αv_K_σh.
• av pushes aeiou
• _ pushes the current iterated element
• K counts the occurrences of aeiou in _
• _ the element again
• σh Splits the element into slices of length occurences and takes the first element.
• Effectively this takes the first occurences chars
• 0J Pushes the stack joined on ''
• The 0 is necessary because it requires an argument that will be joined. If that argument isn't an array it joins the stack
• R reverses the result
• implicit print of the TOS

# Java 8, 171 151 bytes

-20 bytes thanks to @Lukas Rotter

I feel like it still needs some golfing... let me know in the comments if you have any suggestions.

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


Try it online!

• Java supports (?i) for ignoring case in regexs. So (?i)[aeiou] should also work. Jun 18, 2017 at 14:39
• You can also remove the {} brackets of the for loop, since only one statement is contained in it. Jun 18, 2017 at 15:05
• Instead of subtracting the length of the regex string you can also just use ^ to find the amount of vowels: z+=w.substring(0,w.replaceAll("(?i)[^aeiou]","").length()); Jun 18, 2017 at 15:43

# Vyxal, 10 bytes

⌈ƛk∨↔LẎ;∑Ṙ


Try it Online!

⌈          # Split on spaces
ƛ     ;   # Map...
↔      # Remove characters not in...
k∨       # 'aeiouAEIOU'
L     # Get the length of that
Ẏ    # Get that many characters of the original string
∑  # Concatenate all of them
Ṙ # Reverse the whole thing


# Jelly, 12 bytes

ḲµfØcLḣ@µ€FU


Try it online!

# 05AB1E, 14 bytes

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


Try it online!

Darn 05AB1E doesn't have builtin for AEIOUaeiou ಠ_ಠ

• Wait... 05AB1E beaten by Japt? Jun 16, 2017 at 17:28
• @Mr.Xcoder Happens more often than you probably think. Jun 16, 2017 at 17:28
• #RʒDlžMÃg£R? for 12, you can pretty much just lowercase the dupe removing the need for AEIOUaeiou. Also, why the heck wont this work without the ?? Can you post an explanation, I'm unfamiliar with ʒ Jun 16, 2017 at 18:56
• @carusocomputing Unfortunately output must be case-sensitive. Jun 17, 2017 at 8:04
• I know it has been 3 years, but there is a builtin for all vowels now: žÀ (It is aeiouAEIOU, not AEIOUaeiou) Oct 27, 2020 at 11:02

# Mathematica, 145 bytes

(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]}]])&

• I am not really familiar with Mathematica, but can't the space between s[[i]]], and {i,Length@s} be removed? Jun 16, 2017 at 17:22
• yes of course, I missed that. I must golf it more, too Jun 16, 2017 at 17:32
• Is there a way to cast a string to a list in Mathematica? Something like "aeiouAEIOU".ToCharArray()? Jun 16, 2017 at 20:14
• you mean Characters[]? Jun 16, 2017 at 20:30

# Retina, 49 46 bytes

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


Try it online! Link includes test suite. Explanation: This is an application of .NET's balancing groups. The lookahead searches the word for vowels, which are captured in group 2. The group is then popped as each letter is matched, thus capturing the number of letters equal to the number of vowels in the word. The rest of the word and any trailing space is then ignored so that the process can begin again with the next word. Finally the remaining letters are reversed.

# C# (.NET Core), 144 bytes

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


Try it online!

The worst part is that reversing a string in C# returns a IEnumerable<char> which you have to convert back to a string.

# PHP, 96 bytes

foreach(explode(" ",$argn)as$w)$r.=substr($w,0,preg_match_all("#[aeiou]#i",$w));echo strrev($r);


Try it online!

# Common Lisp, 218 bytes

(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)))))


Explanation

(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


# 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! ## 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. # 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!

• 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! Jun 17, 2017 at 21:59

# CJam, 26 bytes

qS/{_el"aeiou"fe=:+<}%:+W%


Try it online!

I was proud of coming up with the el"aeiou"fe=:+ snippet to count vowels.

# GolfScript, 33 bytes

" "/-1%{.{"aeiouAIUEO"?)},,<-1%}/


Try it online!

" "/                                # Split the words                          ["Hello" "World"]
-1%                             # Reverse the list                         ["World" "Hello"]
{                       }/   # For each word                            "World"         | "Hello"
.                           # Copy it                                  "World" "World" | "Hello" "Hello"
{              },          # List all letters that pass this test
"aeiouAIUEO"?)            # Is it a vowel?                           "World" ["o"]   | "Hello" ["e" "o"]
,         # Get the number of letters in the list    "World" 1       | "Hello" 2
<        # Get that many letters from the beginning "W"             | "He"
-1%     # Reverse it                               "W"             | "eH"
"WeH"


# k, 33 28 bytes

|,/{(+/~^"aeiou"?_x)#x}'" "\


Try it online!

-5 bytes thanks to coltim.

• Can save 5 bytes by doing |,/{(+/~^"aeiou"?_x)#x}'" "\ . A k4 version is |,/{(+/(_x)in"aeiou")#x}'" "\:. Oct 27, 2020 at 13:42

# Husk, 17 bytes

ṁS↑ṁ#¨aeıuAEIOU¨w


Try it online!

Even without a builtin, does pretty well.