Skip to content

Instantly share code, notes, and snippets.

@User4574
Last active September 2, 2023 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save User4574/f966df2e1452aa138eccabfc007be510 to your computer and use it in GitHub Desktop.
Save User4574/f966df2e1452aa138eccabfc007be510 to your computer and use it in GitHub Desktop.
Digit combinations for target sum
#!/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