Avatar of paulfioravanti

paulfioravanti's solution

to Change in the Ruby Track

Published at May 27 2019 · 0 comments
Instructions
Test suite
Solution

Correctly determine the fewest number of coins to be given to a customer such that the sum of the coins' value would equal the correct amount of change.

For example

  • An input of 15 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) or [5, 10]
  • An input of 40 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) and one quarter (25) or [5, 10, 25]

Edge cases

  • Does your algorithm work for any given set of coins?
  • Can you ask for negative change?
  • Can you ask for a change value smaller than the smallest coin value?

For installation and learning resources, refer to the Ruby resources page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

gem install minitest

If you would like color output, you can require 'minitest/pride' in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

ruby change_test.rb

To include color from the command line:

ruby -r minitest/pride change_test.rb

Source

Software Craftsmanship - Coin Change Kata https://web.archive.org/web/20130115115225/http://craftsmanship.sv.cmu.edu:80/exercises/coin-change-kata

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

change_test.rb

require 'minitest/autorun'
require_relative 'change'

# Common test data version: 1.3.0 258c807
class ChangeTest < Minitest::Test
  def test_single_coin_change
    # skip
    assert_equal [25], Change.generate([1, 5, 10, 25, 100], 25)
  end

  def test_multiple_coin_change
    skip
    assert_equal [5, 10], Change.generate([1, 5, 10, 25, 100], 15)
  end

  def test_change_with_lilliputian_coins
    skip
    assert_equal [4, 4, 15], Change.generate([1, 4, 15, 20, 50], 23)
  end

  def test_change_with_lower_elbonia_coins
    skip
    assert_equal [21, 21, 21], Change.generate([1, 5, 10, 21, 25], 63)
  end

  def test_large_target_values
    skip
    assert_equal [2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100], Change.generate([1, 2, 5, 10, 20, 50, 100], 999)
  end

  def test_possible_change_without_unit_coins_available
    skip
    assert_equal [2, 2, 2, 5, 10], Change.generate([2, 5, 10, 20, 50], 21)
  end

  def test_another_possible_change_without_unit_coins_available
    skip
    assert_equal [4, 4, 4, 5, 5, 5], Change.generate([4, 5], 27)
  end

  def test_no_coins_make_0_change
    skip
    assert_equal [], Change.generate([1, 5, 10, 21, 25], 0)
  end

  def test_error_testing_for_change_smaller_than_the_smallest_of_coins
    skip
    assert_raises(Change::ImpossibleCombinationError) do
      Change.generate([5, 10], 3)
    end
  end

  def test_error_if_no_combination_can_add_up_to_target
    skip
    assert_raises(Change::ImpossibleCombinationError) do
      Change.generate([5, 10], 94)
    end
  end

  def test_cannot_find_negative_change_values
    skip
    assert_raises(Change::NegativeTargetError) do
      Change.generate([1, 2, 5], -5)
    end
  end
end
module Change
  class ImpossibleCombinationError < StandardError; end
  class NegativeTargetError < StandardError; end

  GREATER = 1
  private_constant :GREATER
  EQUAL = 0
  private_constant :EQUAL

  module_function

  def generate(coins, target)
    return [] if target.zero?
    raise NegativeTargetError if target.negative?
    raise ImpossibleCombinationError if target < coins.min

    denominations = generate_denominations(coins, target)
    change_candidates = generate_change_candidates(denominations, target)
    raise ImpossibleCombinationError if change_candidates.empty?

    change_candidates.min_by(&:length)
  end

  def generate_denominations(coins, target)
    coins
      .select { |coin| coin <= target }
      .sort
      .reverse
  end
  private_class_method :generate_denominations

  def generate_change_candidates(denominations, target)
    coin_types = denominations.dup.freeze

    denominations
      .each
      .with_object([denominations, coin_types, target])
      .then(&method(:generate_change))
      .first
  end
  private_class_method :generate_change_candidates

  # rubocop:disable Metrics/MethodLength
  def generate_change(denomination_enumerator)
    denomination_enumerator
      .each_with_object([[], []]) \
      do |(coin, (denominations, coin_types, target)), (candidates, acc)|
        acc.prepend(coin)
        case acc.sum <=> target
        when GREATER
          try_next_smallest_coin(coin, denominations, coin_types, acc)
        when EQUAL
          store_candidate(denominations, coin_types, candidates, acc)
        else # SMALLER
          redo
        end
        next
      end
  end
  private_class_method :generate_change
  # rubocop:enable Metrics/MethodLength

  def try_next_smallest_coin(coin, denominations, coin_types, acc)
    acc.shift
    return unless smallest_coin?(coin, coin_types)

    acc.delete(coin)
    return if acc.empty?

    append_coin_type_subset(denominations, coin_types, acc.first)
    acc.shift
  end
  private_class_method :try_next_smallest_coin

  def smallest_coin?(coin, coin_types)
    coin == coin_types.last
  end
  private_class_method :smallest_coin?

  def store_candidate(denominations, coin_types, candidates, acc)
    append_coin_type_subset(denominations, coin_types, acc.last)
    candidates << acc.dup
    acc.clear
  end
  private_class_method :store_candidate

  def append_coin_type_subset(denominations, coin_types, coin)
    next_smallest_coin_type_index = coin_types.index(coin) + 1
    remaining_coin_types = coin_types[next_smallest_coin_type_index..-1]
    denominations.append(*remaining_coin_types)
  end
  private_class_method :append_coin_type_subset
end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?