aboutsummaryrefslogtreecommitdiff
path: root/digits.rb
blob: addc51e570aa456684796a570c93980f13f43d2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/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