19
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Sorry for the temporary deletion! \$\endgroup\$ – Mr. Xcoder Jun 16 '17 at 16:40
  • 6
    \$\begingroup\$ 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. \$\endgroup\$ – Marc.2377 Jun 17 '17 at 4:56
  • 2
    \$\begingroup\$ @Mr.Xcoder: Please add a test case with uppercase vowels. Thanks! \$\endgroup\$ – nimi Jun 18 '17 at 8:10
  • \$\begingroup\$ @nimi Added. It's just the same algorithm, no matter the case. \$\endgroup\$ – Mr. Xcoder Jun 18 '17 at 12:47
  • 1
    \$\begingroup\$ @Mr.Xcoder: yes, but at least two answer got it wrong (both fixed now). \$\endgroup\$ – nimi Jun 18 '17 at 15:08

26 Answers 26

7
\$\begingroup\$

Haskell, 59 bytes

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
\$\endgroup\$
6
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ This is surprisingly readable... Can you add some words on how it works? \$\endgroup\$ – Mr. Xcoder Jun 16 '17 at 16:55
  • \$\begingroup\$ 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. \$\endgroup\$ – nmjcman101 Jun 16 '17 at 17:03
  • \$\begingroup\$ @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. \$\endgroup\$ – DJMcMayhem Jun 16 '17 at 17:16
  • \$\begingroup\$ 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? \$\endgroup\$ – CAD97 Jun 16 '17 at 18:26
  • \$\begingroup\$ @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/… \$\endgroup\$ – DJMcMayhem Jun 16 '17 at 18:29
5
\$\begingroup\$

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"
\$\endgroup\$
4
\$\begingroup\$

Perl 6, 57 bytes

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

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.
\$\endgroup\$
4
\$\begingroup\$

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"

\$\endgroup\$
4
\$\begingroup\$

Perl 5, 47 bytes

45 bytes code + 2 for -pa.

map$\=$_.$\,(/./g)[0..lc=~y/aeiou//-1]for@F}{

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Does it work with upper case vowels, e.g. "Alabama"? \$\endgroup\$ – nimi Jun 18 '17 at 8:05
  • \$\begingroup\$ @nimi oooh, didn't think about that, updated for +1. \$\endgroup\$ – Dom Hastings Jun 18 '17 at 9:58
3
\$\begingroup\$

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'),
    f('Go Cat Print Pad')
)

\$\endgroup\$
  • \$\begingroup\$ Words with no vowels (Thx) should have no output; your test case outputs the whole word. \$\endgroup\$ – Justin Mariner Jun 16 '17 at 20:58
  • \$\begingroup\$ @JustinMariner Fixed! \$\endgroup\$ – darrylyeo Jun 16 '17 at 22:36
3
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ @DigitalTrauma: I just added an explanation \$\endgroup\$ – Maria Jun 17 '17 at 2:15
  • 1
    \$\begingroup\$ @ - intersection is much better than regex here. Oh, I see - you just have one lambda/map compared to my 2. \$\endgroup\$ – Digital Trauma Jun 17 '17 at 2:19
3
\$\begingroup\$

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

Online test.

                             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
\$\endgroup\$
  • \$\begingroup\$ > I feel like there is probably a better approach -- I got 19 in Pyth \$\endgroup\$ – Maria Jun 17 '17 at 2:07
  • 1
    \$\begingroup\$ @Svetlana there I fixed it. Thanks for the jk tip. \$\endgroup\$ – Digital Trauma Jun 17 '17 at 3:50
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ @nimi It does now. \$\endgroup\$ – Value Ink Jun 18 '17 at 8:19
  • \$\begingroup\$ Just curious, why is -p worth a byte? \$\endgroup\$ – Eric Duminil Jun 18 '17 at 14:18
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – Dom Hastings Jun 19 '17 at 6:48
3
\$\begingroup\$

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.
\$\endgroup\$
  • \$\begingroup\$ 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...) \$\endgroup\$ – ETHproductions Jun 16 '17 at 17:11
  • \$\begingroup\$ 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 ;) \$\endgroup\$ – ETHproductions Jun 16 '17 at 17:13
  • \$\begingroup\$ @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 \$\endgroup\$ – Shaggy Jun 16 '17 at 17:17
2
\$\begingroup\$

Jelly, 12 bytes

ḲµfØcLḣ@µ€FU

Try it online!

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 14 bytes

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

Try it online!

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Wait... 05AB1E beaten by Japt? \$\endgroup\$ – Mr. Xcoder Jun 16 '17 at 17:28
  • \$\begingroup\$ @Mr.Xcoder Happens more often than you probably think. \$\endgroup\$ – Erik the Outgolfer Jun 16 '17 at 17:28
  • 1
    \$\begingroup\$ #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 ʒ \$\endgroup\$ – Magic Octopus Urn Jun 16 '17 at 18:56
  • \$\begingroup\$ @carusocomputing Unfortunately output must be case-sensitive. \$\endgroup\$ – Erik the Outgolfer Jun 17 '17 at 8:04
2
\$\begingroup\$

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]}]])&
\$\endgroup\$
  • \$\begingroup\$ I am not really familiar with Mathematica, but can't the space between s[[i]]], and {i,Length@s} be removed? \$\endgroup\$ – Mr. Xcoder Jun 16 '17 at 17:22
  • \$\begingroup\$ yes of course, I missed that. I must golf it more, too \$\endgroup\$ – J42161217 Jun 16 '17 at 17:32
  • \$\begingroup\$ Is there a way to cast a string to a list in Mathematica? Something like "aeiouAEIOU".ToCharArray()? \$\endgroup\$ – caird coinheringaahing Jun 16 '17 at 20:14
  • \$\begingroup\$ you mean Characters[]? \$\endgroup\$ – J42161217 Jun 16 '17 at 20:30
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

PHP, 96 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 83 81 79 77 bytes

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

Try it online!

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

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!

\$\endgroup\$
  • \$\begingroup\$ Java supports (?i) for ignoring case in regexs. So (?i)[aeiou] should also work. \$\endgroup\$ – Lukas Rotter Jun 18 '17 at 14:39
  • \$\begingroup\$ You can also remove the {} brackets of the for loop, since only one statement is contained in it. \$\endgroup\$ – Lukas Rotter Jun 18 '17 at 15:05
  • \$\begingroup\$ 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()); \$\endgroup\$ – Lukas Rotter Jun 18 '17 at 15:43
1
\$\begingroup\$

k, 33 bytes

{|,/(+/'-1<"aoeui"?/:_x)#'x}@" "\

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
  • 2
    \$\begingroup\$ 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! \$\endgroup\$ – Mr. Xcoder Jun 17 '17 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.