-2
\$\begingroup\$

Guidelines

Task

Write a function that takes in a sentence (a string, or list of characters) and reverses all the words that are greater than or equal to 5 in length.


Examples

"Hey fellow code golfers" -> "Hey wollef code sreflog"

"I aM noT a cAr" -> "I aM noT a cAr"

"I Am a tRaiN" -> "I Am a NiaRt"


Rules

  • Since this is code golf, the person with the least amount of bytes as their answer wins.

  • The input will have only one space between two adjacent words and there will be no trailing or leading spaces.

  • The output must also only have one space between two adjacent words and no trailing or leading spaces.

  • You can assume that the input will either be a string, or an array of characters. It WILL NOT be an array of words.

  • You must output either a string, or an array of characters. You MUST NOT output an array of words.

  • Words with punctuation marks can be seen as 5 or 4 letters, whichever you want

  • Capitalisation should stay the same for the same letters

\$\endgroup\$
  • \$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$ – Martin Ender Feb 20 '18 at 9:10

24 Answers 24

6
\$\begingroup\$

Jelly,  12 10 8  7 bytes

-1 thanks to dylnan (use of repeat, ¡, as a replacement of if, ?, saving the need for identity, ¹.)

ḲṚṫ¡€5K

A monadic link taking and returning lists of characters.

Try it online!

How?

ḲṚṫ¡€5K - Link: list of characters
Ḳ       - split at spaces (gets words)
     5  - literal five
    €   - for €ach word:
   ¡    -   repeat:
  ṫ     -   ...number of times: tail (5th character on, if empty falsey->0, else truthy->1)
 Ṛ      -   ...action: reverse
      K - join with spaces

Previous 8: ḲṚ¹ṫ?€5K

Previous 10: ḲµṚ¹ṫ?5µ€K

Previous 12s: ḲµUµL€>4Tµ¦K and ḲµṚ¹L>¥?4µ€K

\$\endgroup\$
  • 1
    \$\begingroup\$ 7 bytes. Also nice trick with and putting €5 on the right side of ? I didn't realize you could do that \$\endgroup\$ – dylnan Feb 17 '18 at 23:12
  • \$\begingroup\$ Oh and I never knew that would work; thanks! \$\endgroup\$ – Jonathan Allan Feb 17 '18 at 23:57
6
\$\begingroup\$

Retina, 10 8 bytes

2 bytes saved thanks to @ETHproductions

