Skip to content

Instantly share code, notes, and snippets.

@Un3qual
Forked from sriprasanna/gist:2465475
Created November 13, 2019 20:05
Show Gist options
  • Save Un3qual/8d12945965e24a41056c57b62ad76e68 to your computer and use it in GitHub Desktop.
Save Un3qual/8d12945965e24a41056c57b62ad76e68 to your computer and use it in GitHub Desktop.
Reddit ranking algorithm in Ruby
#!/Users/dustyeike/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
require "rubygems"
require "test/unit"
require "date"
EPOCH = Date.new(1970, 1, 1)
#
# Returns the number of seconds from the epoch to date
def epoch_seconds date
td = date - EPOCH
Time.at(td).day * 86400 + Time.at(td).sec + (Time.at(td).usec).to_f / 1000000
end
def score ups, down
ups - down
end
#
# The hot formula. Should match the equivalent function in postgres.
def hot ups, down, date
s = score ups, down
order = Math.log([s.abs, 1].max, 10)
if s > 0
sign = 1
elsif s < 0
sign = -1
else
sign = 0
end
seconds = epoch_seconds(date) - 1134028003
(order + sign * seconds / 45000).round
end
class TestRedditAlgoritym < Test::Unit::TestCase
def setup
today = DateTime.now
@now = Date.new(today.year, today.month, today.day)
end
def test_epoch_seconds
assert_equal(epoch_seconds(@now), 2678403.0)
end
def test_score
assert_equal(score(10, 5), 5)
end
def test_hot
assert_equal(hot(10,5,@now), -25140)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment