某 Python スレの書き込みを見ていてふと。
今のところ、これが一番スマート。
collection _ 'A <<<><<<>><<<><><<>><<<><<><<<>><<<><<>>>><><<>>< B' asOrderedCollection.
[collection includesAllOf: '<>'] whileTrue: [collection removeAll: '<>'].
^ String withAll: collection
"=> 'A <<<<<<<<<< B' "
大なり小なり部分だけを分離して、後で結合するタイプだと、ソートしていろいろできます。
tokens _ Scanner new scanTokens: 'A <<<><<<>><<<><><<>><<<><<><<<>><<<><<>>>><><<>>< B'.
string _ tokens second asString sort.
[string includesSubString: '<>'] whileTrue: [
string _ string copyReplaceAll: '<>' with: ''].
tokens at: 2 put: string.
^ String streamContents: [: s | tokens do: [: e | s nextPutAll: e] separatedBy: [s space]]
tokens _ Scanner new scanTokens: 'A <<<><<<>><<<><><<>><<<><<><<<>><<<><<>>>><><<>>< B'.
collection _ tokens second asSortedCollection.
[collection first == collection last] whileFalse: [collection removeFirst; removeLast].
tokens at: 2 put: (String withAll: collection).
^ String streamContents: [: s | tokens do: [: e | s nextPutAll: e] separatedBy: [s space]]
tokens _ Scanner new scanTokens: 'A <<<><<<>><<<><><<>><<<><<><<<>><<<><<>>>><><<>>< B'.
array _ tokens second asSortedArray.
token2 _ String streamContents: [: s |
array with: array reverse do: [: a : b | a = b ifTrue: [s nextPut: a]]].
tokens at: 2 put: token2.
^ String streamContents: [: s | tokens do: [: e | s nextPutAll: e] separatedBy: [s space]]
もちろん、ループで回して、じかに数えて差を取るのもありでしょう。面倒ですが…。数えるにしても、a Bag くらいは使いたいですね。w
tokens counts first second |
tokens _ Scanner new scanTokens: 'A <<<><<<>><<<><><<>><<<><<><<<>><<<><<>>>><><<>>< B'.
counts _ tokens second asBag sortedCounts.
first _ counts first.
second _ counts second.
tokens at: 2 put: (String streamContents: [: s |
first key - second key timesRepeat: [s nextPut: first
value]]).
^ String streamContents: [: s | tokens do: [: e | s nextPutAll: e] separatedBy: [s space]]