Sha256: a3625589195a38cb54f34b5e19f2836602c74c357c6093caf2e4ec8c01f1f83a

Contents?: true

Size: 1.77 KB

Versions: 3

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true

# Main Gem module
module CodeBrkrGameTraining
  # Class for comparing the hidden code and the code entered by the user
  class CodeComparator
    include Validator

    def initialize(secret_code, user_code)
      check_code_format(user_code)

      @secret_code = secret_code
      @user_code = user_code
    end

    def compare_codes
      {
        in_positions: check_in_positions,
        out_of_positions: check_out_positions,
        not_guessed: check_not_guessed
      }
    end

    private

    def check_code_format(code)
      check_type(code, Array)
      raise GameError, 'incorrect_code_format' unless code.size == Code::GAME_NUMBERS[:count]

      digits_range_array = (Code::GAME_NUMBERS[:from]..Code::GAME_NUMBERS[:to]).to_a
      code.each { |digit| raise GameError, 'incorrect_code_format' unless digits_range_array.member? digit }
    end

    def check_miss_indexes
      @check_miss_indexes ||= Code::GAME_NUMBERS[:count].times.reject do |user_index|
        @user_code[user_index] == @secret_code[user_index]
      end
    end

    def check_in_positions
      @check_in_positions ||= Code::GAME_NUMBERS[:count] - check_miss_indexes.length
    end

    def check_out_positions
      return @check_out_positions if @check_out_positions

      miss_indexes = check_miss_indexes
      system_digits = @secret_code.select.with_index { |_, system_index| miss_indexes.include? system_index }
      @check_out_positions = miss_indexes.collect do |miss_index|
        found = system_digits.find_index { |system_num| @user_code[miss_index] == system_num }
        found.nil? ? nil : system_digits.delete_at(found)
      end.compact.length
    end

    def check_not_guessed
      Code::GAME_NUMBERS[:count] - check_in_positions - check_out_positions
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
code_brkr_game_training-0.9.2 lib/code_brkr_game_training/entities/code_comparator.rb
code_brkr_game_training-0.9.1 lib/code_brkr_game_training/entities/code_comparator.rb
code_brkr_game_training-0.8.5 lib/code_brkr_game_training/entities/code_comparator.rb