John has invited some friends. His list is:
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
Could you make a program that:
-makes this string uppercase
-gives it sorted in alphabetical order by last name
When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.
So the result of function meeting(s)
will be:
"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
It can happen that in two distinct families with the same family name two people have the same first name too.
Today's challenge comes from g964 on CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (11)
Lets do it:
It's pretty straightforward:
split(';')
gets us allName:Surname
.map(n=>n.split(':').reverse().join(':'))
reverses them to beSurname:Name
.sort()
sorts them alphabetically.map(n=>
(${n.split(':')[0]}, ${n.split(':')[1]}).toUpperCase())
reformats every name (uppercase it, place parentheses and commas).join('')
, which transforms the name array to an output stringHere is the output:
Same but different:
You don't need the arbitrary
join(':')
afterreverse()
sincesort()
coerces the nested arrays to strings for you. That means you can avoid having to split again later.But Amin is right:
That's way shorter! Thanks a lot for the input
I see we got a similar solution you and I!
I think you can even shorten (if I'm not mistaken) your solution by reducing one
.map
down and doing like me the surrounding in your first call to the.map
method!Should such a
.surround
method exist inString.prototype
? I have came accross several cases where I would need it like in a WYSIWYG editor. But I don't want to risk proposing such a method to the community haha!Good take btw!
Not much of a challenge, I'm afraid. Pretty straight forward split, split, join, sort and join again. A one liner in most modern languages, I suspect.
In c# it would look like this:
Rust:
My take at the challenge written in Elm
Source-Code
Unit test source-code
Perl solution:
Anyone who says rex is too clever clearly hasn't bumped into bit-shifting code-golf lol
Rex is a very appropriate amount of cleverness 😉
Clever use of the regex split. I like it!