Created
May 11, 2018 11:26
-
-
Save charusat09/142336cb13058ec305f8ebb4c4c7c803 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Rotator | |
attr_accessor :id, :values | |
BASE = 10 | |
def initialize(id, values) | |
@id = id | |
@values = values | |
end | |
def rotate | |
decisive_id = analyse_visiting_id(id) | |
rotating_url(decisive_id, bifurcation_scale) | |
end | |
private | |
def analyse_visiting_id(id) | |
id % BASE | |
end | |
def rotating_url(decisive_id, bifurcation_scale) | |
bifurcation_scale.each_index.select{ |index| bifurcation_scale[index].include? decisive_id } | |
end | |
def bifurcation_scale | |
total = values.sum | |
percentages = values.map! { |v| (v/total.to_f).round(2) } | |
pre_indexes = percentages.each_with_index.map do |per, index| | |
if percentages.uniq.length == 1 | |
index.even? ? (per * BASE).round : (per * BASE).to_i | |
else | |
(per * BASE).round | |
end | |
end | |
pre_indexes = pre_indexes.each.with_index.map do |pi, index| | |
if index == 0 | |
pre_indexes[index] | |
else | |
pre_indexes[index] += pre_indexes[index-1] | |
end | |
end | |
indexes = [] | |
pre_indexes.each.with_index do |pi, index| | |
if index == 0 | |
indexes << [*(0...pre_indexes[index])] | |
else | |
indexes << [*(pre_indexes[index-1]...pre_indexes[index])] | |
end | |
end | |
indexes | |
end | |
end | |
require 'test/unit' | |
class MyTestCase < Test::Unit::TestCase | |
def test_1 | |
ids = [*(1..100)] | |
ans = [] | |
ids.each do |id| | |
ans << Rotator.new(id, [50, 50]).rotate | |
end | |
assert_equal(ans.flatten.count(0), 50) | |
assert_equal(ans.flatten.count(0), 50) | |
end | |
def test_2 | |
ids = [*(1..100)] | |
ans = [] | |
ids.each do |id| | |
ans << Rotator.new(id, [20, 40]).rotate | |
end | |
assert_equal(ans.flatten.count(0), 30) | |
assert_equal(ans.flatten.count(1), 70) | |
end | |
def test_3 | |
ids = [*(1..100)] | |
ans = [] | |
ids.each do |id| | |
ans << Rotator.new(id, [25, 25, 25, 25]).rotate | |
end | |
assert_equal(ans.flatten.count(0), 30) | |
assert_equal(ans.flatten.count(1), 20) | |
assert_equal(ans.flatten.count(2), 30) | |
assert_equal(ans.flatten.count(3), 20) | |
end | |
def test_4 | |
ids = [*(1..100)] | |
ans = [] | |
ids.each do |id| | |
ans << Rotator.new(id, [25, 30, 35]).rotate | |
end | |
assert_equal(ans.flatten.count(0), 30) | |
assert_equal(ans.flatten.count(1), 30) | |
assert_equal(ans.flatten.count(2), 40) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment