Verbose and inefficient, but there was a 10 minute limit
class Gen
include Enumerable
def each
(3β¦7).each do |c1|
(3β¦7).each do |c2| next if [c1].include? c2
(3β¦7).each do |c3| next if [c1,c2].include? c3
(3β¦7).each do |c4| next if [c1,c2,c3].include? c4
(3β¦7).each do |c5| next if [c1,c2,c3,c4].include? c5
yield β#{c1}#{c2}#{c3}β.to_i, β#{c4}#{c5}β.to_i
end
end
end
end
end
end
end
puts Gen.new.min { |(a,b),(c,d)| ab <=> cd }
Damn this is annoying
OK hereβs another one, this time with a recursive permutation generator.
It
should be easier to modify to other variations of this problem. (However
it
currently doesnβt permute arrays with duplicate elements)
class Permutations
include Enumerable
def initialize(src)
@data = src
end
def each(&blk)
permute([], @data.to_a, &blk)
end
def permute(base, rest, &blk)
if rest.empty?
yield base
else
rest.each { |elem| permute(base + [elem], rest - [elem], &blk) }
end
end
end
p Permutations.new(3β¦7).
map { |data| [data[0,3].join.to_i, data[3,2].join.to_i] }.
min { |(a,b),(c,d)| ab <=> cd }
My final offering, inspired by Park H.'s solution.
p (34567β¦76543).map { |x| [x/100 * (x%100), x] if x.to_s !~
/[^3-7]|(.).*\1/ }.compact.min
=> [product, nnnmm]
Regards,
Brian.