我是独立开发人员,几个月前开始学习编程。目前,我正在尝试找到一种方法来获得业务评级,并在需要时向用户显示。我使用Parse.com作为我的后端,并使用包含以下列(键)的解析表:
评级(类型:数字) - 使用浮动值
BusinessName(type:String)
BusinessReviewText(type:String)
现在,我正在检索此数据:
//Declaring empty dictionary
var businessReview = [[String:Float]]()
var businessReviewText = [[String:String]]()
//Parse query
var query: PFQuery = PFQuery(className: "Business")
query.whereKey("ratingBool", equalTo: true) // just checking which businesses have been reviewed by users
query.findObjectsInBackgroundWithBlock{(objects:[AnyObject]?, error: NSError?) -> Void in
if (error == nil) {
for object in objects as! [PFObject!]{
var bN:AnyObject = object["BusinessName"]!
var bR: AnyObject = object["Rating"]!
var bRT: AnyObject = object["BusinessReviewText"]!
self.businessName.addObject(bN)
self.businessRating.addObject(bR)
self.businessRatingText.addObject(bRT)
self.businessReview.append(["\(bN)":bR as! Float])
self.businessReviewText.append(["\(bN)":"\(bRT)"])
}
// Gives me Key: BusinessName and its rating value: floatValue as output
println("\(self.businessReview)") // I get the output as [[businessA: 4.0], [businessA: 4.0], [businessB: 5.0], [businessC: 5.0], [businessC: 3.5], [businessC: 3.5], [businessD: 3.5]]
// Gives me Key:BusinessName and its review Value:ReviewText as output
println("\(self.businessReviewText)") // I get the output as [[businessA: Good job], [businessA: High], [businessC: Awesome service! A++], [businessC: Good service!], [businessC: Good but can improve], [businessD: "NO REVIEW"], [businessD: Ok ]]
}
}
}
现在我有以下问题: 1.我现在如何使用它的键值过滤每个商业名称,以便我可以执行数学运算,例如, 获得businessC的评级:(添加所有businessC评级/ businessC.count),即:((5 + 3.5 + 3.5)/ 3)= 4
注意:在此,我不知道用户正在检查哪些商家评级(例如:用户可以搜索中国餐馆,他可以在屏幕上看到中国餐馆商业评级的所有评级)。所以我很乐意在一个结果中审查所有业务(这是正确的做法吗?)
很抱歉,如果我太描述了。但是在搜索堆栈溢出时,我有时会发现很难理解人们提出的问题。所以我尝试提供所需的信息。
提前致谢。
答案 0 :(得分:0)
您可以创建两个NSDictionarys。第一个是NSString类型的键和NSArray类型的值(例如Key:BusinessName,Value:Array of Ratings)。第二个是NSString类型的键和Integer类型的值(例如Key:BusinessName,Value:Average Rating)。然后,在迭代业务时,将评级插入到与第一个字典中的businessName键对应的数组中。接下来,迭代第一个字典中的键,并迭代值中数组中的对象。最后,平均该特定业务的评级,并将平均值插入对应于businessName密钥的第二个字典中。现在你有一个businessNames字典,它们的值是平均值。
您的问题可以通过多种方式解决,但这只是值得思考的问题。本网站上的某些人可能会为您提供更有效的方式。
伪代码:
Dictionary[String, Array] allRatings
Dictionary[String, Integer] averageRatings
for each business
if allRatings does not contain business.name
Array ratings
ratings add business.rating
allRatings set key equal to business.name and set value equal to ratings
else
Array ratings = allRatings get array for bussiness.name
ratings add business.rating
end for each
for each key called businessName in allRatings
Array ratings = allRatings get value for businessName
int average = 0
for each rating in ratings
average += rating
end for each
average /= ratings.count
averageRatings set key equal to businessName and set value equal to average
end for each
理论上,我认为时间复杂度应为O(n ^ 2)。它很体面,但不是很好。
P.S。我觉得这可能有问题但是,除非我测试它,否则我无法确定。