Last active
September 2, 2023 12:19
-
-
Save User4574/f966df2e1452aa138eccabfc007be510 to your computer and use it in GitHub Desktop.
Digit combinations for target sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'optimist' | |
opts = Optimist::options do | |
version "digits 0.2 (c) 2023 Nat Lasseter" | |
banner <<-EOS | |
Digits gives valid combinations of digits 1-9 that sum to the given total | |
Usage: | |
digits [opts] | |
where [opts] are: | |
EOS | |
opt :number, "The number of digits", type: :integer | |
opt :target, "The target sum", type: :integer | |
opt :exclude, "Exclude a digit", type: :integer, multi: true | |
opt :include, "Include a digit", type: :integer, multi: true | |
educate_on_error | |
end | |
digits = [1,2,3,4,5,6,7,8,9] | |
opts[:exclude].each { |i| digits.delete(i) } | |
def puts_group(digits, mandatory, number, target = nil) | |
if target.nil? | |
puts digits.combination(number).select { |a| (mandatory - a).empty? }.sort { |a, b| a.sum <=> b.sum }.map { |a| "#{a.join} = #{a.sum}" } | |
else | |
puts digits.combination(number).select { |a| a.sum == target }.select { |a| (mandatory - a).empty? }.map { |a| "#{a.join} = #{target}" } | |
end | |
end | |
if opts[:number_given] | |
puts "== #{opts[:number]} ==" | |
puts_group(digits, opts[:include], opts[:number], opts[:target]) | |
else | |
(2..8).each do |n| | |
puts "== #{n} ==" | |
puts_group(digits, opts[:include], n, opts[:target]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment