DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #15 - Stop gninnipS My sdroW!

Good morning, everyone.
Let's warm up for the start of the week by playing with strings.

s'yadoT egnellahc semoc from user xDranik on sraWedoC!

Write a function that takes in a string of one or more words and returns the same string, but with all words with five letters or more reversed. Strings passed in will consist of only letters and spaces.

Be sure to keep the order of the words the same and only reverse the letters.

Good luck, yppaH gniedoc!


Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!

Latest comments (23)

Collapse
 
samarthtripathidesign profile image
Samarth Tripathi

function spinWords(string){
return string.split(' ').map(function(string){
return (string.length > 4) ? string.split('').reverse().join('') : string
}).join(' ');
}

Collapse
 
kvharish profile image
K.V.Harish

My solution in js

const reverseWords = sentence => sentence.split(' ')
                                         .map(word => word.length > 4 ? word.split('').reverse().join('') : word)
                                         .join(' ');
Collapse
 
scrabill profile image
Shannon Crabill

Ruby

def wordSpinner(string)
  string.split(" ").map do |word|
    if word.length >= 5
      word.reverse
    else
      word
    end
  end.join(" ")
end

Tests

wordSpinner("Everything small is just a smaller version of something big")
wordSpinner("Bad biscuits make the baker broke bro")
wordSpinner("Sometimes life is scary and dark")

Results

"gnihtyrevE llams is just a rellams noisrev of gnihtemos big"
"Bad stiucsib make the rekab ekorb bro" 
"semitemoS life is yracs and dark" 
Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell:

flipWords :: String -> String
flipWords = unwords . map (\w -> if length w > 4 then reverse w else w) . words
Collapse
 
p810 profile image
Payton Bice • Edited

PHP 5.3.0 to 7.3.x:

preg_replace_callback('/(\b\w{5,}\b)+/i', function ($match) {
    return strrev($match[0]);
}, 'Hello world, this is a test string.');

PHP >= 7.4:

preg_replace_callback('/(\b\w{5,}\b)+/i', fn($match) => strrev($match[0]), 'Hello world, this is a test string.');
Collapse
 
cssrajput profile image
Chandra Shekhar

Python 3 : :P

s='yadoT egnellahc semoc from user xDranik on sraWedoC!'
print(s[::-1])

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Rust, sort of in place

fn reverse_in_place(input: &mut [u8]) {
    input
        .split_mut(|&byte| byte == b' ')
        .filter(|word| word.len() >= 5)
        .for_each(<[_]>::reverse);
}

The rest of the story below the fold:

fn reverse(input: &str) -> String {
    let mut output = input.as_bytes().to_vec();
    reverse_in_place(&mut output);
    String::from_utf8(output).unwrap()
}

fn main() {
    let test = "Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!";
    println!("{}", reverse(test));
    println!("{}", reverse(&reverse(test)));
}

Collapse
 
prvnbist profile image
Praveen Bisht • Edited

JS/ES

const revWords = str => {
    return str
        .split(" ")
        .map(word => (word.length >= 5 ? [...word].reverse().join("") : word))
        .join(" ")
};
Collapse
 
brightone profile image
Oleksii Filonenko • Edited

Elixir:

defmodule Spinner do
  @spec spin(String.t()) :: String.t()
  def spin(sentence) do
    String.replace(sentence, ~r/\w+/, fn word ->
      if String.length(word) > 4 do
        String.reverse(word)
      else
        word
      end
    end)
  end
end

"Please spin me around!"
|> Spinner.spin()
|> IO.puts()

# => "esaelP spin me dnuora!"
Collapse
 
praneetnadkar profile image
Praneet Nadkar

A quick one in C#

 var input = Console.ReadLine().Split(' ');
 var output = new List<string>();
 foreach (var word in input)
 {
    if (word.Length <= 4)
    {
      output.Add(word);
      continue;
    }

    // word reversal. This can be done using inbuilt functions as well
    var wordArray = word.ToCharArray();
    var current = string.Empty;
    for (int i = word.Length - 1; i >= 0 ; i--)
    {
       current += wordArray[i];
    }

    output.Add(current);
 }

 Console.WriteLine(string.Join(" ", output));
 Console.ReadKey();