%%%%%%%%%%%%%%%%%%%  Magic Sequences    %%%%%%%%%%%%%%%%%%%
%  magic(N,L) takes as input an integer N, and produces   %
%  a list L of integers such that, for each k:0..N-1,     %
%  the k_th integer is the number of occurrences of k     %
%  in the list.                                           %
%  (The first member of the list is called the 0_th.)     %
%  magic(N,L) can also be used to check if a given list   %
%  is a "magic sequence"                                  %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

:- nodbgcomp.
:- lib(fd_global).

magic(N, L):-
        length(L,N),
        N1 is N-1,
        L:: 0..N1,
        ( foreach(X,L), for(I,0,N1), param(L) 
        do 
	    occurrences(I,L,X) 
	),
        ( for(J,0,N1), foreach(X, IntsToN1) do X=J ),
        IntsToN1 * L #= N,
        sum(L) #= N, !,
        writeln(setup_done),
        labelingff(L).


labelingff([]) :- !.
labelingff(List) :-
    deleteff(Var,List,Rest), !,
    indomain(Var),
    labelingff(Rest).

