/* Global constraint elementn in Picat. From Global Constraint Catalogue http://www.emn.fr/x-info/sdemasse/gccat/Celementn.html """ Constraint elementn(INDEX,TABLE,ENTRIES) Purpose forall(i)[1,|ENTRIES|]:ENTRIES[i].entry=TABLE[INDEX+i-1].value Example (3,<6,9,2,9>,<2,9>) The elementn constraint holds since its third argument ENTRIES=<2,9> is set to the subsequence starting at the third (i.e., INDEX=3) item of the table TABLE=<6,9,2,9>. Usage The elementn constraint is useful for extracting of subsequence of fixed length from a given sequence. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import cp. main => go. go ?=> N = 4, S = 2, % length of sub sequence (must be fixed) Elements = new_list(N), Elements :: 1..9, Entries = new_list(S), Entries :: 1..9, TIndex :: 1..N, % Elements = [6,9,2,9], Elements = [2,9,2,9], % finds both occurrences (if TIndex is free) Entries = [2,9], % TIndex #= 3, elementn(TIndex, Elements, Entries), Vars = Elements ++ Entries ++ [TIndex], solve(Vars), println(elements=Elements), println(entries=Entries), println(tIndex=TIndex), nl, fail, nl. go => true. go2 ?=> N = 8, S = 4, % length of sub sequence (must be fixed) Elements = new_list(N), Elements :: 1..9, Entries = new_list(S), Entries :: 1..9, TIndex :: 1..N, Entries = [3,1,4,1], elementn(TIndex, Elements, Entries), Vars = Elements ++ Entries ++ [TIndex], solve(Vars), println(elements=Elements), println(entries=Entries), println(tIndex=TIndex), nl, fail, nl. go2 => true. % % Note: this use a variable TIindex, which makes is quite multidirectional. % elementn(TIndex, Elements, Entries) => foreach(I in 1..Entries.len) T #= TIndex+I-1, element(T,Elements,Entries[I]) end.