Print a list from a matrix - prolog

I need a function that given an input of this style:
printMatrix(N, M)
where N is an integer and M a list of integers:
printMatrix(3, [1,5,8,9 ...]).
Where 3 is the number of rows and columns of a board.
The successive integers mark the box number (1 would be equivalent to position 1 (row), 1 (column) of the matrix, 2 the 1,2, 3 the 1,3, 4 the 2,1, 5 the 2 , 2, 6 the 2.3, 7 the 3.1, 8 the 3.2 and 9 the 3.3). You have to paint an 'X' for each number that appears in the list.
The output sought in this example would be the following:
-------
| X | | |
-------
| | X | |
-------
| | X | X |
I don't even know how to start, any help is welcomed.

You can compute the index of each box easily. Then iterate over every row and every column and check whether its corresponding index is in the input list, printing the required value along the way (either a 'X' or a ' ', also interleaving the box's walls):
printMatrix(N, M):-
Width is 2*N+1,
format('~`-t~*|', [Width]),
forall(between(1,N,Row),
(
SBase is N*(Row-1)+1,
EBase is N*Row,
nl,
write('|'),
forall(between(SBase,EBase,Item),
(
(memberchk(Item, M)->write('X');write(' ')),
write('|')
))
)),
nl,
format('~`-t~*|', [Width]).
Here I use forall/2 and between/3 predicates to iterate over rows and columns, and memberchk/2 to see if the item is in the list.
Sample output:
?- printMatrix(3,[1,4,5,9]).
-------
|X| | |
|X|X| |
| | |X|
-------

You can start from something like from this basic solution where the matrix has elements from 0 to 8 in case of 3x3:
test:-
% -------
% | 0 | 1 | 2 |
% | 3 | 4 | 5 |
% | 6 | 7 | 8 |
N = 3,
L = [1,5,7],
NN is N*N,
write('|'),
loop(0,NN,N,L).
check_newline(I,_,I):- !.
check_newline(V,Mod,Max):-
V < Max, !,
( 0 =:= mod(V,Mod) -> nl,write('|'); true).
loop(H,H,_,_):- !.
loop(I,Max,N,[]):-
I < Max, !,
write('_|'),
I1 is I+1,
check_newline(I1,N,Max),
loop(I1,Max,N,[]).
loop(H,Max,N,[H|T]):-
H < Max, !,
write('X|'),
H1 is H+1,
check_newline(H1,N,Max),
loop(H1,Max,N,T).
loop(H,Max,N,[E|T]):-
H < Max, !,
H \= E,
write('_|'),
H1 is H+1,
check_newline(H1,N,Max),
loop(H1,Max,N,[E|T]).
?- test.
|_|X|_|
|_|_|X|
|_|X|_|
true
Then you can complicate the code and do all sort of fancy stuff and maybe write shorter code.

Related

Max sum in the vector, according to the condition, which is defined by another vector

I have 2 variables in the data.frame: a, b.
I need to find the max sum of a, where sum of b = x.
Ok, for example:
| a | b |
|401| 2 |
|380| 3 |
|380| 2 |
|370| 1 |
So, for sum(b)=1, max(sum(a)) = 370, for sum(b)=2, max(sum(a))=401 etc.
How can I find a solution to this problem?
Not sure that this problem can be solved using linear programming

Prolog Extended Euclidian Algorithm

I have been struggling with some prolog code for several days and I couldn't find a way out of it. I am trying to write the extended Euclidean algorithm and find values p and s in :
a*p + b*s = gcd(a,b)
equation and here is what I have tried :`
common(X,X,X,_,_,_,_,_,_).
common(0,Y,Y,_,_,_,_,_,_).
common(X,0,X,_,_,_,_,_,_).
common(X,Y,_,1,0,L1,L2,SF,TF):-
append(L1,1,[H]),
append(L2,0,[A]),
SF is H ,
TF is A,
common(X,Y,_,0,1,[H],[A],SF,TF).
common(X,Y,_,0,1,L1,L2,SF,TF):-
append(L1,0,[_,S2]),
append(L2,1,[_,T2]),
Q is truncate(X/Y),
S is 1-Q*0,T is 0-Q*1 ,
common(X,Y,_,S,T,[S2,S],
[T2,T],SF,TF).
common(X,Y,N,S,T,[S1,S2],[T1,T2],SF,TF):-
Q is truncate(X/Y),
K is X-(Y*Q),
si_finder(S1,S2,Q,SF),
ti_finder(T1,T2,Q,TF),
common(Y,K,N,S,T,[S2,S],[T2,T],SF,TF).
si_finder(PP,P,Q,C):- C is PP - Q*P.
ti_finder(P2,P1,QA,C2):- C2 is P2 - QA*P1.
After a little search I found that s and p coefficients start from 1 and 0 and the second values for them are 0 and 1 respectively.Then it continues in a pattern which is what I have done in si_finder and ti_finder predicates.Common predicates are where I tried to control the pattern recursively. However the common predicates keeps on returning false in every call. Can anyone help me implement this algorithm in Prolog.
Thanks in advance.
First let's think about the arity of the predicate. Obviously you want to have the numbers A and B as well as the Bézout coefficients P and S as arguments. Since the algorithm is calculating the GCD anyway, it is opportune to have that as an argument as well. That leaves us with arity 5. As we're talking about the extended Euclidean algorithm, let' call the predicate eeuclid/5. Next, consider an example: Let's use the algorithm to calculate P, S and GCD for A=242 and B=69:
quotient (Q) | remainder (B1) | P | S
-------------+-------------------+-------+-------
| 242 | 1 | 0
| 69 | 0 | 1
242/69 = 3 | 242 − 3*69 = 35 | 1 | -3
69/35 = 1 | 69 − 1*35 = 34 | -1 | 4
35/34 = 1 | 35 − 1*34 = 1 | 2 | -7
34/1 = 34 | 34 − 34*1 = 0 | -69 | 242
We can observe the following:
The algorithm stops if the remainder becomes 0
The line before the last row contains the GCD in the remainder column (in this example 1) and the Bézout coefficients in the P and S columns respectively (in this example 2 and -7)
The quotient is calculated from the previous to remainders. So in the next iteration A becomes B and B becomes B1.
P and S are calculated from their respective predecessors. For example: P3 = P1 - 3*P2 = 1 - 3*0 = 1 and S3 = S1 - 3*S2 = 0 - 3*1 = -3. And since it's sufficient to have the previous two P's and S's, we might as well pass them on as pairs, e.g. P1-P2 and S1-S2.
The algorithm starts with the pairs P: 1-0 and S: 0-1
The algorithm starts with the bigger number
Putting all this together, the calling predicate has to ensure that A is the bigger number and, in addition to it's five arguments, it has to pass along the starting pairs 1-0 and 0-1 to the predicate describing the actual relation, here a_b_p_s_/7:
:- use_module(library(clpfd)).
eeuclid(A,B,P,S,GCD) :-
A #>= B,
GCD #= A*P + B*S, % <- new
a_b_p_s_(A,B,P,S,1-0,0-1,GCD).
eeuclid(A,B,P,S,GCD) :-
A #< B,
GCD #= A*P + B*S, % <- new
a_b_p_s_(B,A,S,P,1-0,0-1,GCD).
The first rule of a_b_p_s_/7 describes the base case, where B=0 and the algorithm stops. Then A is the GCD and P1, S1 are the Bézout coefficients. Otherwise the quotient Q, the remainder B1 and the new values for P and S are calculated and a_b_p_s_/7 is called with those new values:
a_b_p_s_(A,0,P1,S1,P1-_P2,S1-_S2,A).
a_b_p_s_(A,B,P,S,P1-P2,S1-S2,GCD) :-
B #> 0,
A #> B, % <- new
Q #= A/B,
B1 #= A mod B,
P3 #= P1-(Q*P2),
S3 #= S1-(Q*S2),
a_b_p_s_(B,B1,P,S,P2-P3,S2-S3,GCD).
Querying this with the above example yields the desired result:
?- eeuclid(242,69,P,S,GCD).
P = 2,
S = -7,
GCD = 1 ;
false.
And indeed: gcd(242,69) = 1 = 2*242 − 7*69
EDIT: On a second thought I would suggest to add two constraints. Firstly Bézout's identity before calling a_b_p_s_/7 and secondly A #> B after the first goal of a_b_p_s_/7. I edited the predicates above and marked the new goals. These additions make eeuclid/5 more versatile. For example, you could ask what numbers A and B have the Bézout coefficients 2 and -7 and 1 as the gcd. There is no unique answer to this query and Prolog will give you residual goals for every potential solution. However, you can ask for a limited range for A and B, say between 0 and 50 and then use label/1 to get actual numbers:
?- [A,B] ins 0..50, eeuclid(A,B,2,-7,1), label([A,B]).
A = 18,
B = 5 ;
A = 25,
B = 7 ;
A = 32,
B = 9 ;
A = 39,
B = 11 ;
A = 46,
B = 13 ;
false. % <- previously loop here
Without the newly added constraints the query would not terminate after the fifth solution. However, with the new constraints Prolog is able to determine, that there are no more solutions between 0 and 50.

How to find all tuples in a table if and only if the tuple appears once?

I have a table:
x | y | z
------------
1 | 1 | *
1 | 1 | *
1 | 3 | *
2 | 2 | *
2 | 3 | *
3 | 4 | *
3 | 4 | *
3 | 3 | *
What is the relational algebra representation of only returning all unique (x, y) tuples?
For example, I would like the following (x,y) tuples returned in the above table: (1,3), (2,2) (2,3), and (3,3).
Thanks
Rename R to S
S := ρS/R(R)
Join R and S on x,y
D := R ⋈S.x = R.x ∧ S.y = R.y S
This squares the number of tuples with a particular value for (x,y). Particularly, if a value for (x,y) appears only once in R, it appears only once in D.
Join R and S on x,y,z
E := R ⋈S.x = R.x ∧ S.y = R.y ∧ S.z = R.z S
This basically adds some columns to R. It does not add or remove tuples.
Subtract E from D and project to the attributes of R
F := πx,y,z(D\E)
This removes the tuples from D, that where created by joining a tuple from R to the corresponding tuple in S. The remaining tuples are the ones that where created by joining a tuple in R to a different tuple in S. Particularly, if a value for (x,y) appears only once in R, no tuple in F exists with that value.
Remove the tuples in F from R
R\F

How to find the maximum number of matching data?

Given a bidimensionnal array such as:
-----------------------
| | 1 | 2 | 3 | 4 | 5 |
|-------------------|---|
| 1 | X | X | O | O | X |
|-------------------|---|
| 2 | O | O | O | X | X |
|-------------------|---|
| 3 | X | X | O | X | X |
|-------------------|---|
| 4 | X | X | O | X | X |
-----------------------
I have to find the largest set of cells currently containing O with a maximum of one cell per row and one per column.
For instance, in the previous example, the optimal answer is 3, when:
row 1 goes with column 4;
row 2 goes with column 1 (or 2);
row 3 (or 4) goes with column 3.
It seems that I have to find an algorithm in O(CR) (where C is the number of columns and R the number of rows).
My first idea was to sort the rows in ascending order according to its number on son. Here is how the algorithm would look like:
For i From 0 To R
For j From 0 To N
If compatible(i, j)
add(a[j], i)
Sort a according to a[j].size
result = 0
For i From 0 To N
For j From 0 to a[i].size
if used[a[i][j]] = false
used[a[i][j]] = true
result = result + 1
break
Print result
Altough I didn't find any counterexample, I don't know whether it always gives the optimal answer.
Is this algorithm correct? Is there any better solution?
Going off Billiska's suggestion, I found a nice implementation of the "Hopcroft-Karp" algorithm in Python here:
http://code.activestate.com/recipes/123641-hopcroft-karp-bipartite-matching/
This algorithm is one of several that solves the maximum bipartite matching problem, using that code exactly "as-is" here's how I solved example problem in your post (in Python):
from collections import defaultdict
X=0; O=1;
patterns = [ [ X , X , O , O , X ],
[ O , O , O , X , X ],
[ X , X , O , X , X ],
[ X , X , O , X , X ]]
G = defaultdict(list)
for i, x in enumerate(patterns):
for j, y in enumerate(patterns):
if( patterns[i][j] ):
G['Row '+str(i)].append('Col '+str(j))
solution = bipartiteMatch(G) ### function defined in provided link
print len(solution[0]), solution[0]

What does the % operator do in Ruby in N % 2?

if counter % 2 == 1 I am trying to decode this line - it's a Rails project and I am trying to figure out what the % does in this if statement.
% is the modulo operator. The result of counter % 2 is the remainder of counter / 2.
n % 2 is often a good way of determining if a number n is even or odd. If n % 2 == 0, the number is even (because no remainder means that the number is evenly divisible by 2); if n % 2 == 1, the number is odd.
In answer to the question "What does the % symbol do or mean in Ruby?" It is:
1) The modulo binary operator (as has been mentioned)
17 % 10 #=> 7
2) The alternative string delimiter token
%Q{hello world} #=> "hello world"
%Q(hello world) #=> "hello world"
%Q[hello world] #=> "hello world"
%Q!hello world! #=> "hello world"
# i.e. choose your own bracket pair
%q(hello world) #=> 'hello world'
%x(pwd) #=> `pwd`
%r(.*) #=> /.*/
3) The string format operator (shorthand for Kernel::sprintf)
"05d" % 123 #=> "00123"
That's the modulo operator. It gives the remainder when counter is divided by 2.
For example:
3 % 2 == 1
2 % 2 == 0
Regardless of how it works, the modulo operator is probably not the best code for the purpose (even though we are not given much context). As Jörg mentioned in a comment, the expression if counter.odd? is probably the intent, and is more readable.
If this is view code and used to determine (for example) alternating row colors, then you may be able to do without the counter altogether by using the built-in Rails helper cycle(). For example, you can use cycle('odd','even') as a class name for a table row, eliminating the counter and surrounding if/then logic.
Another thought: if this is within an each block, you may be able to use each_with_index and eliminate the extraneous counter variable.
My refactoring $0.02.
Also keep in mind that, Ruby's definition of the modulo (%) operator differs from that of C and Java. In Ruby, -7%3 is 2. In C and Java, the result is -1 instead. In Ruby, the sign of the result (for % operator) is always the same as the sign of the second operand.
Its the modulo operator.
http://en.wikipedia.org/wiki/Modulo_operation
It is the modulo operator, which is a fancy way of saying it's the remainder operator.
So if you divided a number by two, and the integer remainder of that number is one, then you know the number was odd. Your example checks for odd numbers.
Often this is done to highlight odd number rows with a different background color, making it easier to read large lists of data.
This is a very basic question. % is the modulo opereator if counter % 2 == 1 results to true for every odd number and to false for every even number.
If you're learning ruby you should learn how to use irb, there you can try things out and perhaps answer the question yourself.
try to enter
100.times{|i| puts "#{i} % 2 == 1 #=> #{i % 2 == 1}"}
into your irb irb console and see the output, than it should be clear what % does.
And you really should take a look at the rails api documentation (1.9, 1.8.7, 1.8.7), there you would have found the answer two your question % (Fixnum) with a further link to a detailed description of divmod (Numeric):
Returns an array containing the quotient and modulus obtained by dividing num by aNumeric. > If q, r = x.divmod(y), then
q = floor(float(x)/float(y))
x = q*y + r
The quotient is rounded toward -infinity, as shown in the following table:
a | b | a.divmod(b) | a/b | a.modulo(b) | a.remainder(b)
------+-----+---------------+---------+-------------+---------------
13 | 4 | 3, 1 | 3 | 1 | 1
------+-----+---------------+---------+-------------+---------------
13 | -4 | -4, -3 | -3 | -3 | 1
------+-----+---------------+---------+-------------+---------------
-13 | 4 | -4, 3 | -4 | 3 | -1
------+-----+---------------+---------+-------------+---------------
-13 | -4 | 3, -1 | 3 | -1 | -1
------+-----+---------------+---------+-------------+---------------
11.5 | 4 | 2, 3.5 | 2.875 | 3.5 | 3.5
------+-----+---------------+---------+-------------+---------------
11.5 | -4 | -3, -0.5 | -2.875 | -0.5 | 3.5
------+-----+---------------+---------+-------------+---------------
-11.5 | 4 | -3, 0.5 | -2.875 | 0.5 | -3.5
------+-----+---------------+---------+-------------+---------------
-11.5 | -4 | 2 -3.5 | 2.875 | -3.5 | -3.5
Examples
11.divmod(3) #=> [3, 2]
11.divmod(-3) #=> [-4, -1]
11.divmod(3.5) #=> [3, 0.5]
(-11).divmod(3.5) #=> [-4, 3.0]
(11.5).divmod(3.5) #=> [3, 1.0]
To give a few ways to say it:
Modulo operator
Remainder operator
Modular residue
Strictly speaking, if a % b = c, c is the unique constant such that
a == c (mod b) and 0 <= c < b
Where x == y (mod m) iff x - y = km for some constant k.
This is equivalent to the remainder. By some well known theorem, we have that a = bk + c for some constant k, where c is the remainder, which gives us a - c = bk, which obviously implies a == c (mod b).
(Is there a way to use LaTeX on Stackoverflow?)

Resources