How to print square of n*n given characters in prolog? - printing

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).

Related

Parsing an input file which contains polynomials

Hello experienced pythoners.
The goal is simply to read in my own files which have the following format, and to then apply mathematical operations to these values and polynomials. The files have the following format:
m1:=10:
m2:=30:
Z1:=1:
Z2:=-1:
...
Some very similar variables, next come the laguerre polynomials
...
F:= (12.58295)*L(0,x)*L(1,y)*L(6,z) + (30.19372)*L(0,x)*L(2,y)*L(2,z) - ...:
Where L stands for a laguerre polynomial and takes two arguments.
I have written a procedure in Python which splits apart each line into a left and right hand side split using the "=" character as a divider. The format of these files is always the same, but the number of laguerre polynomials in F can vary.
import re
linestring = open("file.txt", "r").read()
linestring = re.sub("\n\n","\n",str(linestring))
linestring = re.sub(",\n",",",linestring)
linestring = re.sub("\\+\n","+",linestring)
linestring = re.sub(":=\n",":=",linestring)
linestring = re.sub(":\n","\n",linestring)
linestring = re.sub(":","",linestring)
LINES = linestring.split("\n")
for LINE in LINES:
LINE = re.sub(" ","",LINE)
print "LINE=", LINE
if len(LINE) <=0:
next
PAIR = LINE.split("=")
print "PAIR=", PAIR
LHS = PAIR[0]
RHS = PAIR[1]
print "LHS=", LHS
print "RHS=", RHS
The first re.sub block just deals with formatting the file and discarding characters that python will not be able to process; then a loop is performed to print 4 things, LINE, PAIR, LHS and RHS, and it does this nicely. using the example file from above the procedure will print the following:
LINE= m1=1
PAIR= ['m1', '1']
LHS= m1
RHS= 1
LINE= m2=1
PAIR= ['m2', '1']
LHS= m2
RHS= 1
LINE= Z1=-1
PAIR= ['Z1', '-1']
LHS= Z1
RHS= -1
LINE= Z2=-1
PAIR= ['Z2', '-1']
LHS= Z2
RHS= -1
LINE= F= 12.5*L(0,x)L(1,y) + 30*L(0,x)L(2,y)L(2,z)
PAIR=['F', '12.5*L(0,x)L(1,y) + 30*L(0,x)L(2,y)L(2,z)']
LHS= F
RHS= 12.5*L(0,x)L(1,y) + 30*L(0,x)L(2,y)L(2,z)
My question is what is the next best step to process this output and use it in a mathematical script, especially assigning the L to mean a laguerre polynomial? I tried putting the LHS and RHS into a dictionary, but found it troublesome to put F in it due to the laguerre polynomials.
Any ideas are welcome. Perhaps I am overcomplicating this and there is a much simpler way to parse this file.
Many thanks in advance
Your parsing algorithm doesn't seem to work correctly, as the RHS of your variables dont produce the expected result.
Also the first re.sub block where you want to format the file seems overly complicated. Assuming every statement in your input file is terminated by a colon, you could get rid of all whitespace and newlines and seperate the statements using the following code:
linestring = open('file.txt','r').read()
strippedstring = linestring.replace('\n','').replace(' ','')
statements = re.split(':(?!=)',strippedstring)[:-1]
Then you iterate over the statements and split each one in LHS and RHS:
for st in statements:
lhs,rhs = re.split(':=',st)
print 'lhs=',lhs
print 'rhs=',rhs
In the next step, try to distinguish normal float variables and polynomials:
#evaluate rhs
try:
#interpret as numeric constant
f = float(rhs)
print " ",f
except ValueError:
#interpret as laguerre-polynomial
summands = re.split('\+', re.sub('-','+-',rhs))
for s in summands:
m = re.match("^(?P<factor>-?[0-9]*(\.[0-9]*)?)(?P<poly>(\*?L\([0-9]+,[a-z]\))*)", s)
if not m:
print ' polynomial misformatted'
continue
f = m.group('factor')
print ' factor: ',f
p = m.group('poly')
for l in re.finditer("L\((?P<a>[0-9]+),(?P<b>[a-z])\)",p):
print ' poly: L(%s,%s)' % (l.group("a"),l.group("b"))
This should work for your given example file.

Format string to number with minimum length in lua

