编写Prolog程序:判断列表中是否存在三个元素之和等于N
Hey there! Let's put together a clean Prolog solution to check if a given list has exactly three distinct elements that add up to a specified number N.
Approach
The core idea is to pick three unique elements from the list (so we don't reuse the same element multiple times) and verify if their sum matches N. We'll use Prolog's built-in select/3 predicate to safely extract elements one by one—this ensures each element comes from the remaining part of the list after the previous selection, avoiding duplicates.
Solution Code
% Main predicate: Checks if three distinct elements in List sum to N three_sum(List, N) :- % Pick first element A, leaving the rest of the list as Rest1 select(A, List, Rest1), % Pick second element B from Rest1, leaving Rest2 select(B, Rest1, Rest2), % Pick third element C from Rest2 select(C, Rest2, _), % Verify the sum of A, B, C equals N A + B + C =:= N.
How It Works
select(A, List, Rest1): Removes elementAfrom the original list, giving usRest1—this guaranteesAis part of the list and won't be picked again.select(B, Rest1, Rest2): PullsBfrom the remaining listRest1, ensuring it's a different element thanA.select(C, Rest2, _): ExtractsCfromRest2, making sure it's distinct from bothAandB.- Finally,
A + B + C =:= Nchecks if the arithmetic sum of the three elements matches our target number.
Test Cases
Let's validate with your examples:
For
List = [1,2,3,4,5,6]andN = 6:?- three_sum([1,2,3,4,5,6], 6). true.This returns
truebecause1 + 2 + 3 = 6.For
List = [2,5,7,9]andN = 12:?- three_sum([2,5,7,9], 12). false.All possible triplets sum to 14, 16, 18, or 21—none equal 12, so we get
false.
Quick Note
If you ever need to allow reusing the same element multiple times (like checking if three 2s sum to 6 in [2,3]), you can swap select/3 with member/2 instead. But based on your examples, the distinct-element approach is exactly what you need.
内容的提问来源于stack exchange,提问作者SpaceCow

