Skip to content

Commit 3de0d36

Browse files
committed
Add 1.23
1 parent 9eab3ed commit 3de0d36

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

problems/lists.org

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,3 +314,26 @@ Success:
314314

315315
L = [4,5,6,7,8,9]
316316
#+end_src
317+
318+
* 1.23 (**) Extract a given number of randomly selected elements from a list.
319+
320+
The selected items shall be put into a result list.
321+
322+
It should not include duplicates, unless there are duplicates items in the given
323+
list.
324+
325+
Example:
326+
327+
#+begin_src teyjus-edit
328+
329+
> select-rnd [1,2,3,4,5,6,7,8] 3 L.
330+
331+
Success:
332+
333+
L = [5,4,1]
334+
#+end_src
335+
336+
Of course, your results will be random.
337+
338+
Hint: Use the built-in random number generator random.int/2 and the result of
339+
problem 1.20.

solutions/lists.mod

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,24 @@ range N N' _ :- N' < N, std.fatal-error "`range` with second index smaller than
251251
range N N [N].
252252
range N N' [N|Ns] :- range {util.succ N} N' Ns.
253253
254+
% 1.23
255+
% FIXME: Sometimes gets stuck at random.int. Report bug?
256+
pred select-rnd i:int, i:list A, o:list A.
257+
pred select-rnd.aux i:int, i:int, i:list A, o:list A.
258+
select-rnd N Ls Xs :-
259+
random.self_init,
260+
( select-rnd.aux N _ _ Xs
261+
& select-rnd.aux _ 0 _ Xs
262+
& pi M M' Len Len' Opts Acc X Rest Idx\
263+
select-rnd.aux M Len Opts Acc :-
264+
random.int Len Idx,
265+
select-nth Idx Opts X Rest,
266+
util.succ M M',
267+
util.succ Len' Len,
268+
select-rnd.aux M' Len' Rest [X|Acc]
269+
) => select-rnd.aux 0 {len Ls} Ls []
270+
.
271+
254272
}
255273
256274
@@ -301,6 +319,8 @@ tests :- test (list.last [1, 2, 3, 4] (some 4))
301319
& test (list.select-nth 2 [1,2,3,4] 2 [1,3,4])
302320
& test (list.insert-at 10 2 [1,2,3,4] [1,2,10,3,4])
303321
& test (list.range 4 9 [4,5,6,7,8,9])
322+
% FIXME
323+
% & test (list.select-rnd 3 [1,2,3,4,5,6,7,8] [_, _, _])
304324
.
305325
306326
pred main.

0 commit comments

Comments
 (0)