簡體   English   中英

Prolog座位限制

[英]Prolog seating constraints

我必須在Prolog中解決以下問題。 亞歷克斯,弗雷德和簡是3個孩子,他們用10米長的木板做了一個蹺蹺板 它們沿着木板標記了11個座位,每個位置相距一米。 座位數為-5,-4,-3,-2,-1,0,1,2,3,4,5,其中0為中心位置。 亞歷克斯,弗雷德和簡的重量分別為4,3和2個單位。 他們有興趣知道當他們三個坐在木板的某個地方時,他們如何讓蹺蹺板平衡,每個孩子都必須坐在不同的位置。

一個座位位置是Alex,Fred和Jane位於-4,2和5位置,因為(-4 * 4)+(2 * 3)+(5 * 2)= - 16 + 6 + 10 = 0。 Alex,Fred和Jane的另一個座位是-4,4和2,而另一個是-3,2和3。

我已經嘗試了以下解決此問題,但得到錯誤:錯誤:輸入錯誤: integer' expected, found [_G11889,_G11892,_G11895]'

任何人都可以幫助解釋我哪里出錯/如何去做?

提前謝謝了

:-use_module(library(clpfd)).

find(Seats):-
    Seats=[Alex, Fred, Jane],
    Seats in -5..5,
    all_different(Seats),
    (Alex*4+Fred*3+Jane*2)#=0,     % I am not sure about this line
    labeling([],Seats).

我會使用對稱性破壞來減少解決方案的數量。 簡單的對稱性是當(A,F,J)是解時,也是(-A,-F,-J)。 所以我們可以限制為J#> = 0,並記住如果J#\\ = 0,那么有一個翻轉的解決方案。

所以我們首先導入CLP(FD)庫:

Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.1.16)
Copyright (c) 1990-2014 University of Amsterdam, VU Amsterdam
?- use_module(library(clpfd)).

然后我們制定我們的查詢,而不是(in)/ 2應該使用(ins)/ 2,正如larsman已經注意到的那樣。 (in)/ 2的使用也導致錯誤消息。 線性形式周圍不需要括號。 所以我們得到:

?- Seats=[Alex, Fred, Jane],
   Seats ins -5..5,
   Jane #> 0,
   all_different(Seats),
   Alex*4+Fred*3+Jane*2 #= 0,
   label(Seats),
   write(Seats), nl, fail; true.
[-4,2,5]
[-4,4,2]
[-3,2,3]
[-2,0,4]
[-2,2,1]
[-1,-2,5]
[-1,0,2]
[0,-2,3]
[1,-4,4]
true.

您可以獲得不同重量的獨特解決方案,如果您需要沒有人坐在蹺蹺板中間。 重物15,10和6完成這項工作。 這是一個示例運行,請注意修改后的(ins)/ 2語句:

?- Seats=[Alex, Fred, Jane],
   Seats ins -5.. -1\/1..5,
   Jane #> 0,
   all_different(Seats),
   Alex*15+Fred*10+Jane*6 #= 0,
   label(Seats),
   write(Seats), nl, fail; true.
[-4,3,5]
true.

再見

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM