mirror of
https://github.com/sigmasternchen/gleam-community-maths
synced 2025-03-15 07:59:01 +00:00
Add cartesian_product func
This commit is contained in:
parent
7fbdfe1391
commit
0912bacf8c
2 changed files with 51 additions and 3 deletions
|
@ -29,6 +29,8 @@
|
|||
import gleam/list
|
||||
import gleam/int
|
||||
import gleam/float
|
||||
import gleam/set
|
||||
import gleam/io
|
||||
|
||||
/// <div style="text-align: right;">
|
||||
/// <a href="https://github.com/gleam-community/maths/issues">
|
||||
|
@ -146,7 +148,7 @@ pub fn permutation(arr: List(a)) -> List(a) {
|
|||
/// </a>
|
||||
/// </div>
|
||||
///
|
||||
/// Generate a list containing all combinations of one element from each of two given lists.
|
||||
/// Generate a list containing all combinations of pairs of elements coming from two given lists.
|
||||
///
|
||||
/// <details>
|
||||
/// <summary>Example:</summary>
|
||||
|
@ -165,6 +167,26 @@ pub fn permutation(arr: List(a)) -> List(a) {
|
|||
/// </a>
|
||||
/// </div>
|
||||
///
|
||||
pub fn cartesian_product(xarr: List(a), yarr: List(a)) -> List(a) {
|
||||
todo
|
||||
pub fn cartesian_product(xarr: List(a), yarr: List(a)) -> List(#(a, a)) {
|
||||
let xset: set.Set(a) =
|
||||
xarr
|
||||
|> set.from_list()
|
||||
let yset: set.Set(a) =
|
||||
yarr
|
||||
|> set.from_list()
|
||||
xset
|
||||
|> set.fold(
|
||||
set.new(),
|
||||
fn(accumulator0: set.Set(#(a, a)), member0: a) -> set.Set(#(a, a)) {
|
||||
set.fold(
|
||||
yset,
|
||||
accumulator0,
|
||||
fn(accumulator1: set.Set(#(a, a)), member1: a) -> set.Set(#(a, a)) {
|
||||
io.debug(#(member0, member1))
|
||||
set.insert(accumulator1, #(member0, member1))
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
|> set.to_list()
|
||||
}
|
||||
|
|
|
@ -20,3 +20,29 @@ pub fn list_trim_test() {
|
|||
|> listx.trim(1, 4)
|
||||
|> should.equal(Ok([2.0, 3.0, 4.0, 5.0]))
|
||||
}
|
||||
|
||||
pub fn list_cartesian_product_test() {
|
||||
// An empty lists returns an empty list
|
||||
[]
|
||||
|> listx.cartesian_product([])
|
||||
|> should.equal([])
|
||||
|
||||
// Test with some arbitrary inputs
|
||||
[1, 2, 3]
|
||||
|> listx.cartesian_product([1, 2, 3])
|
||||
|> should.equal([
|
||||
#(1, 1),
|
||||
#(1, 2),
|
||||
#(1, 3),
|
||||
#(2, 1),
|
||||
#(2, 2),
|
||||
#(2, 3),
|
||||
#(3, 1),
|
||||
#(3, 2),
|
||||
#(3, 3),
|
||||
])
|
||||
|
||||
[1.0, 10.0]
|
||||
|> listx.cartesian_product([1.0, 2.0])
|
||||
|> should.equal([#(1.0, 1.0), #(1.0, 2.0), #(10.0, 1.0), #(10.0, 2.0)])
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue