Skip to content

Instantly share code, notes, and snippets.

@voleinikov
Created January 9, 2013 17:55
Show Gist options
  • Save voleinikov/4495251 to your computer and use it in GitHub Desktop.
Save voleinikov/4495251 to your computer and use it in GitHub Desktop.
W1D2 Code Review
class Student
attr_accessor :name
def initialize(first_name, last_name)
@name = "#{first_name} #{last_name}"
end
def courses
Course.get_courses(self)
end
def enroll(course)
course.add_student(self)
end
def course_load
# This is a nice way to count up things in hashes. Will try and remember this method for the future.
load = Hash.new(0)
courses.each do |course|
load[course.dept] += course.credits
end
load
end
end
class Course
attr_accessor :students
attr_reader :name, :dept, :credits, :days, :period
# A bit confused on the use of the class variable here instead of a normal method variable
@@courses = []
class << self
def get_courses(student)
@@courses.select { |course| course.students.include?(student) }
end
def conflicts?(course1, course2)
if course1.period == course2.period
course1.days.any? { |day| course2.days.include?(day) } ? true : false
else
false
end
end
end
def initialize(name, dept, credits, days, period)
# I think you forgot to assign @weekdays a value
@name, @dept, @credits, @weekdays = name, dept, credits
@days, @period = days, period
@students = []
@@courses << self
end
def add_student(student)
if student.courses.any? { |course| Course.conflicts?(self, course) }
raise ArgumentError, "courses conflict"
elsif students.include?(student)
raise ArgumentError, "student already enrolled in that class"
else
self.students << student
true
end
end
end
# john = Student.new("John", "Smith")
# #sally = Student.new("Sally", "Smith")
# biology = Course.new("Bio101", "Biology", 3, [:mon, :wed], 3)
# economics = Course.new("Bio101", "Biology", 3, [:mon, :thurs], 3)
# # biology.add_student(john)
# # sally.enroll(biology)=# puts biology.students
# john.enroll(biology)
# john.enroll(economics)
# john.courses.each { |course| puts course.name }
# # puts "John's courses: #{john.courses}"
# # puts biology.students
def thinking_of_a_number
number_of_guesses = 5
puts "I'm thinking of a number between 1 and 100, you get #{number_of_guesses} \
guesses. Go!"
random_number = (1 + Random.rand(100))
number_of_guesses.times do |iter|
print "Guess ##{iter + 1}: "
guess = gets.chomp.to_i
if guess > random_number
puts "Lower"
elsif guess < random_number
puts "Higher"
elsif guess == random_number
return "Congratulations you won!"
end
end
"You lose!"
end
puts thinking_of_a_number
#!/usr/bin/ruby
def line_randomizer
if ARGV[0]
line_array = File.readlines(ARGV[0]).map(&:chomp)
else
puts "Sorry that is not the right syntax. Type '#{$PROGRAM_NAME} \
some_file.txt'"
end
2.times { line_array.shuffle! }
File.open("#{ARGV[0]}--shuffled.txt", 'w') do |f|
f.puts line_array.join("\n")
end
line_array.join("\n")
end
puts "#{line_randomizer}"
# You need to print i in this excercise so you should print i after you break out of the loop
i = 250
loop do
break if i > 250 && i % 7 == 0
i += 1
end
(1..100).each do |num|
factor_array = []
(1..num).each do |factor|
factor_array << factor if num % factor == 0
end
# puts "#{num} = #{factor_array}"
end
def bubble_sort(array)
sorted = array.dup
swapped = true
while swapped do
swap_count = 0
((sorted.length) - 1).times do |i|
if sorted[i] > sorted[i+1]
sorted[i+1], sorted[i] = sorted[i], sorted[i+1]
swap_count += 1
end
end
swapped = false if swap_count == 0
end
sorted
end
def big_array(num)
array = []
range = (-1000..1000).to_a
num.times { array << range[rand(range.length)] }
array
end
def benchmark(name)
start = Time.now
yield
puts "#{name}: #{Time.now - start}"
end
def read_words(filename)
File.open(filename, "r") do |f|
f.each do |line|
puts line.split
end
end
end
read_words("english.0")
# rps should prompt the user for a move using gets (so that non-programmers can play too)
def rps(move)
# I like the use of hash here. Nice and concise. We should have done it this way
win_hash = {
"Rock" => "Scissors",
"Paper" => "Rock",
"Scissors" => "Paper"
}
return "Bad move, chump." if !win_hash.has_key?(move)
comp_move = win_hash.keys[rand(3)]
result = if win_hash[move] == comp_move
"You Win"
elsif win_hash[comp_move] == move
"You Lose"
else
"You Draw"
end
"Computer's move: #{comp_move}, #{result}"
end
def swingers(couples)
males = []
females = []
couples.each do |couple|
males << couple[0]
females << couple[1]
end
while true do
swingers_arr = []
rand_males = males.shuffle
rand_females = females.shuffle
couples.length.times { swingers_arr << [rand_males.pop, rand_females.pop] }
return swingers_arr if couples.sort != swingers_arr.sort
end
end
#puts rps("Scissors")
puts "#{swingers([
["Clyde", "Bonnie"],
["Paris", "Helen"],
["Romeo", "Juliet"]
])}"
#!/usr/bin/ruby
# If handed a filename, will evaluate ex: ./rpncalc.rb rpnstring.txt
# If not, will ask for keyboard input
class RPNCalculator
attr_reader :numbers
def initialize
@numbers = []
end
def take_input
if ARGV[0]
input = File.read(ARGV[0])
else
input = []
while input.last != ""
print "Next input: "
input << gets.chomp
end
input = input.join(" ")
end
puts "Result: #{evaluate(input)}"
end
def value
@numbers.last
end
def push(num)
@numbers << num
end
def plus
@numbers << (@numbers.pop + @numbers.pop)
end
def minus
@numbers << (@numbers.pop - @numbers.pop)
end
def times
@numbers << (@numbers.pop * @numbers.pop)
end
def divide
@numbers << (@numbers.pop / @numbers.pop.to_f)
end
def tokens(string)
string.split.map do |x|
x =~ /\w/ ? x.to_i : x.to_sym
end
end
def evaluate(string)
dispatch = { :+ => :plus,
:- => :minus,
:* => :times,
:/ => :divide }
tokens(string).each do |x|
dispatch.include?(x) ? send(dispatch[x]) : push(x)
end
value
end
end
calc = RPNCalculator.new
calc.take_input
def super_print(string, options = {})
defaults = {
times: 1,
upcase: false,
reverse: false
}
options = defaults.merge(options)
super_string = string
super_string = super_string.upcase if options[:upcase]
super_string = super_string.reverse if options[:reverse]
options[:times].times { puts "#{super_string}" }
nil
end
super_print("hello", reverse: true, times: 5)
# Should take debugger out in production
require 'debugger'
class TicTacToe
attr_reader :board, :players
def initialize
@board = Array.new(3) { ["", "", ""] }
@players = add_players
end
def play
while true do
players.each do |player|
puts
print_board
current_move = player.move(self)
while !valid_move?(current_move) do
current_move = player.move(self)
end
make_move(player, current_move)
if game_over?(board)
puts
print_board
puts "Game over! #{player.letter} wins."
return
end
end
end
end
def game_over?(a_board)
paths(a_board).each do |path|
next if path[0] == ""
return true if all_equal?(path)
end
false
end
def paths(a_board)
[ a_board[0], #Rows
a_board[1],
a_board[2],
[a_board[0][0], a_board[1][0], a_board[2][0]], #Columns
[a_board[0][1], a_board[1][1], a_board[2][1]],
[a_board[0][2], a_board[1][2], a_board[2][2]],
[a_board[0][0], a_board[1][1], a_board[2][2]], #Diagonals
[a_board[0][2], a_board[1][1], a_board[2][0]] ]
end
def all_equal?(array)
array.count(array[0]) == array.length
end
def make_move(player, move)
board[move[0]][move[1]] = player.letter
end
def get_move(player)
print "Player #{player.letter}, What's your move? ex: '1, 3' "
gets.chomp.split(", ").map do |num|
num.to_i - 1
end
end
def valid_move?(amove)
row, column = amove[0], amove[1]
if board[row][column] == ""
true
else
puts "Invalid move"
false
end
end
def add_players
print "How many people will be playing (0-2)? "
humans = gets.chomp.to_i
players = []
if humans == 2
players << HumanPlayer.new('X')
players << HumanPlayer.new('O')
elsif humans == 1
players << HumanPlayer.new('X')
players << ComputerPlayer.new('O')
elsif humans == 0
players << ComputerPlayer.new('X')
players << ComputerPlayer.new('O')
end
end
# Should print out the number corresponding to the board square so user knows where they are placing a square. The example is a bit vague because it seems like its showing a few examples (ex: 1, 3 reads like "examples 1,3 etc.") (do I need a row number and a column number in quotes?) I finally figured it out, but it took a while. Need to make this easier for end user.
def print_board
board.each { |row| p row }
end
end
class HumanPlayer
attr_reader :letter
def initialize(letter)
@letter = letter
end
def move(game)
print "Player #{letter}, What's your move? ex: '1, 3' "
gets.chomp.split(", ").map do |num|
num.to_i - 1
end
end
end
class ComputerPlayer < HumanPlayer
def move(game)
possibles = find_empties(game.board)
winners = find_winners(game, possibles)
current_move = if winners.empty?
possibles[rand(possibles.length)]
else
winners[rand(winners.length)]
end
end
def find_empties(board)
possibles = []
board.each_with_index do |row, i|
row.each_with_index do |val, j|
possibles << [i, j] if val == ""
end
end
possibles
end
def find_winners(game, possibles)
winners = []
possibles.each do |possible|
pretend_board = board_copy(game)
pretend_board[possible[0]][possible[1]] = self.letter
if game.game_over?(pretend_board)
winners << possible
end
end
winners
end
def board_copy(game)
copy_board = []
game.board.each do |row|
copy_row = []
row.each do |val|
copy_row << val
end
copy_board << copy_row
end
copy_board
end
end
game = TicTacToe.new
game.play
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment