| 1 | % (c) 2009-2017 Lehrstuhl fuer Softwaretechnik und Programmiersprachen, | |
| 2 | % Heinrich Heine Universitaet Duesseldorf | |
| 3 | % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html) | |
| 4 | ||
| 5 | :- module(random_permutations, [get_num_bits/3, | |
| 6 | get_masks/3, | |
| 7 | random_permutation_element/10, | |
| 8 | init_random_permutations/0 | |
| 9 | ]). | |
| 10 | ||
| 11 | :- use_module(probsrc(module_information),[module_info/2]). | |
| 12 | :- module_info(group,cbc). | |
| 13 | :- module_info(description,'This module provides on-the-fly construction of random permutations of intervals.'). | |
| 14 | ||
| 15 | foreign_resource(random_permutations,[get_num_bits,draw_index]). | |
| 16 | foreign(get_num_bits, c, get_num_bits(+integer,-integer,-integer)). | |
| 17 | foreign(draw_index, c, draw_index(+integer,+integer,+integer,+integer,+integer,+integer,+integer,+integer,-integer,-integer)). | |
| 18 | ||
| 19 | :- dynamic is_initialised/0. | |
| 20 | ||
| 21 | init_random_permutations :- is_initialised,!. | |
| 22 | init_random_permutations :- | |
| 23 | load_foreign_resource(library(random_permutations)), | |
| 24 | assert(is_initialised). | |
| 25 | ||
| 26 | get_masks(HalfNumBits,LeftMask,RightMask) :- | |
| 27 | RightMask is (1 << HalfNumBits) - 1, | |
| 28 | LeftMask is RightMask << HalfNumBits. | |
| 29 | ||
| 30 | random_permutation_element(Index,MaxIndex,From,To,Seed,NumBits,LeftMask,RightMask,RandomElement,NextIndex) :- | |
| 31 | draw_index(Index,MaxIndex,Seed,NumBits,LeftMask,RightMask,From,To,DrawnElement,NextIndex), | |
| 32 | % working on a 4^x long interval. thus, we might pick a number that is too large | |
| 33 | % if this happens, we just pick a new one | |
| 34 | % to avoid context switching overhead, this is now done inside the C code | |
| 35 | RandomElement is DrawnElement + From. | |
| 36 | ||
| 37 | % ------------------- | |
| 38 | % Testing predicates | |
| 39 | % ------------------- | |
| 40 | % unused at the moment: | |
| 41 | %:- public shuffle/2. | |
| 42 | %:- use_module(library(system)). | |
| 43 | %shuffle(From,To) :- | |
| 44 | % init_random_permutations, | |
| 45 | % IntervalLength is To - From + 1, | |
| 46 | % get_num_bits(IntervalLength,MaxIndex,NumBits), | |
| 47 | % get_masks(NumBits,LeftMask,RightMask), | |
| 48 | % now(Seed), | |
| 49 | % shuffle(From,0,To,MaxIndex,Seed,NumBits,LeftMask,RightMask). | |
| 50 | %shuffle(From,CurIdx,To,MaxIndex,Seed,NumBits,LeftMask,RightMask) :- | |
| 51 | % random_permutation_element(CurIdx,MaxIndex,From,To,Seed,NumBits,LeftMask,RightMask,Drawn,NextIdx), | |
| 52 | % format('Drawing index ~w resulted in ~w~n',[CurIdx,Drawn]), | |
| 53 | % shuffle(From,NextIdx,To,MaxIndex,Seed,NumBits,LeftMask,RightMask). | |
| 54 | %shuffle(_,_,_,_,_,_,_,_). |