Sha256: 20bcf7bd00c14c6edce7b09cba508dc136f4b70ab49bef5e452af0629ad8efef

Contents?: true

Size: 991 Bytes

Versions: 6

Compression:

Stored size: 991 Bytes

Contents

module Codebreaker
  class SecretCodeMatcher
    EXACT_MATCH_SYMBOL = '+'.freeze
    DIGIT_MATCH_SYMBOL = '-'.freeze
    WIN_COMBINATION = '++++'.freeze

    def self.win_combination?(combination)
      combination == WIN_COMBINATION
    end

    def initialize(secret_code, guess_code)
      @secret_code = secret_code.dup
      @guess_code = guess_code.dup
    end

    def call
      exact_match + digit_match
    end

    private

    def exact_match
      result = ''
      @guess_code.each_with_index do |digit, index|
        next unless digit == @secret_code[index]

        result << EXACT_MATCH_SYMBOL
        @guess_code[index] = nil
        @secret_code[index] = nil
      end
      result
    end

    def digit_match
      result = ''
      @guess_code.compact.each do |digit|
        found_index = @secret_code.index(digit)

        next unless found_index

        result << DIGIT_MATCH_SYMBOL
        @secret_code[found_index] = nil
      end
      result
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
cb-core-0.1.6 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.4 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.3 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.2 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.1 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.0 lib/codebreaker/secret_code_matcher.rb