Skip to content

Instantly share code, notes, and snippets.

@volo1st
Created October 29, 2015 01:01
Show Gist options
  • Save volo1st/d8593cfdf114f8ecbca1 to your computer and use it in GitHub Desktop.
Save volo1st/d8593cfdf114f8ecbca1 to your computer and use it in GitHub Desktop.
MonkeyKingElector
require 'minitest/autorun'
class MonkeyKingElector
def elect(n, m)
(1..n).to_a.tap { |x| x.delete_at(m % x.size - 1) while x.size > 1 }[0]
end
end
describe MonkeyKingElector do
before do
@elector = MonkeyKingElector.new
end
it "should elect #1 when n = 1 and m = 1" do
@elector.elect(1, 1).must_equal 1
end
# n = [1, 2], m = 1
#
# [2]
it "should elect #2 when n = 2 and m = 1" do
@elector.elect(2, 1).must_equal 2
end
# n = [1, 2, 3, 4, 5], m = 7
# [1, 3, 4, 5]
# [1, 3, 5]
# [3, 5]
# [5]
it "should elect #5 when n = 5 and m = 7" do
@elector.elect(5, 7).must_equal 5
end
# n = [1, 2, 3, 4, 5, 6, 7], m = 3
# [1, 2, 4, 5, 6, 7]
# [1, 2, 5, 6, 7]
# [1, 2, 6, 7]
# [1, 2, 7]
# [1, 2]
# [2]
it "should elect #2 when n = 7 and m = 3" do
@elector.elect(7, 3).must_equal 2
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment