mirror of
https://github.com/sigmasternchen/gleam-community-maths
synced 2025-03-15 07:59:01 +00:00
Fixed and tidied combinatorics.list_permutation function: it no longer mistakenly shortens lists with duplicates
This commit is contained in:
parent
009209253a
commit
788e142466
1 changed files with 5 additions and 21 deletions
|
@ -350,30 +350,14 @@ fn do_list_combination(arr: List(a), k: Int, prefix: List(a)) -> List(List(a)) {
|
|||
pub fn list_permutation(arr: List(a)) -> List(List(a)) {
|
||||
case arr {
|
||||
[] -> [[]]
|
||||
_ ->
|
||||
flat_map(
|
||||
arr,
|
||||
fn(x) {
|
||||
let remaining = list.filter(arr, fn(y) { x != y })
|
||||
list.map(list_permutation(remaining), fn(perm) { [x, ..perm] })
|
||||
},
|
||||
)
|
||||
_ -> {
|
||||
use x <- list.flat_map(arr)
|
||||
let assert Ok(#(_, remaining)) = list.pop(arr, fn(y) { x == y })
|
||||
list.map(list_permutation(remaining), fn(perm) { [x, ..perm] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Flat map function
|
||||
fn flat_map(list: List(a), f: fn(a) -> List(b)) -> List(b) {
|
||||
list
|
||||
|> list.map(f)
|
||||
|> concat()
|
||||
}
|
||||
|
||||
/// Concatenate a list of lists
|
||||
fn concat(lists: List(List(a))) -> List(a) {
|
||||
lists
|
||||
|> list.fold([], list.append)
|
||||
}
|
||||
|
||||
/// <div style="text-align: right;">
|
||||
/// <a href="https://github.com/gleam-community/maths/issues">
|
||||
/// <small>Spot a typo? Open an issue!</small>
|
||||
|
|
Loading…
Reference in a new issue