mirror of
https://github.com/Swiftgram/Telegram-iOS.git
synced 2025-06-16 05:55:20 +00:00
78 lines
1.9 KiB
Swift
78 lines
1.9 KiB
Swift
import Foundation
|
|
import TelegramCore
|
|
|
|
private struct PercentCounterItem: Comparable {
|
|
var index: Int = 0
|
|
var percent: Int = 0
|
|
var remainder: Int = 0
|
|
|
|
static func <(lhs: PercentCounterItem, rhs: PercentCounterItem) -> Bool {
|
|
if lhs.remainder > rhs.remainder {
|
|
return true
|
|
} else if lhs.remainder < rhs.remainder {
|
|
return false
|
|
}
|
|
return lhs.percent < rhs.percent
|
|
}
|
|
|
|
}
|
|
|
|
private func adjustPercentCount(_ items: [PercentCounterItem], left: Int) -> [PercentCounterItem] {
|
|
var left = left
|
|
var items = items.sorted(by: <)
|
|
var i:Int = 0
|
|
while i != items.count {
|
|
let item = items[i]
|
|
var j = i + 1
|
|
loop: while j != items.count {
|
|
if items[j].percent != item.percent || items[j].remainder != item.remainder {
|
|
break loop
|
|
}
|
|
j += 1
|
|
}
|
|
if items[i].remainder == 0 {
|
|
break
|
|
}
|
|
let equal = j - i
|
|
if equal <= left {
|
|
left -= equal
|
|
while i != j {
|
|
items[i].percent += 1
|
|
i += 1
|
|
}
|
|
} else {
|
|
i = j
|
|
}
|
|
}
|
|
return items
|
|
}
|
|
|
|
public func countNicePercent(votes: [Int], total: Int) -> [Int] {
|
|
var result: [Int] = []
|
|
var items: [PercentCounterItem] = []
|
|
for _ in votes {
|
|
result.append(0)
|
|
items.append(PercentCounterItem())
|
|
}
|
|
|
|
let count = votes.count
|
|
|
|
var left:Int = 100
|
|
for i in 0 ..< votes.count {
|
|
let votes = votes[i]
|
|
items[i].index = i
|
|
items[i].percent = Int((Float(votes) * 100) / Float(total))
|
|
items[i].remainder = (votes * 100) - (items[i].percent * total)
|
|
left -= items[i].percent
|
|
}
|
|
|
|
if left > 0 && left <= count {
|
|
items = adjustPercentCount(items, left: left)
|
|
}
|
|
for item in items {
|
|
result[item.index] = item.percent
|
|
}
|
|
|
|
return result
|
|
}
|