Sha256: df306df152030c316e033df3f2c3c315ef94da0a755f75b48b3eece25800a869

Contents?: true

Size: 854 Bytes

Versions: 4

Compression:

Stored size: 854 Bytes

Contents

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

    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
      @guess_code.each_with_object('').with_index do |(digit, result), index|
        next unless digit == @secret_code[index]

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

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

        next unless found_index

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
cb-core-0.1.10 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.9 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.8 lib/codebreaker/secret_code_matcher.rb
cb-core-0.1.7 lib/codebreaker/secret_code_matcher.rb