1

I have the following file with the predicate attends which symbolizes that every student attends a certain course (the first argument : Student_ID, the second argument : Course_ID).

attends(476, c216).
attends(478, c216).
attends(484, c216).
attends(487, c216).
attends(491, c216).

What I want to do is create a predicate-function which creates an examination schedule consisting of 3 lists (A,B,C) with courses.

Each list symbolizes a week. Then for instance to find the optimal schedule in order it suits most students, it prints out all the different permutations of courses in pairs of 3-3-2:

The list A is week one with courses [c204,c209,c210] in the first case bellow.

List B is week 2 etc...

?- schedule(A,B,C).
A = [c204,c209,c210],
B = [c212,c214,c216],
C = [c217,c218];

A = [c204,c209,c210],
B = [c212,c214,c216],
C = [c218,c217];

Problem 1:

So how can I take the attends/2 predicates and convert only the second argument to a List, in a manner that the list will contain all the courses that have been declared.

For example: L = [c212,c213...].

Problem 2:

The permutations will be done with a custom function called k_permutation/3:

delete(E,L,NL):-
  append(L1,[E|L2],L),
  append(L1,L2,NL).


k_permutation(0,_,[]).
k_permutation(K,L1,[X|T2]) :-
  K > 0,
  K1 is K - 1,
  delete(X,L1,L2),
  k_permutation(K1,L2,T2).

But for some reason this custom function (k_permutation/3) runs for infinite time. Is there something wrong with the functions recursion? How should the function be used?

tas
  • 8,100
  • 3
  • 14
  • 22
DIMITRIOS
  • 305
  • 1
  • 3
  • 10

1 Answers1

4

Well as for problem 1 the easy way would be:

collect_courses(L1):- findall(Course, attends(_,Course), L), sort(L,L1).

L will have all courses that appear in attends/2, so it will have duplicates, that's the reason we're using sort/2 which removes duplicates.

As for problem 2, first of all Swi-Prolog already has a definition of delete/3 predicate so I suggest that you rename it. Apart from that the k_permutations/2 works fine:

?- k_permutation(2,[1,2,3],L).
L = [1, 2] ;
L = [1, 3] ;
L = [2, 1] ;
L = [2, 3] ;
L = [3, 1] ;
L = [3, 2] ;
false.
coder
  • 12,832
  • 5
  • 39
  • 53