#!/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