我正在构建一个应用程序,该应用程序将具有允许您按1-5的等级为用户评分的功能。我已经决定我会像这样使用加权平均值:
Sum of (weight * number of reviews at that weight) / total number of reviews
我无法确定如何使用firebase存储此数据,因为我需要此评级值来初始化User
对象。我想将每个评级存储为字典,其中密钥是id
用户离开评论,值是实际评级。然后我从数据库中获取用户并需要初始化User
后,我执行以下操作:
// keep track of amount of each rating.
var oneStars = 0
var twoStars = 0
var threeStars = 0
var fourStars = 0
var fiveStars = 0
// iterate through dictionary of ratings where key is unique Id, and value is star rating.
for (key, value) in ratings {
switch value {
case 1: oneStars += 1
case 2: twoStars += 1
case 3: threeStars += 1
case 4: fourStars += 1
case 5: fiveStars += 1
}
}
let weightedSum = (
(5 * fiveStars) +
(4 * fourStars) +
(3 * threeStars) +
(2 * twoStars) +
(1 * oneStars)
)
let reviewsSum = oneStars + twoStars + threeStars + fourStars + fiveStars
let rating = weightedSum / reviewsSum
let user = User(name: "john doe", rating: rating)
这是存储评级的最佳方式,并进行实际计算以初始化对象,还是有更高效的设计?谢谢。
答案 0 :(得分:1)
您可能需要存储每个用户的评分,因此可以通过这种方式存储评分。
至于计算最终评级,这是一个更好的实施:
var count = 0
var rating = 0
for (key, value) in ratings {
count += 1
rating += value
}
rating /= count
let user = User(name: "john doe", rating: rating)
另一种可以处理大量收视率的算法可能会导致溢出:
var count = 0
var rating = 0
for (key, value) in ratings {
count += 1
rating += (value - rating) / count
}
let user = User(name: "john doe", rating: rating)
如果您在每次新用户评分时重新计算服务器端的评级,那么第二种算法效果很好(如果您有大量用户访问这些评级,并且还有大量评级,那么它会更好在服务器端计算这个。)