Skip to content

Commit cc9873e

Browse files
committed
feat(random): adding random:shuffle
1 parent 84b04cd commit cc9873e

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

Random.ark

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,22 @@
1313
(head _L)
1414
(@ _L (random 0 (- (len _L) 1)))))))
1515

16+
# @brief Shuffle a given list
17+
# @details The original list is not modified
18+
# @param _L list to shuffle
19+
# =begin
20+
# (import std.Random)
21+
# (let data [1 2 3 4 5])
22+
# (let randomized (random:shuffle data))
23+
# =end
24+
# @author https://github.com/SuperFola
25+
(let shuffle (fun (_L) {
26+
(mut _output [])
27+
28+
(while (not (empty? _L)) {
29+
(let _idx (random 0 (- (len _L) 1)))
30+
(append! _output (@ _L _idx))
31+
(pop! _L _idx) })
32+
33+
_output }))
34+

tests/random-tests.ark

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
(import std.Random)
2+
(import std.List :forEach :find)
23
(import std.Testing)
34

45
(test:suite random {
@@ -18,5 +19,18 @@
1819
(test:eq "1" (random:choice "111"))
1920
(test:eq "1" (random:choice "111"))
2021
(test:eq "1" (random:choice "111"))
21-
(test:eq "1" (random:choice "111")) })})
22+
(test:eq "1" (random:choice "111"))
23+
24+
(test:eq [] (random:shuffle []))
25+
(test:eq [1] (random:shuffle [1]))
26+
27+
(let data [0 1 2 3 4 5 6 7 8 9])
28+
(let randomized (random:shuffle data))
29+
(test:eq (len data) (len randomized))
30+
31+
(forEach
32+
randomized
33+
(fun (e)
34+
(test:expect (!= (list:find data e) -1))))
35+
})})
2236

0 commit comments

Comments
 (0)