For example I need number with minimum 3 digit
"512" --> 512
"24" --> 24.0
"5" --> 5.00
One option is write small function. Using answers here for my case it will be something like this
function f(value, w)
local p = math.ceil(math.log10(value))
local prec = value <= 1 and w - 1 or p > w and 0 or w - p
return string.format('%.' .. prec .. 'f', value)
end
print(f(12, 3))
But may be it is possible just using string.format() or any other simple way?
Ok, it seems this case beyond the string.format power. Thanks to #Schollii, this is my current variant
function f(value, w)
local p = math.ceil(math.log10(value))
local prec = value <= 1 and w - 1 or p > w and 0 or w - p
return string.format('%.' .. prec .. 'f', value)
end
print(f(12, 3))
There is no format code specifically for this since string.format uses printf minus a few codes (like * which would hace simplified the solution I give below). So you have to implement yourself, for example:
function f(num, w)
-- get number of digits before decimal
local intWidth = math.ceil(math.log10(num))
-- if intWidth > w then ... end -- may need this
local fmt='%'..w..'.' .. (w-intWidth) .. 'f'
return string.format(fmt, num)
end
print(f(12, 4))
print(f(12, 3))
print(f(12, 2))
print(f(512, 3))
print(f(24, 3))
print(f(5, 3))
You should probably handle case where integer part doesn't fit in field width given (return ceil or floor?).
You can't. Maximum you can reach - specify floating point precision or digit number, but you can't force output to be like your example. Lua uses C like printf with few limitations reference. Look here for full specifiers list link. Remember unsupported ones.
Writing a function would be the best and only solution, especially as your task looks strange, as it doesn't count decimal dot.

Prolog print value as result instead of true

I need to write a program, which returns a new list from a given list with following criteria.
If list member is negative or 0 it should and that value 3 times to new list. If member is positive it should add value 2 times for that list.
For example :
goal: dt([-3,2,0],R).
R = [-3,-3,-3,2,2,0,0,0].
I have written following code and it works fine for me, but it returns true as result instead of R = [some_values]
My code :
dt([],R):- write(R). % end print new list
dt([X|Tail],R):- X =< 0, addNegavite(Tail,X,R). % add 3 negatives or 0
dt([X|Tail],R):- X > 0, addPositive(Tail,X,R). % add 2 positives
addNegavite(Tail,X,R):- append([X,X,X],R,Z), dt(Tail, Z).
addPositive(Tail,X,R):- append([X,X],R,Z), dt(Tail, Z).
Maybe someone know how to make it print R = [] instead of true.
Your code prepares the value of R as it goes down the recursing chain top-to-bottom, treating the value passed in as the initial list. Calling dt/2 with an empty list produces the desired output:
:- dt([-3,2,0],[]).
Demo #1 - Note the reversed order
This is, however, an unusual way of doing things in Prolog: typically, R is your return value, produced in the other way around, when the base case services the "empty list" situation, and the rest of the rules grow the result from that empty list:
dt([],[]). % Base case: empty list produces an empty list
dt([X|Like],R):- X =< 0, addNegavite(Like,X,R).
dt([X|Like],R):- X > 0, addPositive(Like,X,R).
% The two remaining rules do the tail first, then append:
addNegavite(Like,X,R):- dt(Like, Z), append([X,X,X], Z, R).
addPositive(Like,X,R):- dt(Like, Z), append([X,X], Z, R).
Demo #2
Why do you call write inside your clauses?
Better don't have side-effects in your clauses:
dt([], []).
dt([N|NS], [N,N,N|MS]) :-
N =< 0,
dt(NS, MS).
dt([N|NS], [N,N|MS]) :-
N > 0,
dt(NS, MS).
That will work:
?- dt([-3,2,0], R).
R = [-3, -3, -3, 2, 2, 0, 0, 0] .
A further advantage of not invoking functions with side-effects in clauses is that the reverse works, too:
?- dt(R, [-3, -3, -3, 2, 2, 0, 0, 0]).
R = [-3, 2, 0] .
Of cause you can invoke write outside of your clauses:
?- dt([-3,2,0], R), write(R).
[-3,-3,-3,2,2,0,0,0]
R = [-3, -3, -3, 2, 2, 0, 0, 0] .

How do I use lhs and rhs to define a function?

In the Maxima session below, how come f(1) is not 0?
(%i1) eq: 2 * x + 1 = 3;
(%o1) 2 x + 1 = 3
(%i2) f(x) := lhs(eq) - rhs(eq);
(%o2) f(x) := lhs(eq) - rhs(eq)
(%i3) f(1);
(%o3) 2 x - 2
the process of function calling in maxima here binds x to 1 in the function
definition, lhs(eq)-rhs(eq). That has no x in it, so that binding does nothing.
Next, lhs(eq) is evaluated to 2*x+1. rhs(eq) is evaluated to 3. etc.
Do you always want the same equation eq? perhaps you want to do
define(f(x),lhs(eq)-rhs(eq));
to check what the definition is, try
grind(f);
If you want to vary the equation maybe something like
g(val, eq) := subst(val,x, lhs(eq)-rhs(eq)) ;
would do.

Create a path in a grid in prolog

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'

Resources