Coogle Code Jam “Magic Trick” solution

Yup, this is still very much alpha and can be refactored. I’ve broken it apart into multiple files, had other plans and ran out of time, but the meat of the code is in guessing_game.rb.

magic_trick.rb

  
class MagicTrick
 
  attr_reader :tricks
 
  def initialize(tricks, file_input = './magic_trick_input.txt')
    @tricks = tricks
    parse File.read(file_input)
  end
 
  def parse(contents)
    tricks = @tricks.new contents.split("\n")
    tricks.perform
    puts tricks.results
  end
 
end
 
magic_trick = MagicTrick.new(GuessingGame)
  

guessing_game.rb

  
class GuessingGame
 
  attr_reader :total_tricks, :trick_config, :results
 
  def initialize(trick_config)
    @total_tricks = trick_config.slice!(0).to_i 
    @trick_config = trick_config
    @results = []
  end
 
  def perform
    @trick_config.each_slice(10).each_with_index { |line, idx| build(line, idx) }
  end
 
  private
 
    def build(l, idx)
      tricks = get_card_grid(l)
      @results < < "Case #%s: %s" % [idx+1, validate(tricks)]
    end
 
    def validate(trick)
      return 'Volunteer cheated!' if trick[0] === trick[1]
      intersection = trick[0] & trick[1]
      return intersection[0] if intersection.any?
      'Bad magician!'
    end  
 
    def get_card_grid(line)
      2.times.map do |index|
        start = index*5
        range = (start+1..start+14)
        line[range][(line[start].to_i)-1].split
      end
    end
 
end
  

magic_trick_input.txt

  
3
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 5 4
3 11 6 15
9 10 7 12
13 14 8 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
  
Chapley Watson
Husband, Father, Software Developer, Attempted Writer, and many other things depending on the day.
%d bloggers like this: