0

My task is to write a rule in SWI Prolog, which takes two strings as input. It should then divide and merge them at a random point and generate two new lists.

Example:

?- crossover([a,r,s,u,p],[b,t,c,z,k],NewList1,NewList2).
NewList1 = [a,r,s,z,k]
NewList2 = [b,t,c,u,p]

I have no idea how to split lists at a random point and then generating two new lists from there.. Thanks a lot in advance to anyone who can help! :)

1 Answers1

1

Here's something that worked for me

split_at(X,I,Left,Right) :-
    length(Left,I),
    append(Left,Right,X).

crossover(X,Y,Z1,Z2) :-
    length(X,Len),
    random_between(0,Len,Cut),
    split_at(X,Cut,X1,X2),
    split_at(Y,Cut,Y1,Y2),
    append(X1,Y2,Z1),
    append(Y1,X2,Z2).
madeofmistake
  • 528
  • 2
  • 7