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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*******************************************************************************
 * OscaR is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * (at your option) any later version.
 *  
 * OscaR is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License  for more details.
 *  
 * You should have received a copy of the GNU Lesser General Public License along with OscaR.
 ******************************************************************************/
package oscar.examples.cp.hakank
 
import oscar.cp.modeling._
 
import oscar.cp.core._
import scala.io.Source._
import scala.math._
 
/*
 
  Magic sequence problem in Oscar.
   
  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, ...
  """
 
  @author Hakan Kjellerstrand hakank@gmail.com
  
*/
object MagicSequence {
 
 
  def main(args: Array[String]) {
 
    val cp = CPSolver()
 
    //
    // data
    //
    val n = if (args.length > 0) args(0).toInt else 10;
    val all_values = Array.tabulate(n)(i=> (i,CPIntVar(0 to n-1)(cp)))
 
    //
    // variables
    //
    val x = Array.fill(n)(CPIntVar(0 to n-1)(cp))
 
    //
    // constraints
    //
    var numSols = 0
    cp.solve subjectTo {
 
      cp.add(weightedSum(0 to n, x) == n)
 
      cp.add(sum(x) == n)
 
      cp.add(gcc(x, all_values), Strong)
      for(i<- 0 until n) {
        cp.add(x(i) == all_values(i)._1)
      }
 
    } search {
        
      binary(x, -_.constraintDegree, _.min)
    } onSolution {
       
      println("\nSolution:")
      println("x: " + x.mkString(" "))
 
      numSols += 1
 
   }
   println(cp.start())
 
  }
 
}