V`\w{5,}

Try it online!

  \w{5,}     match 5 or more characters long strings
V`           reverse each match and insert in place
\$\endgroup\$
  • 2
    \$\begingroup\$ And we had such a nice chain going :( \$\endgroup\$ – ETHproductions Feb 17 '18 at 21:32
  • \$\begingroup\$ Nice! I think it will be tricky to beat this. \$\endgroup\$ – Amorris Feb 17 '18 at 21:35
  • 1
    \$\begingroup\$ Yep, this is close to optimal for any language. But why do you need the \b? \$\endgroup\$ – ETHproductions Feb 17 '18 at 21:36
  • \$\begingroup\$ @ETHproductions I don't, thanks. Residue from the * mistake \$\endgroup\$ – Uriel Feb 17 '18 at 21:38
4
\$\begingroup\$

brainfuck, 123 bytes

,[[>++++[-<-------->]<[[-<+>]++++[-<++++++++>]>,>]<]<[>]<<<<<[[>]<[.<]>[>]]>>>>[[<]>[.>]]>>>>>,[>++++[->++++++++<]>.[-]]<<]

Try it online!

Most of this is just creating the ASCII value for space (32) 3 times, which is 51 bytes, or 41.4% of the total bytecount.

An attempt to only create one cell with 32 at the beginning and use that (124 bytes):

++++[->++++++++<],[[>[-<-<+>>>+<]<[[-<+>]>,>>>>]<[[-]>>>>]<<<]>>[-<+>]<<<<<<<<[[>]<[.<]>[[-]>]<<]>>>>[[<]>[.[-]>]]>,[>.>]<<]
\$\endgroup\$
  • 1
    \$\begingroup\$ Earned an upvote for doing it in BF. \$\endgroup\$ – Amorris Feb 17 '18 at 23:56
  • \$\begingroup\$ Having posted my first brainfuck answer a couple of weeks ago, I have great respect for this. I'm sure I can learn a lot by these examples. Great effort. \$\endgroup\$ – ElPedro Feb 18 '18 at 22:31
4
\$\begingroup\$

JavaScript (ES6), 60 bytes

-57 bytes, w/ help from @Amorris, @Oliver, @Shaggy

s=>s.split` `.map(w=>w[4]?[...w].reverse().join``:w).join` `

My first ever codegolf submission!

\$\endgroup\$
  • 3
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Steadybox Feb 17 '18 at 23:44
  • \$\begingroup\$ Welcome to PPCG! One thing I can see right off the bat to remove 2 bytes is the brackets around s, when you are passing the input to the f arrow function. That is not needed unless you have two variables to input. \$\endgroup\$ – Amorris Feb 17 '18 at 23:55
  • \$\begingroup\$ You can replace w.split('') with [...w] and .join(' ') & .join('') can be replaced with backticks .join` ` .join`` \$\endgroup\$ – Oliver Feb 18 '18 at 1:41
  • \$\begingroup\$ Why are you using a when you're already mapping over s? Also, the () around the length check are unecessary. \$\endgroup\$ – Shaggy Feb 18 '18 at 12:18
  • \$\begingroup\$ Thanks for the advice everyone, I've just made some changes. Thanks for the warm welcome too! \$\endgroup\$ – healeycodes Feb 18 '18 at 12:41
3
\$\begingroup\$

QuadR, 10 bytes

\w{5,}
⌽⍵M

Try it online!

\w{5,}   match 5 or more characters long strings
         and replace
 ⍵M      each match
⌽        with its reverse
\$\endgroup\$
  • \$\begingroup\$ Got an upvote for using a language I hadn't even heard of before! \$\endgroup\$ – Amorris Feb 17 '18 at 23:55
3
\$\begingroup\$

Haskell, 50 49 bytes

f s|s>take 4s=reverse s|1<2=s
unwords.map f.words

Try it online!

Edit: -1 byte thanks to @totallyhuman.

\$\endgroup\$
  • \$\begingroup\$ 49 bytes. (words that are greater than or equal to 5 in length) \$\endgroup\$ – totallyhuman Feb 18 '18 at 1:45
3
\$\begingroup\$

Python 2, 56 51 49 bytes

-3 bytes thanks to Jonathan Allan
-2 bytes thanks to Mr. Xcoder
-2 bytes thanks to ElPedro

for w in input().split():print w[::len(w)<5or-1],

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Save three moving to Python 3 and a full program \$\endgroup\$ – Jonathan Allan Feb 17 '18 at 22:29
  • \$\begingroup\$ You can use [::len(w)<5or-1] for -2 bytes. \$\endgroup\$ – Mr. Xcoder Feb 18 '18 at 6:44
  • \$\begingroup\$ 49 by going back to Python 2 and using a standard for loop \$\endgroup\$ – ElPedro Feb 18 '18 at 8:14
  • \$\begingroup\$ @Mr.Xcoder - as hard as I try I can't figure out why len(w)<5or-1 works. Any chance you can explain? \$\endgroup\$ – ElPedro Feb 18 '18 at 12:51
  • 2
    \$\begingroup\$ @ElPedro In Python, bools are subclasses of integers. Namely, len(w)<5 returns either True - which is equivalent to 1 - or False - which is equivalent to 0. In case this condition is true (the length is less than 5), len(w)<5or-1 evaluates to 1, so w[::len(w)<5or-1] gives w[::1], which returns the string unchanged. In case the condition is false, then len(w)<5or-1 is equivalent to 0 or -1, which yields -1 because 0 is falsy, and therefore w[::len(w)<5or-1] is the same as w[::-1], which takes every element from the end of the string (i.e. it reverses it). \$\endgroup\$ – Mr. Xcoder Feb 18 '18 at 12:56
2
\$\begingroup\$

Japt, 11 bytes

Saved a byte thanks to @Shaggy

®Ê<5?Z:Zw}S

Try it online!

