Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
Nice one!
If you replace the trim() with a substring(1) then it'll work with strings that have spaces in front and behind since you're reliably adding a single space to the front, none to the back.
See the warning here re thesplit('') call. Seems the recommended way now is [...string].
Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
#!/usr/bin/perlusev5.24;usestrict;usewarnings;useCarp;# Challenge says only letters and spaces, but this won't be pickysub reverse_over_4{my$string=shiftorcroak"Error: missing argument to function.";my$res=join"",map{(length($_)>4)?scalarreverse($_):$_}split/ /,$string;return$res;}print"Enter string: ";my$input=<STDIN>;chomp$input;sayreverse_over_4($input);
This one was fun! I decided to approach it from a slightly different angle by building a general-purpose when function that could be used to decide when to map to a value (vs return the original value) based on a condition... just for kicks :-)
Here's my go:
constwhen=(when=()=>false,fn=i=>i)=>(v,idx,arr)=>when(v,idx,arr)?(typeoffn==="function"?fn(v,idx,arr):fn):v;constreverseString=str=>Array.from(str).reverse().join("");constreverseWords=({inString="",ofLength=0}={})=>inString.split("").map(when(w=>w.length>=ofLength,reverseString)).join("");constgnirtS=reverseWords({inString:"one two three four",ofLength:5});
pubfnspin_words(input:&str)->String{input.split(" ").map(|word|{ifword.len()>=5{word.chars().rev().collect()}else{word.to_string()}}).collect::<Vec<String>>().join(" ")}#[cfg(test)]modtests{usecrate::*;#[test]fnit_works_for_words_shorter_than_4_chars(){assert_eq!(spin_words("Test"),"Test".to_string());assert_eq!(spin_words("Te"),"Te".to_string());assert_eq!(spin_words("ant"),"ant".to_string());assert_eq!(spin_words("lots of tiny word"),"lots of tiny word".to_string());}#[test]fnit_words_for_the_example(){assert_eq!(spin_words("Stop gninnipS My sdroW"),"Stop Spinning My Words".to_string());}#[test]fnit_words_with_space_padded_strings(){assert_eq!(spin_words(" Stop gninnipS My sdroW ")," Stop Spinning My Words ".to_string());}}
Senior undergraduate at IIT Gandhinagar, Developer of Crusta Browser and Truck programming language +other cool projects, GSoC 2018 participant under KDE
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();
19 yo student *and* a full-time developer.
Building with Rails currently, exploring new frontiers.
I enjoy functional programming, Linux, FOSS, refactoring and mentoring :)
defmoduleSpinnerdo@specspin(String.t())::String.t()defspin(sentence)doString.replace(sentence,~r/\w+/,fnword->ifString.length(word)>4doString.reverse(word)elsewordendend)endend"Please spin me around!"|>Spinner.spin()|>IO.puts()# => "esaelP spin me dnuora!"
fnreverse(input:&str)->String{letmutoutput=input.as_bytes().to_vec();reverse_in_place(&mutoutput);String::from_utf8(output).unwrap()}fnmain(){lettest="Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!";println!("{}",reverse(test));println!("{}",reverse(&reverse(test)));}
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"
Over decades of experience in Integration development.
Designed and deployed production-ready end-to-end architecture for Java EE, Spring Boot, and Microservices.
JS quickie
JavaScript
Using reduce to generate a string from the array, but then I have to use trim as I end up with a space at either end :-/
Live demo on CodePen.
Nice one!
If you replace the
trim()with asubstring(1)then it'll work with strings that have spaces in front and behind since you're reliably adding a single space to the front, none to the back.See the warning here re the
split('')call. Seems the recommended way now is [...string].And one that modifies a string inplace using C
Perl one-liner:
A bit more cleaned up, taking user input:
See runnable demo on PerlBanjo
Note that
($_)is not needed forlengthandreverse.Yeah, true, that's just my personal preference 🙂
Python one-liner:
for x in input().split(): print(x[::1]*(len(x)<5) or x[::-1], end=' ')65 chars at most :)
Or,
print(*map(lambda x: x[::1]*(len(x)<5)or x[::-1], input().split()))Also 65 at most :)
This one was fun! I decided to approach it from a slightly different angle by building a general-purpose
whenfunction that could be used to decide when to map to a value (vs return the original value) based on a condition... just for kicks :-)Here's my go:
Gist (w/ some tests): gist.github.com/kerrishotts/ac0f30...
Here is my Rust solution and test cases!
The Rust std lib made this one pretty simple!
Haskell, with user input
A quick one in C#
Elixir:
Rust, sort of in place
The rest of the story below the fold:
PHP 5.3.0 to 7.3.x:
PHP >= 7.4:
My solution in js
Ruby
Ruby
Tests
Results
Haskell:
Python 3 : :P
s='yadoT egnellahc semoc from user xDranik on sraWedoC!'
print(s[::-1])
JS/ES
function spinWords(string){
return string.split(' ').map(function(string){
return (string.length > 4) ? string.split('').reverse().join('') : string
}).join(' ');
}