#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Factorions
#

func max_power(b = 10) {
    var m = 1
    var f = (b-1)!
    while (m*f >= b**(m-1)) {
        m += 1
    }
    return m-1
}

func factorions(b = 10) {

    var result = []
    var digits = @^b
    var fact = digits.map { _! }

    for k in (1 .. max_power(b)) {
        digits.combinations_with_repetition(k, {|*comb|
            var n = comb.sum_by { fact[_] }
            if (n.digits(b).sort == comb) {
                result << n
            }
        })
    }
 
    return result
}

for b in (2..6) {
    var r = factorions(b)
    say "Base #{'%2d' % b} factorions: #{r}"
}
