all_your_base
 
% all_your_base.pi (in Picat)
% author:  Mike Bionchik & N.F. Zhou
% date: 06/22/2015
% http://code.google.com/codejam/contest/189252/dashboard#s=p0
% Round 1C 2009
% Problem A. All Your Base
%
% to use: picat all_your_base < input_file > output_file
%

% Intuition for this problem is similar to the minimum scalar product problem:
% In order to minimize the expression A*Base**N+B*Base**(N-1)...Z*Base**0, we
% need to arrange coefficients in the order A < B < ... < Z. So we simply map 
% the 'digits' from the highest to the lowest to 1,0,2,3..Base.

main =>
    T = to_int(read_line()),
    foreach(TC in 1..T)
        Ds = read_line(),
        do_case(TC, Ds)
    end.

do_case(TC, Ds) =>
    Uniq = Ds.remove_dups(),
    Map = new_map([K=V : {K,V} in zip(Uniq, [1,0|2..Uniq.length()])]),
    Result = compute(Map, Ds, max(2, Uniq.length()), 0),
    writef("Case #%w: %w%n", TC, Result).

compute(_Map, [],  _Base, Acc) = Acc.
compute(Map, [D|Ds], Base, Acc) = 
    compute(Map, Ds, Base, Acc*Base+Map.get(D)).