Explanation

®        }S    Split on spaces and map each word Z through this function:
 Ê<5             If the length of Z is less than 5,
    ?Z             return Z unchanged.
      :Zw        Otherwise, return Z reversed.
               The words are then re-joined on spaces and sent to output.

Japt v2, 11 bytes

r/\w{5,}/_w

Test it online!

Thought of this just before the Retina answer was posted. Replaces each match of /\w{5,}/g with the match reversed.

\$\endgroup\$
  • \$\begingroup\$ Fun fact: this would be 7 bytes according to the current feature plan for v2: r»ẉ⁵⁻_w \$\endgroup\$ – ETHproductions Feb 17 '18 at 21:48
  • \$\begingroup\$ If only there were a shortcut for l , your second solution could be 11 bytes too! ;) \$\endgroup\$ – Shaggy Feb 17 '18 at 22:07
  • \$\begingroup\$ @Shaggy ...I'm a moron sometimes :P \$\endgroup\$ – ETHproductions Feb 17 '18 at 22:32
2
\$\begingroup\$

C,  105  104 bytes

Thanks to @ceilingcat for saving a byte!

i,k;f(char*s){for(i=0;s[k=i]>32;)++i;for(;i>4&&k--;)putchar(s[k]);~k&&write(1,s,i+=k=!!s[i]);k&&f(s+i);}

Try it online!

Unrolled:

i, k;
f(char*s)
{
    for (i=0; s[k=i]>32;)
        ++i;

    for (; i>4&&k--;)
        putchar(s[k]);

    ~k && write(1, s, i+=k=!!s[i]);
    k && f(s+i);
}
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 12 bytes

ð¡εDg4›iR]ðý

Try it online!

Explanation

ð¡             # split on spaces
  ε      ]     # apply to each word
   D           # duplicate
    g          # length
     4›        # greater than 4
       iR      # if true, reverse
          ðý  # join by space
\$\endgroup\$
1
\$\begingroup\$

><>, 63 53 43 bytes

