Prolog random permutation

Permuting a given list comes up as a subroutine of the REVERSE game. I’ve seen a pretty crazy implementation of shuffle which involves extracting a random element from the source list and putting it in the result. Pretty heavy on the Prolog engine. I think I got a slightly better one: iterate the given list, appending or prepending each element to the initially empty result, with a probability of 50%. Same shit.

permute([H|T], [H|R]) :-
random(X), X < 0.5, !,
permute(T, R).
permute([H|T], R) :-
permute(T, Q),
append(Q, [H], R).
permute([], []).

If append isn’t fast enough, you can always go crazy with difference lists.

The second cut is meant to avoid an extra unneeded unification attempt with the third predicate. Things work just as well without it.

GNU Prolog doesn’t seem to have a very good random number generator, so I gave it some slack:

permute_on_steroids(L, R) :-
permute(L, P),
permute(P, Q),
permute(Q, R).

Prolog “sorted” predicate

My interest in Prolog was recently revived, after briefly courting the P vs NP problem, which, I was hoping, might be made solvable by the machine. While playing with the thing, I found a Prolog solution to the REVERSE game. The exercise is trivial, the point of it being merely to compare the implementation in various programming languages.

The interesting detail, however, is how the author of the Prolog solution tests if a list is sorted:
sorted(L) :- sort(L, L).

You can’t comment because I got bored with cleaning up after all the spammers and disabled comments altogether. 😀 Long live DOS attacks (which btw are much older than technology – just try talking a woman out of her idea)!

To Iceland

Brave people of Iceland, do not let yourselves be robbed. Better to live a generation of isolation with an intact conscience that allows you to look your children in the eye than to succumb to the EU’s blackmails and endure a life of shame.

Those who know,,, know BDO what I’m talking about.


Back offline from a full day at work. The philosophical thoughts swarming through my mind this morning all gone. It’s amazing how ephemeral deep thinking can be for some.

Perhaps it’s the music playing at this time, or maybe it’s excitement in anticipation of tomorrow’s events. Or maybe work just drains you of philosophical thoughts in much the same way boiling drains vegetables of their best ingredients.

Be it as it may, Depeche Mode is beating to my heart, tomorrow will be the company’s NERF wars final, and my destination is approaching quickly. I suspect I have no more than 6-7 minutes till the journal closes once again.

My thoughts now go to my unborn daughter and to her mom and my love. I miss them and want to touch thep pregnant belly – that all so powerful symbol of life that dwarfs all prozaic human values in its majesty.

My station comes next. Sayonara!