-4

I have String data like "1,2,3,4,5,1,2,1,5,6". I split with "," and count them one by one. After that I want to order them with descending. How can I do that with Swift.

I want to get a result like this. Key should be the above string number(converting to Int is fine). Value should be number of data. If some data have the same count number, smaller key should be first.

final result

["1" => 3, "2" => 2, "5" => 2, "3" => 1, "4" => 1, "6" => 1]

or

[1 => 3, 2 => 2, 5 => 2, 3 => 1, 4 => 1, 6 => 1]
New Dev
  • 48,427
  • 12
  • 87
  • 129
Ken
  • 109
  • 9
  • 1
    What have you tried, and what problems are you running into? – New Dev May 28 '20 at 18:03
  • Consider that dictionaries are unordered. – vadian May 28 '20 at 18:10
  • For the first task, see [How to count occurrences of an element in a Swift array?](https://stackoverflow.com/q/30545518/1187415) or [Histogram of Array in Swift](https://stackoverflow.com/q/49979152/1187415) – Martin R May 28 '20 at 18:24

1 Answers1

0

First you would need to separate your components by the comma, map the components to integers, reduce the elements counting their frequency and then do a custom sort on the result:

let string = "1,2,3,4,5,1,2,1,5,6"
let results = string.components(separatedBy: ",")
    .compactMap(Int.init)
    .reduce(into: [:]) { $0[$1, default: 0] += 1 }
    .sorted(by: { $1.value < $0.value ? true :
                  $0.key < $1.key })
print(results)
// "[(key: 1, value: 3), (key: 2, value: 2), (key: 5, value: 2), (key: 3, value: 1), (key: 4, value: 1), (key: 6, value: 1)]\n"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571