gpt4 book ai didi

prolog - 取自加德纳的谜题

转载 作者:行者123 更新时间:2023-12-01 15:52:38 25 4
gpt4 key购买 nike

我正在尝试解决 Prolog 中的以下难题:

Ten cells numbered 0,...,9 inscribe a 10-digit number such that each cell, say i, indicates the total number of occurrences of the digit i in this number. Find this number. The answer is 6210001000.

这是我在 Prolog 中写的,但我卡住了,我认为我的 ten_digit 谓词有问题:

%count: used to count number of occurrence of an element in a list

count(_,[],0).
count(X,[X|T],N) :-
count(X,T,N2),
N is 1 + N2.
count(X,[Y|T],Count) :-
X \= Y,
count(X,T,Count).

%check: f.e. position = 1, count how many times 1 occurs in list and check if that equals the value at position 1
check(Pos,List) :-
count(Pos,List,Count),
valueOf(Pos,List,X),
X == Count.

%valueOf: get the value from a list given the index
valueOf(0,[H|_],H).
valueOf(I,[_|T],Z) :-
I2 is I-1,
valueOf(I2,T,Z).

%ten_digit: generate the 10-digit number
ten_digit(X):-
ten_digit([0,1,2,3,4,5,6,7,8,9],X).

ten_digit([],[]).
ten_digit([Nul|Rest],Digits) :-
check(Nul,Digits),
ten_digit(Rest,Digits).

我该如何解决这个难题?

最佳答案

查看 约束 global_cardinality/2

例如,使用 SICStus Prolog 或 SWI:

:- use_module(library(clpfd)).

ten_cells(Ls) :-
numlist(0, 9, Nums),
pairs_keys_values(Pairs, Nums, Ls),
global_cardinality(Ls, Pairs).

示例查询及其结果:

?- time((ten_cells(Ls), labeling([ff], Ls))).1,359,367 inferences, 0.124 CPU in 0.124 seconds (100% CPU, 10981304 Lips)Ls = [6, 2, 1, 0, 0, 0, 1, 0, 0, 0] ;319,470 inferences, 0.028 CPU in 0.028 seconds (100% CPU, 11394678 Lips)false.

这给了你一个解决方案,也表明它是独一无二的。

关于prolog - 取自加德纳的谜题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35485185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com