Skip to content

Commit

Permalink
✨ add cartesianProduct; combine combinations file into collections
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 25, 2024
1 parent 57e6133 commit 54a77fa
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 28 deletions.
36 changes: 36 additions & 0 deletions src/main/scala/org/lemon/advent/lib/collections.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,39 @@ extension [A](it: Iterator[A])
* @return the nth element of the iterator, or None if there is no nth element
*/
def nthOption(n: Int): Option[A] = it.drop(n).nextOption

extension [A](it: Iterable[A])
/** Returns an iterator view of the Cartesian product of this iterable and another.
* Also known as the cross product
*
* @param rhs the other iterable
* @return all pairs of elements (a, b) where a is from this iterable and b is from the other iterable
*/
def cartesianProduct[B](rhs: Iterable[B]): Iterator[(A, B)] =
for a <- it.iterator; b <- rhs.iterator yield (a, b)

/** Returns an iterator of all unordered pairs of elements in the iterable.
* If the collection contains duplicates, the pairs will not be unique.
*
* @return iterator of all unordered pairs
*/
def pairs: Iterator[(A, A)] =
for
(x, i) <- it.iterator.zipWithIndex
(y, j) <- it.iterator.zipWithIndex
if i < j
yield (x, y)

/** Returns an iterator of all unordered triples of elements in the iterable.
* If the collection contains duplicates, the triples will not be unique.
*
* @return iterator of all unordered triples
*/
def triples: Iterator[(A, A, A)] =
for
(x, i) <- it.iterator.zipWithIndex
(y, j) <- it.iterator.zipWithIndex
(z, k) <- it.iterator.zipWithIndex
if i < j
if j < k
yield (x, y, z)
28 changes: 0 additions & 28 deletions src/main/scala/org/lemon/advent/lib/combinations.scala

This file was deleted.

0 comments on commit 54a77fa

Please sign in to comment.