Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please Help me with this Problem

Status
Not open for further replies.

xonTAB

Programmer
Jan 4, 2007
2
MT
I was working on the following problem:

The Cartesian Product of two sets is the set containing all the tuples produced from one element of one set and second element from the other set. Consider the sets A = {a, b, c} and B = {1, 2, 3}
The cartesian product of A and B = A ? B
= { (a,1), (a,2), (a,3), (b,1), (b,2), (b,3), (c,1), (c,2), (c,3) }


Write a Prolog program in which it is possible to issue goals to display all the tuples produced from the Cartesian Product of any two sets, including the empty set.
e.g. cartesian_product ([a,b,c],[1,2,3]) would display:
a 1 a 2 a 3
b 1 b 2 b 3
c 1 c 2 c 3

How can you do it using Prolog?

Shaun Tabone
 
cartesian_product([H|T],B):- cartesian_product_1(H,B),cartesian_product(T,B).


cartesian_product_1(H,[H1,T1]):- put(H),write( {*spaces*} ),
put(H1),cartesian_product_1(H,T1).


its just a thought.i dont know whether it works, i didnt run it.if i had this problem this is what id think first.

if it happens that you dont understand,

cartesian_product takes each member of the first list and sends it to cartesian_product_1 along with the second list.then cartesian_product_1 puts on the screen every pair the members of the second list produce with the member of the first list passed from cartesian_product.

hope you get what i mean.

if it doesnt work think on it on your own but i guess it could be whole wrong.
 
Thanks Very Much. I tried to run your code but did not work. I tried to modify it a bit and it finally it worked.

cartesian_product([H|T],B):- cartesian_product_1(H,B),
nl,cartesian_product(T,B).
cartesian_product_1(H,[]).
cartesian_product_1(H,[H1|T1]):- write(H),
write(H1),write(' '),cartesian_product_1(H,T1).

Thanks a lot for your help.

 
happy to help man ;)
sorry for the mistakes as i said before its just what crossed my mind.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top