注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

一路

To find the final symmetry & beauty

 
 
 

日志

 
 
 
 

Solve eight queen problem using Prolog programing language  

2012-11-15 05:27:00|  分类: 学习笔记 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    Prolog programming language is not a general purpose programming language, even a not very run time efficient programming language. But the declarative way of solving logic problems is impressive. Often very difficult can be solved without much human involvement. Prolog is being used in field of artificial intelligent. Prolog is really interesting for the first time I saw it. In the following post, I show one example of using Prolog to solve famous eight-queen problem.

    Problem description can be found here.

http://en.wikipedia.org/wiki/Eight_queens_puzzle

As newbie to Prolog, there may not be elegant way to do things, but things are right. Prolog successfully compute all 92 ways to put queens on the board.

 

Attention please, prolog can do things but may not in a fully efficient way, here is an really efficient way to compute this eight queen problem based on backtrack bit operation algorithm.

 

http://saturnman.blog.163.com/blog/static/557611201102792959426/

 

The following is Prolog code with comments.

% get list len

size([],0).

size([Head|Tail],Value) :-

    size(Tail,TailValue),

    Value is 1 + TailValue.

 

% valid whole board

valid_board([]).

valid_board([Head|Tail]) :-

    valid_queen(Head),valid_board(Tail).

 

% column id should be in range (1..8)

valid_queen(Queen) :-

    Range = [1,2,3,4,5,6,7,8],

    member(Queen,Range).

 

% get all diagonal elements from upper left to lower right

diag_ul_lr([],[]).

diag_ul_lr([Head|Tail],[Value|DialTail]) :-

    size([Head|Tail],Count),

    Value is Head - Count,

    diag_ul_lr(Tail,DialTail).

 

% get all diagonal elements from upper right to lower left

diag_ur_ll([],[]).

diag_ur_ll([Head|Tail],[Value|DialTail]) :-

    size([Head|Tail],Count),

    Value is Head + Count,

    diag_ur_ll(Tail,DialTail).

%main function to compute valid eight queen configuration

eight_queen(Cols) :-

    length(Cols,8),

    valid_board(Cols),

    diag_ul_lr(Cols,UL_LR),

    diag_ur_ll(Cols,UR_LL),

    fd_all_different(Cols),

    fd_all_different(UL_LR),

    fd_all_different(UR_LL).

  评论这张
 
阅读(1573)| 评论(3)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017