Created
September 26, 2013 20:29
-
-
Save rndmcnlly/6720071 to your computer and use it in GitHub Desktop.
Longest path problem, including trivial test case generator and solution visualization. Example output: http://chart.googleapis.com/chart?cht=gv:neato&chl=graph{node[shape=circle]35[penwidth=3];56[penwidth=3];23--74;58--69;37--68;17--57;23--67;48--52;28--42;25--34;51--55;11--29;1--26;2--11;7--37;11--42;32--71;13--70;18--60;20--46;4--51;25--30;23…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#begin_lua | |
function collect(pred,arity) | |
local t = {} | |
Assignment.begin(pred,arity) | |
while Assignment.next() do | |
if Assignment.isTrue() then | |
table.insert(t,Assignment.args()) | |
end | |
end | |
return t | |
end | |
function onModel() | |
local edges = collect("edge",2) | |
local chunks = {} | |
table.insert(chunks, "graph{node[shape=circle]") | |
for _,e in ipairs(collect("start",1)) do table.insert(chunks, tostring(e[1]).."[penwidth=3];") end | |
for _,e in ipairs(collect("finish",1)) do table.insert(chunks, tostring(e[1]).."[penwidth=3];") end | |
for _,e in ipairs(collect("vis_edge",2)) do table.insert(chunks, tostring(e[1]).."--"..tostring(e[2])..";") end | |
table.insert(chunks,"edge[penwidth=3];") | |
for _,e in ipairs(collect("link",2)) do table.insert(chunks, tostring(e[1]).."--"..tostring(e[2])..";") end | |
table.insert(chunks,"}") | |
local dot = table.concat(chunks,"") | |
print("http://chart.googleapis.com/chart?cht=gv:neato&chl="..dot) | |
end | |
math.randomseed(os.time()) | |
function flip(n,...) | |
if math.random() < 1.0/n then | |
return 1 | |
else | |
return 0 | |
end | |
end | |
#end_lua. | |
#const nodes = 75. | |
node(1..nodes). | |
edge(P,Q) :- node(P;Q), @flip(nodes,P,Q)==1. | |
edge(P,Q) :- edge(Q,P). % edges are bidirectional | |
1 { start(Node):node(Node) } 1. | |
1 { finish(Node):node(Node) } 1. | |
reached(Node) :- start(Node). | |
1 { link(Node,Peer):edge(Node,Peer) } 1 :- reached(Node), not finish(Node). | |
reached(Peer) :- link(Node,Peer). | |
:- finish(N), not reached(N). | |
#maximize { reached(N) }. | |
vis_edge(P,Q) :- edge(P,Q), P<Q, not link(P,Q), not link(Q,P). | |
#hide. | |
#show start/1. | |
#show finish/1. | |
#show link/2. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment