Download
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
44
45
46
47
48
49
50
51
52
53
54
55
/*
 
  Magic sequence in SICStus Prolog.
 
  From
  http://www.dcs.st-and.ac.uk/~ianm/CSPLib/prob/prob019/spec.html
  """
  A magic sequence of length n is a sequence of integers x0 . . xn-1
  between 0 and n-1, such that for all i in 0 to n-1, the number i
  occurs exactly xi times in the sequence.
  For instance, 6,2,1,0,0,0,1,0,0,0 is a magic sequence since 0 occurs
  6 times in it, 1 occurs twice, ...
  """
 
  Compare with the following models:
  
  Also, in the SICStus Prolog distribution there is a model
  using global_cardinality:
     library/clpfd/examples/magicseq.pl
 
 
  Model created by Hakan Kjellerstrand, hakank@gmail.com
  See also my SICStus Prolog page: http://www.hakank.org/sicstus/
 
*/
 
% Licenced under CC-BY-4.0 : http://creativecommons.org/licenses/by/4.0/
 
:-use_module(library(clpfd)).
:-use_module(library(lists)).
 
 
go :-
        N = 123,
        magic_sequence(N, Seq),
        write(Seq),nl,nl,
        fd_statistics.
 
 
% Note: after I wrote this I realized that count/4 is
%       deprecated in version 4.1.
magic_sequence(N, Seq) :-
        length(Seq,N),
        N1 is N-1,
        domain(Seq,0,N1),
 
        ( for(I,0,N1),
          foreach(S,Seq),
          param(Seq) do
              count(I,Seq,#=,S)
        ),
        sum(Seq,#=,N),
        labeling([leftmost,step,down], Seq).