我有一个2D数组:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Vyhodnotenie testu"
self.showAlert()
}
func showAlert() {
func callback(){}
if numberOfPoints > 49 {
let customIcon = UIImage(named: "smile")
let alertview = JSSAlertView().show(self, title: "Gratulujeme! Uspeli ste.", text: "Dokončili ste test s počtom bodov \(numberOfPoints + 1) z \(maximumNumberOfPoints)!", buttonText: "OK!", color: UIColorFromHex(0x22c411, alpha: 1), iconImage: customIcon)
alertview.setTextTheme(.Light)
alertview.addAction(myCancelCallback)
self.navigationController?.navigationBar.alpha = 0.7
} else {
let customIcon = UIImage(named: "sad")
let alertview = JSSAlertView().show(self, title: "Ľutujeme! Neuspeli ste.", text: "Dokončili ste test s počtom bodov \(numberOfPoints + 1) z \(maximumNumberOfPoints)!", buttonText: "OK!", color: UIColorFromHex(0xd20606, alpha: 1), iconImage: customIcon)
alertview.addAction(myCancelCallback)
alertview.setTextTheme(.Light)
self.navigationController?.navigationBar.alpha = 0.7
}
}
func myCancelCallback() {
self.navigationController?.navigationBar.alpha = 1.0
self.interstitialPresentationPolicy = ADInterstitialPresentationPolicy.Automatic
}
func interstitialAdWillLoad(interstitialAd: ADInterstitialAd!) {
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
interstitialAdView = UIView()
interstitialAdView.frame = self.view.bounds
view.addSubview(interstitialAdView)
interstitialAd.presentInView(interstitialAdView)
UIViewController.prepareInterstitialAds()
}
func interstitialAdActionDidFinish(var interstitialAd: ADInterstitialAd!) {
interstitialAd = nil
interstitialAdView.removeFromSuperview()
}
func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
}
func interstitialAdDidUnload(var interstitialAd: ADInterstitialAd!) {
interstitialAd = nil
interstitialAdView.removeFromSuperview()
}
子阵列的第一个元素是用户名,第二个元素是得分。
我需要返回最高分的用户名。例如,这里它将返回[["user1", 20], ["user2", 30], ["user3", 10]]
。
一个用户的分数较高,或者他们都有相同的分数(在这种情况下,它应该返回"user2"
)。
我知道如何通过一堆迭代和多行代码来实现这一点,但我正在努力寻找“最佳实践方式”。
你会建议什么?答案 0 :(得分:6)
查看max_by
users = [["user1", 20], ["user2", 30], ["user3", 10]]
users.max_by{ |user, weight| weight }
#=> ["user2", 30]
# shorthand
users.max_by(&:last)
#=> ["user2", 30]
users.max_by(&:last).first
#=> "user2"
值得一提的是,如果你有多个最大值,它将只返回第一个。
答案 1 :(得分:1)
给定示例的简单解决方案:
a = [["user1", 20], ["user2", 30], ["user3", 10]]
h = Hash[a].invert
h[h.keys.max]
#=> "user2"
在一般情况下,如果出现相同的最大数字,以下解决方案将返回所有共享相同最大值的用户(由Nigel执行w /反转功能,请参阅Swapping keys and values in a hash):
class Hash
def safe_invert
self.each_with_object( {} ) { |(key, value), out| ( out[value] ||= [] ) << key }
end
end
a = [["user1", 20], ["user2", 30], ["user3", 10], ["user4", 30]]
h = Hash[a].safe_invert
h[h.keys.max]
#=> ["user2", "user4"]