I have to create a path between two given points in a grid in Prolog. The code I have so far is:
createPath(GridSize, BeginPosition, EndPosition, VisitedPoints, Path):-
nextStep(BeginPosition, NextStep, GridSize),
(
NextStep \== EndPosition,
->
nonmember(NextStep, VisitedPoints),
add(NextStep, VisitedPoints, NewVisitedPoints),
add(NextStep, Path, NewPath),
createPath(GridSize, NextStep, EndPosition, NewVisitedPoints, NewPath)
;
???
).
A little bit of explanation of my code:
GridSize is just an integer. If it is 2, the grid is a 2x2 grid. So all the grids are square.
The BeginPosition and EndPosition are shown like this: pos(X,Y).
The function nextStep looks for a valid neigbor of a given position. The values of X and Y have to be between 1 and the grid size. I've declared 4 different predicates of nextStep: X + 1, X - 1, Y + 1 and Y - 1.
This is the code:
nextStep(pos(X,Y),pos(X1,Y),GridSize):-
X1 is X + 1,
X1 =< GridSize.
nextStep(pos(X,Y),pos(X1,Y),_):-
X1 is X - 1,
X1 >= 1.
nextStep(pos(X,Y),pos(X,Y1),GridSize):-
Y1 is Y + 1,
Y1 =< GridSize.
nextStep(pos(X,Y),pos(X,Y1),_):-
Y1 is Y - 1,
Y1 >= 1.
nonmember returns true if a given element doesn't occur in a given list.
add adds an element to a given list, and returns the list with that element in it.
Another thing to know about VisitedPoints: Initially the BeginPosition and EndPosition are stored in that list. For example, if I want to find a path in a 2x2 grid, and I have to avoid point pos(2,1), then I will call the function like this:
createPath(2, pos(1,1), pos(2,2), [pos(1,1),pos(2,2),pos(2,1)], X).
The result I should get of it, should be:
X = [pos(1,2)]
Because that is the point needed to connect pos(1,1) and pos(2,2).
My question is, how can I stop the code from running when NextStep == EndPosition. In other words, what do I have to type at the location of the '???' ? Or am I handling this problem the wrong way?
I'm pretty new to Prolog, and making the step from object oriented languages to this is pretty hard.
I hope somebody can answer my question.
Kind regards,
Walle
I think you just placed the 'assignment' to path at the wrong place
createPath(GridSize, BeginPosition, EndPosition, VisitedPoints, Path):-
nextStep(BeginPosition, NextStep, GridSize),
(
NextStep \== EndPosition,
->
nonmember(NextStep, VisitedPoints),
add(NextStep, VisitedPoints, NewVisitedPoints),
% add(NextStep, Path, NewPath),
% createPath(GridSize, NextStep, EndPosition, NewVisitedPoints, NewPath)
createPath(GridSize, NextStep, EndPosition, NewVisitedPoints, Path)
;
% ???
% bind on success the output variable, maybe add EndPosition
Path = VisitedPoints
).
Maybe this is not entirely worth an answer, but a comment would be a bit 'blurry'
Related
I am using z3 to do bit blasting. I then solve the problem in a SAT solver, and do reverse bit blasting in order to find out what value the varibles take. However, I find that the solutions I get after doing reverse bit balsting do not live up to the constraints. As z3 does not save which values corrospond to what in the bit blasted reslult, I have used a piece of code from How can I access the variable mapping used when bit-blasting? to do that. I suspect that the problem might be here, as I get more varibles and constraints when using a bitmap than when I don't do it.
I have the following code:
x1 = BitVec('x1', 2)
x2 = BitVec('x2', 2)
g = Goal()
bitmap = {}
for i in range(2):
bitmap[(x1,i)] = Bool('x1'+str(i))
mask = BitVecSort(2).cast(math.pow(2,i))
g.add(bitmap[(x1,i)] == ((x1 & mask) == mask))
bitmap[(x2,i)] = Bool('x2'+str(i))
mask = BitVecSort(2).cast(math.pow(2,i))
g.add(bitmap[(x2,i)] == ((x2 & mask) == mask))
g.add(x1 + x2 == 3)
t = Then('simplify', 'bit-blast', 'tseitin-cnf')
subgoal = t(g)
For which I get the following solutions (x1 = 2, x2 =2), (x1 = 0, x2 = 0), (x1 = 1, x2 = 1) and (x1 = 3, x2 = 3).
For different constraints I get different solutions(x1 and x2 and not always the same), but they don't live up to the constraints.
There's nothing wrong with this encoding, and while it's hard to decipher the tseitin output from z3, I'd assume it's correct as well.
What you haven't shown us is the output of this "other" SAT solver, and more importantly, how you translate that back to z3. I suspect the bug is in there somewhere. But without seeing that code, it's impossible to answer your question. But as a guide, I'd look at the code that translates back the SAT output to your z3py variables. What code are you using for that purpose?
I have a finite set of pairs of type (int a, int b). The exact values of the pairs are explicitly present in the knowledge base. For example it could be represented by a function (int a, int b) -> (bool exists) which is fully defined on a finite domain.
I would like to write a function f with signature (int b) -> (int count), representing the number of pairs containing the specified b value as its second member. I would like to do this in z3 python, though it would also be useful to know how to do this in the z3 language
For example, my pairs could be:
(0, 0)
(0, 1)
(1, 1)
(1, 2)
(2, 1)
then f(0) = 1, f(1) = 3, f(2) = 1
This is a bit of an odd thing to do in z3: If the exact values of the pairs are in your knowledge base, then why do you need an SMT solver? You can just search and count using your regular programming techniques, whichever language you are in.
But perhaps you have some other constraints that come into play, and want a generic answer. Here's how one would code this problem in z3py:
from z3 import *
pairs = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 1)]
def count(snd):
return sum([If(snd == p[1], 1, 0) for p in pairs])
s = Solver()
searchFor = Int('searchFor')
result = Int('result')
s.add(Or(*[searchFor == d[0] for d in pairs]))
s.add(result == count(searchFor))
while s.check() == sat:
m = s.model()
print("f(" + str(m[searchFor]) + ") = " + str(m[result]))
s.add(searchFor != m[searchFor])
When run, this prints:
f(0) = 1
f(1) = 3
f(2) = 1
as you predicted.
Again; if your pairs are exactly known (i.e., they are concrete numbers), don't use z3 for this problem: Simply write a program to count as needed. If the database values, however, are not necessarily concrete but have other constraints, then above would be the way to go.
To find out how this is coded in SMTLib (the native language z3 speaks), you can insert print(s.sexpr()) in the program before the while loop starts. That's one way. Of course, if you were writing this by hand, you might want to code it differently in SMTLib; but I'd strongly recommend sticking to higher-level languages instead of SMTLib as it tends to be hard to read/write for anyone except machines.
I've been working on a project that renders a Mandelbrot fractal. For those of you who know, it is generated by iterating through the following function where c is the point on a complex plane:
function f(c, z) return z^2 + c end
Iterating through that function produces the following fractal (ignore the color):
When you change the function to this, (z raised to the third power)
function f(c, z) return z^3 + c end
the fractal should render like so (again, the color doesn't matter):
(source: uoguelph.ca)
However, when I raised z to the power of 3, I got an image extremely similar as to when you raise z to the power of 2. How can I make the fractal render correctly? This is the code where the iterations are done: (the variables real and imaginary simply scale the screen from -2 to 2)
--loop through each pixel, col = column, row = row
local real = (col - zoomCol) * 4 / width
local imaginary = (row - zoomRow) * 4 / width
local z, c, iter = 0, 0, 0
while math.sqrt(z^2 + c^2) <= 2 and iter < maxIter do
local zNew = z^2 - c^2 + real
c = 2*z*c + imaginary
z = zNew
iter = iter + 1
end
So I recently decided to remake a Mandelbrot fractal generator, and it was MUCH more successful than my attempt last time, as my programming skills have increased with practice.
I decided to generalize the mandelbrot function using recursion for anyone who wants it. So, for example, you can do f(z, c) z^2 + c or f(z, c) z^3 + c
Here it is for anyone that may need it:
function raise(r, i, cr, ci, pow)
if pow == 1 then
return r + cr, i + ci
end
return raise(r*r-i*i, 2*r*i, cr, ci, pow - 1)
end
and it's used like this:
r, i = raise(r, i, CONSTANT_REAL_PART, CONSTANT_IMAG_PART, POWER)
Write a Prolog program to print out a square of n*n given characters on the screen. Call your predicate square/2. The first argument should be a (positive) integer. the second argument the character (any Prolog term) to be printed. Example:
?-square(5, '*').
*****
*****
*****
*****
*****
Yes
I just start to learn this language. I did this:
square(_,'_').
square(N, 'B') :-
N>0,
write(N*'B').
It doesn't work at all. Can anyone help me?
So your question is, basically, "how do I write a loop nested in a loop?"
This is how you write an empty loop with an integer for a counter:
loop(0).
loop(N) :- N > 0, N0 is N-1, loop(N0).
which in C would be:
for(i=0; i < n; ++i) { }
And you seem to know already how to print (write(foo)).
Decompose the problem. To write an NxN square, you need to do two things:
Write N lines
Write a single line, consisting of N characters followed by a newline character.
The second is easy:
do_line(0,_) :-
nl
.
do_line(N,C) :-
N > 0 ,
write(C) ,
N1 is N-1 ,
do_line(N1,C)
.
The first isn't much more difficult:
do_lines(0,_,_).
do_lines(M,N,C) :-
M > 0 ,
do_line(N,C) ,
M1 is M-1 ,
do_lines(M1,N,C)
.
The all you need to do is wrap it:
write_square(N,C) :- do_lines(N,N,C) .
Easy!
You need to draw a line of N stars/characters
line(N,X):- N>0, N1 is N-1, line(N1,X), write(X), fail; true.
Then you will draw a column of N lines of stars/characters.
s(N,Chr):-sAux(N,0,Chr).
sAux(N,N,Chr).
sAux(N,C,Chr):-C<N, C1 is C+1, sAux(N, C1, Chr), line(N,Chr),nl.
s(N,Chr):- N>0, N1 is N-1, s(N1,X), linie(N,X), nl, fail;true.
Doing this:
square2(0,_). % base case, recursion stops when X reaches 0, second argument is irrelevent
square2(X,Symbol):-
X1 is X - 1,
write(Symbol),
square2(X1,Symbol).
With the query, which results in:
?- square2(5,'* ').
* * * * *
Therefore, we need another loop to make it write X times.
square1(0,_,_). % base case, recursion stops when X reaches 0
square1(X,Y,Symbol):-
X1 is X - 1,
square2(Y,Symbol), % with the same Y passed in square2 predicate to print a line of symbols
nl, % creates a new line
square1(X1,Y,Symbol).
However, the question is asking for the format with square(5, '* '). Therefore,
square(X,Symbol):-
square1(X,X,Symbol).
To wrap up:
square(X,Symbol):-
square1(X,X,Symbol).
square1(0,_,_).
square1(X,Y,Symbol):-
X1 is X - 1,
square2(Y,Symbol),
nl,
square1(X1,Y,Symbol).
square2(0,_).
square2(X,Symbol):-
X1 is X - 1,
write(Symbol),
square2(X1,Symbol).
I'm experimenting with the ImageTransformation function to try to make anamorphic versions of images, but with limited progress so far. I'm aiming for the results you get using the image reflected in a cylindrical mirror, where the image curves around the central mirror for about 270 degrees. The wikipedia article has a couple of neat examples (and I borrowed Holbein's skull from them too).
i = Import["../Desktop/Holbein_Skull.jpg"];
i = ImageResize[i, 120]
f[x_, y_] := {(2 (y - 0.3) Cos [1.5 x]), (2 (y - 0.3) Sin [1.5 x])};
ImageTransformation[i, f[#[[1]], #[[2]]] &, Padding -> White]
But I can't persuade Mathematica to show me the entire image, or to bend it correctly. The anamorphic image should wrap right round the mirror placed "inside" the centre of the image, but it won't. I found suitable values for constants by putting it inside a manipulate (and turning the resolution down :). I'm using the formula:
x1 = a(y + b) cos(kx)
y1 = a(y + b) sin(kx)
Any help producing a better result would be greatly appreciated!
In ImageTransformation[f,img], the function f is such that a point {x,y} in the resulting image corresponds to f[{x,y}] in img. Since the resulting image is basically the polar transformation of img, f should be the inverse polar transformation, so you could do something like
anamorphic[img_, angle_: 270 Degree] :=
Module[{dim = ImageDimensions[img], rInner = 1, rOuter},
rOuter = rInner (1 + angle dim[[2]]/dim[[1]]);
ImageTransformation[img,
Function[{pt}, {ArcTan[-#2, #1] & ## pt, Norm[pt]}],
DataRange -> {{-angle/2, angle/2}, {rInner, rOuter}},
PlotRange -> {{-rOuter, rOuter}, {-rOuter, rOuter}},
Padding -> White
]
]
The resulting image looks something like
anamorphic[ExampleData[{"TestImage", "Lena"}]]
Note that you can a similar result with ParametricPlot and TextureCoordinateFunction, e.g.
anamorphic2[img_Image, angle_: 270 Degree] :=
Module[{rInner = 1,rOuter},
rOuter = rInner (1 + angle #2/#1 & ## ImageDimensions[img]);
ParametricPlot[{r Sin[t], -r Cos[t]}, {t, -angle/2, angle/2},
{r, rInner, rOuter},
TextureCoordinateFunction -> ({#3, #4} &),
PlotStyle -> {Opacity[1], Texture[img]},
Mesh -> None, Axes -> False,
BoundaryStyle -> None,
Frame -> False
]
]
anamorphic2[ExampleData[{"TestImage", "Lena"}]]
Edit
In answer to Mr.Wizard's question, if you don't have access to ImageTransformation or Texture you could transform the image data by hand by doing something like
anamorph3[img_, angle_: 270 Degree, imgWidth_: 512] :=
Module[{data, f, matrix, dim, rOuter, rInner = 1.},
dim = ImageDimensions[img];
rOuter = rInner (1 + angle #2/#1 & ## dim);
data = Table[
ListInterpolation[#[[All, All, i]],
{{rOuter, rInner}, {-angle/2, angle/2}}], {i, 3}] &#ImageData[img];
f[i_, j_] := If[Abs[j] <= angle/2 && rInner <= i <= rOuter,
Through[data[i, j]], {1., 1., 1.}];
Image#Table[f[Sqrt[i^2 + j^2], ArcTan[i, -j]],
{i, -rOuter, rOuter, 2 rOuter/(imgWidth - 1)},
{j, -rOuter, rOuter, 2 rOuter/(imgWidth - 1)}]]
Note that this assumes that img has three channels. If the image has fewer or more channels, you need to adapt the code.