作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试解决 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).
我该如何解决这个难题?
最佳答案
查看 clpfd约束 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/
我是一名优秀的程序员,十分优秀!