Download
# Licenced under CC-BY-4.0 : http://creativecommons.org/licenses/by/4.0/
MAIN MODEL Main_MagicSequence

  DECLARATION SECTION 

    PARAMETER:
       identifier   :  N
       initial data :  5 ;

    PARAMETER:
       identifier   :  N2
       definition   :  N-1 ;

    MATHEMATICAL PROGRAM:
       identifier   :  MagicSequencePlan
       direction    :  minimize
       constraints  :  AllConstraints
       variables    :  AllVariables
       type         :  CSP ;

    SET:
       identifier   :  ii
       subset of    :  Integers
       indices      :  i, j
       definition   :  ElementRange(0, N-1) ;

    VARIABLE:
       identifier   :  x
       index domain :  (i)
       range        :  {0..N2} ;

    CONSTRAINT:
       identifier   :  CCount
       index domain :  (i)
       definition   :  /* x(i) = Sum[j,  x(j) = i] */
                       cp::Count(j, x(j), i, '=', x(i)) ;

    CONSTRAINT:
       identifier   :  CSum
       definition   :  Sum[i, x(i)] = N
       comment      :  "Extra (redundant) constraint." ;

  ENDSECTION  ;

  PROCEDURE
    identifier :  MainInitialization

  ENDPROCEDURE  ;

  PROCEDURE
    identifier :  MainExecution
    body       :  
      ShowProgressWindow;
      solve MagicSequencePlan;
      
      if (MagicSequencePlan.ProgramStatus <> 'Optimal') then
           empty x;
      endif;

  ENDPROCEDURE  ;

  PROCEDURE
    identifier :  MainTermination
    body       :  
      if ( CaseSaveAll( confirm:2 ) = 1 ) then
          return 1;
      else
          return 0;
      endif ;

  ENDPROCEDURE  ;

ENDMODEL Main_MagicSequence ;