Swift, 134 bytes
var c = NSCountedSet(),n = ""
i.characters.forEach({var s = String($0);c.addObject(s);for _ in 0..<c.countForObject(s){n.append($0)}})
Assumes Foundation has been implicitly imported. i
is the input of type String
, n
is the output of type String
.
I'm falling back on Foundation classes here as NSCountedSet
gives the the character count lookup behavior we want. The problem with mixing Swift and Objective-C types is that Swift structs do not conform to NSObjectProtocol
. We see this issue when trying to store a Swift Character
(String.CharacterView
) in an NSCountedSet
, which is expecting objects of type AnyObject
(or NSObject
). I lose around 17 bytes having to create a String
from each Character
in the input string.
I also lose some bytes having to create a for
loop to append the new characters based on their count in the set. I can't use forEach
here since the return type of countForObject
is an Int
, not a collection type. There is room for improvement here.
Swift String
types are immutable, so I can't explicitly mutate the input. There may be room for improvement by using an NSMutableString
, but the characters lost by explicitly declaring the input of that type and calling the appendString
method may add more characters to the program.
21Well then... rip Pyth. – Adnan – 2016-04-04T14:16:17.270
2This site is becoming a competition for the best general-purpose golfing language... not that that's a bad thing. – Shelvacu – 2016-04-04T23:34:52.083
8@shelvacu The latter is debatable, 2 friends I've shown PPCG to have said something along the lines of "all the top answers are just using golf languages" as a first impression. – Insane – 2016-04-05T06:37:20.673
@Insane there is/ are. Code golf is a pretty common thing. So languages are put together for that purpose, exclusively. – Evan Carslake – 2016-04-06T23:53:04.590
How does this.... work? – Erik the Outgolfer – 2016-10-04T15:22:50.330