Last active
January 13, 2016 18:22
-
-
Save kinduff/cd763edf51120b8c6ec6 to your computer and use it in GitHub Desktop.
How to Win a Guessing Game
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
# How to Win a Guessing Game - Numberphile | |
# Based on https://www.youtube.com/watch?v=ud_frfkt1t0 | |
class WinGuessing | |
def initialize(total_iterations, max_random_num) | |
@total_times = total_iterations | |
@max_random_num = max_random_num | |
@max_length = @max_random_num.to_s.length | |
@total_result = 0 | |
end | |
def start | |
print_table_headers | |
start_iterations | |
print_separator | |
print_result | |
end | |
private | |
def random_number | |
Random.rand(@max_random_num) | |
end | |
def print_separator | |
separator = [*1..@max_length].map{'-'}.join | |
printf(format, separator, separator, separator, separator) | |
end | |
def format | |
"%#{@max_length}s\t%#{@max_length}s\t%#{@max_length}s\t%#{@max_length}s\n" | |
end | |
def print_table_headers | |
printf(format, "A", "B", "K", "Result") | |
print_separator | |
end | |
def start_iterations | |
@total_times.times do | |
a, b, k = random_number, random_number, random_number | |
result = a > b if a > k | |
result = a < b if a < k | |
@total_result += 1 if result | |
printf(format, a, b, k, (result ? 'Win' : 'Lose')) | |
end | |
end | |
def print_result | |
printf(format, nil, nil, nil, "#{@total_result*100/@total_times}%") | |
end | |
end | |
game = WinGuessing.new(100, 1000) | |
game.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment