Prolog: Finding all solutions

后端 未结 2 2098
情深已故
情深已故 2021-01-29 02:24

The title may look like it\'s a dime a dozen, but it\'s not. The object of this program is to take these classes (needs)

needs([[ece2090,1,m,13,16],
[ece3520,1,t         


        
2条回答
  •  没有蜡笔的小新
    2021-01-29 03:15

    This is probably an assignment, so I'll stop short of giving away a complete solution. But I would recommend structuring your information differently, to be more typical of how it's done in Prolog:

    need(ece2090, 1, [m, 13, 16]).
    need(ece3520, 1, [tu, 11, 14]).
    need(ece4420, 1, [w, 13, 16]).
    
    qualified_for(joel, ece2090).
    qualified_for(joel, ece2010).
    qualified_for(joel, ece3520).
    qualified_for(joel, ece4420).
    qualified_for(sam, ece2090).
    qualified_for(sam, ece4420).
    qualified_for(pete, ece3520).
    
    busy(joel, [m, 13, 16]).
    % busy(sam, []).  % absence of this fact means sam isn't busy
    busy(pete, [w, 13, 16]).
    busy(pete, [f, 9, 12]).
    

    Here, rather than having embedded lists in facts, each fact stands on its own. Each distinct functor is like one table in a database that you can query, and the different functors are different tables that are interrelated based upon some argument.

    So if you want to know what joel is qualified for:

    | ?- qualified_for(joel, C).
    
    C = ece2090 ? ;
    C = ece2010 ? ;
    C = ece3520 ? ;
    C = ece4420
    
    yes
    | ?-
    

    If you need a list of all the qualified TAs:

    | ?- setof(TA, C^qualified_for(TA, C), AllTAs).
    
    AllTAs = [joel,pete,sam]
    
    yes
    | ?-
    

    If you want to see what needed classes joel is available for and qualified to teach:

    | ?-  need(Class, I, Schedule), qualified_for(joel, Class), \+ busy(joel, Schedule).
    
    Class = ece3520
    I = 1
    Schedule = [tu,11,14] ? a
    
    Class = ece4420
    I = 1
    Schedule = [w,13,16]
    
    (1 ms) yes
    | ?-
    

    The assumption above is that "schedule" blocks are all described in the same way, [day, start, end] as you show, so they can simply be matched as entire 3-element lists. With a little extra effort, this can be more generalized to check days and time intervals in more detail. But that doesn't appear to be a requirement for you. The above are good building blocks to help solve your problem. It only requires a few lines of code (I used only 12 lines, plus the above facts). :)

提交回复
热议问题