Guessing Passcode in Ruby
I’m sure there are better algorithms. But welp …
print 'Please give me the code to guess (integer only): ' the_code = gets.chomp code_digits = the_code.length code_matched = '' puts "The code is #{code_digits} digits long." puts 'Begin guessing ...' # check basics guessed = [] (0..9).each do |n| guess = "#{n}" * code_digits guessed.push(guess) if guess == the_code code_matched = guess break end end # now brute force if code_matched.length == 0 # create array of all possibilites # ... except the basic guessed last_code = '9' * code_digits possibles = (0..last_code.to_i).collect { |item| item.to_s.rjust(code_digits, '0') } - guessed possibles.each do |guess| if guess == the_code code_matched = guess break end end end # Should matched something or the user is cheating. if code_matched.length > 0 puts "The code is #{code_matched}. Right?" else puts "I can't find your code. Are you cheating?" end
Work like charm. :P
Guessing Passcode in Ruby
Refactoring is a way of meditation.
# ---- [ map.with ] --------------------------------------- # http://stackoverflow.com/questions/23695653/can-you-supply-arguments-to-the-mapmethod-syntax-in-ruby # Patch Symbol class to allow # ... passing parameters to map() or similar method class Symbol def with(*args, &block) ->(caller, *rest) { caller.send(self, *rest, *args, &block) } end end # ---- [ ] ----------------------------------------------- # create array of all possibilites # ... except the basic guessed def possibilities last_code = ('9' * @digits).to_i # (0..last_code).map(&:to_s).collect { |s| s.rjust(@digits, '0') } - @guessed (0..last_code).map(&:to_s).map(&:rjust.with(@digits, '0')) - @guessed end def matched?(guess) if guess == @the_code @code_matched = guess true else false end end # ---- [ ] ----------------------------------------------- print 'Please give me the code to guess (integer only): ' @the_code = gets.chomp @digits = @the_code.length @code_matched = '' @guessed = [] puts "The code is #{@digits} digits long." puts 'Begin guessing ...' # check basics # (0..9).map(&:to_s).collect { |s| s * @digits }.each do |guess| (0..9).map(&:to_s).map(&:*.with(@digits)).each do |guess| @guessed.push(guess) break if matched?(guess) end # now brute force if @code_matched.length == 0 possibilities.each { |guess| break if matched?(guess) } end # Should matched something or the user is cheating. if @code_matched.length > 0 puts "The code is #{@code_matched}. Right?" else puts "I can't find your code. Are you cheating?" end