i>::48*=$0(+?v
6ov!?lr?(5l~ <.1
*^>i:0(?;48

Try it online!

10 20 bytes saved thanks to Jo King!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can save bytes by doing either 48* or " " instead of 3a*2+ \$\endgroup\$ – Jo King Feb 18 '18 at 1:42
  • 1
    \$\begingroup\$ Also the 6 on the second line should be a 5. You might be able to save bytes by just wrapping around on the second line, rather than going to a fourth \$\endgroup\$ – Jo King Feb 18 '18 at 1:50
  • \$\begingroup\$ Woah, yeah, guess I was more tired than I realized while making this. Thanks! \$\endgroup\$ – hakr14 Feb 18 '18 at 17:12
  • 1
    \$\begingroup\$ 43 bytes \$\endgroup\$ – Jo King Feb 18 '18 at 21:44
1
\$\begingroup\$

Python, 74 69 Bytes

def f(a):print' '.join([i if len(i)<5else i[::-1]for i in a.split()])

Edit: -5 thanks to @ElPedro

\$\endgroup\$
  • 1
    \$\begingroup\$ 69 (TIO) - print instead of return, Python splits on space by default (don't need ' ') and lose the space between 5 and else. \$\endgroup\$ – ElPedro Feb 18 '18 at 10:43
0
\$\begingroup\$

C (gcc), 152 125 bytes

j;f(char*S){for(char*Z,s;*S;S=Z+!!*Z){for(Z=S;*Z&&*Z-32;Z++);if(Z-S>4)for(j=0;--j*2>S-Z;s=Z[j],Z[j]=Z[S-Z+~j],Z[S-Z+~j]=s);}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl, 22 bytes

Includes +1 for p

perl -pe 's/\w{5,}/reverse$&/eg' <<< "Hey fellow code golfers"
\$\endgroup\$
0
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 132 119 bytes

 s =input
s s arb . x (' ' | rpos(0)) rem . s
 x =gt(size(x),5) reverse(x)
 o =o x differ(s) ' ' :s(s)
 output =o x
end

Try it online!

\$\endgroup\$
0
\$\begingroup\$

JavaScript, 69 66 bytes

s=>s.split` `.map(i=>i.length>4?[...i].reverse().join``:i).join` `

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can replace i.split'' with [...i] \$\endgroup\$ – Oliver Feb 18 '18 at 1:36
  • \$\begingroup\$ w[4] is shorter than w.length>4. \$\endgroup\$ – Shaggy Feb 18 '18 at 10:13
0
\$\begingroup\$

Red, 98 bytes

f: func[a][parse a[any[copy n[to{ }| to end](if(length? n)> 4[n: reverse n]prin n)skip(prin{ })]]]

Try it online!

Ungolfed

f: func [a] [                         
    parse a [                            ; parse the argument on
        any [                            ; zero or more
            copy n [                     ; copy the matched substring to n 
                to { }                   ; scan to a space 
                | to end                 ; or to the end  
            ] 
            ( if (length? n) > 4 [       ; if the length of the match is bigger than 4 
                  n: reverse n           ; reverse the match  
              ]
            prin n)                      ; print the match   
            skip (prin { })              ; skip the space
        ]
    ]
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 53 bytes

An alternative, but slightly longer, method to the straightforward reversing of words of length ≥5, which Oliver beat me to.

s=>s.replace(/\S+/g,m=>[...m].sort(_=>!!m[4]).join``)

Try it online

\$\endgroup\$
0
\$\begingroup\$

Python 2, 53 bytes

for i in input().split():print i[::(-1,1)[len(i)<5]],

As far as I can see the , at the end does not leave a trailing space but please correct me if I am wrong.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Python 3, 67 65 bytes

lambda s:' '.join([c[::-1]if len(c)>4 else c for c in s.split()])
\$\endgroup\$
  • \$\begingroup\$ f= is not needed unless it is recursive. Saves 2. \$\endgroup\$ – ElPedro Feb 18 '18 at 19:51
0
\$\begingroup\$

Pyth, 20 bytes

VcwdI>lN4p+_Nd.?p+Nd

Try it online!

Vcwd          | for N in input().split(" "):
    I>lN4     |     if len(N)>4:
        p+_Nd |         print(N[::-1]+" ", end="")
    .?        |     else:
        p+Nd  |         print(N+" ", end="")
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 73 50 bytes

-23 bytes thanks to Shaggy and ETHproductions

s=>s.replace(/\w{5,}/g,x=>[...x].reverse().join``)

Test cases

let f =

s=>s.replace(/\w{5,}/g,x=>[...x].reverse().join``)

console.log(f("Hey fellow code golfers"))
console.log(f("I aM noT a cAr"))
console.log(f("I Am a tRaiN"))

\$\endgroup\$
  • \$\begingroup\$ You don't need to split on the spaces. \$\endgroup\$ – Shaggy Feb 18 '18 at 9:45
  • \$\begingroup\$ I think Shaggy means that the .split and .join are superfluous and can be removed, since /\w{5,}/ doesn't match spaces. (You will have to add the g flag though) \$\endgroup\$ – ETHproductions Feb 19 '18 at 2:08
0
\$\begingroup\$

Java 8, 131 bytes

s->s.join(" ",java.util.Arrays.stream(s.split(" ")).map(x->x.length()<5?x:new StringBuffer(x).reverse()+"").toArray(String[]::new))

Explanation:

Try it online.

s->                            // Method with String as both parameter and return-type
  s.join(" ",                  //  Join String-array with spaces:
      java.util.Arrays.stream( //   An Array-stream of:
        s.split(" "))          //    The input-String split by spaces
      .map(w->                 //     Mapped to:
           w.length()<5?       //      If the word is not of length 5:
            w                  //       Leave the word as is
           :                   //      Else:
            new StringBuffer(x).reverse()+"")
                               //       Reverse it
      .toArray(String[]::new)) //   And convert the Stream to a String-array for the join
\$\endgroup\$
0
\$\begingroup\$

Perl 5 + -p, 21 bytes

s/\S{5,}/reverse$&/eg

Try it online!

Replace (s///) all (/g) at least 5 ({5,}) non-whitespace (\S) by the evaluation (/e) of reverse$&/the reversed match.

\$\endgroup\$

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.