這篇文章我要向你們介紹Hacker News網站的文章排名算法工做原理,以及如何在本身的應用裏使用這種算法。這個算法很是的簡單,但卻在突出熱門文章和遴選新文章上表現的異常優秀。python
Hacker News是用Arc語言開發的,這是一種Lisp方言,由Y Combinator投資公司創始人Paul Graham創造。Hacker News的開源的,你能夠在arclanguage.org找到它的源代碼。深刻發掘 news.arc 程序,你會找到這段排名算法代碼,就是下面這段:算法
; Votes divided by the age in hours to the gravityth power. ; Would be interesting to scale gravity in a slider. (= gravity* 1.8 timebase* 120 front-threshold* 1 nourl-factor* .4 lightweight-factor* .3 ) (def frontpage-rank (s (o scorefn realscore) (o gravity gravity*)) (* (/ (let base (- (scorefn s) 1) (if (> base 0) (expt base .8) base)) (expt (/ (+ (item-age s) timebase*) 60) gravity)) (if (no (in s!type 'story 'poll)) 1 (blank s!url) nourl-factor* (lightweight s) (min lightweight-factor* (contro-factor s)) (contro-factor s))))
本質上,這段 Hacker News採用的排名算法的工做原理看起來大概是這個樣子:segmentfault
Score = (P-1) / (T+2)^G
其中,ide
正如你看到的,這個算法很容易實現。在下面的內容裏,咱們將會看到這個算法是如何工做的。post
比重和時間在文章的排名得分上有重大的影響。正常狀況下以下面所述:網站
爲了能視覺呈現這個算法,咱們能夠把它繪製到Wolfram Alpha。url
你能夠看到,隨着時間的流逝,得分驟然降低,例如,24小時前的文章的分數變的很是低——無論它得到了如何多的票數。spa
Plot語句:翻譯
plot( (30 - 1) / (t + 2)^1.8, (60 - 1) / (t + 2)^1.8, (200 - 1) / (t + 2)^1.8 ) where t=0..24
圖中你能夠看到,比重越大,得分降低的越快。rest
plot( (p - 1) / (t + 2)^1.8, (p - 1) / (t + 2)^0.5, (p - 1) / (t + 2)^2.0 ) where t=0..24, p=10
以前已經說了,這個評分算法很容易實現:
def calculate_score(votes, item_hour_age, gravity=1.8): return (votes - 1) / pow((item_hour_age+2), gravity)
關鍵是要理解算法中的各個因素對評分的影響,這樣你能夠在你的應用中進行定製。我但願這篇文章已經向你說明了這些
更新: Paul Graham 分享了修正後的HN 排名算法:
(= gravity* 1.8 timebase* 120 front-threshold* 1 nourl-factor* .4 lightweight-factor* .17 gag-factor* .1) (def frontpage-rank (s (o scorefn realscore) (o gravity gravity*)) (* (/ (let base (- (scorefn s) 1) (if (> base 0) (expt base .8) base)) (expt (/ (+ (item-age s) timebase*) 60) gravity)) (if (no (in s!type 'story 'poll)) .8 (blank s!url) nourl-factor* (mem 'bury s!keys) .001 (* (contro-factor s) (if (mem 'gag s!keys) gag-factor* (lightweight s) lightweight-factor* 1)))))