Skip to content

Commit

Permalink
Merge pull request #9 from TomPlum/feature/lcm
Browse files Browse the repository at this point in the history
Math | Added LCM to CollectionExtensions.kt
  • Loading branch information
TomPlum authored Dec 8, 2023
2 parents 1e41e79 + c77683d commit 8e17706
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ subprojects {
apply(plugin = "maven-publish")

ext {
set("releaseVersion", "2.3.1")
set("releaseVersion", "2.4.0")
}

repositories {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,28 @@ fun <T> List<T>.cartesianProductCubic(second: List<T>, third: List<T>): List<Tri
private fun <T> cartesianProduct(vararg sets: List<T>): List<List<T>> = sets.fold(listOf(listOf())) { acc, set ->
acc.flatMap { list -> set.map { element -> list + element } }
}

/**
* Calculates the lowest common multiple of
* all the long values of this given list.
*/
fun List<Long>.lcm(): Long {
if (this.isNotEmpty()) {
var result = this[0]
this.forEachIndexed { i, _ -> result = lcm(result, this[i]) }
return result
}

throw IllegalArgumentException("Cannot find the LCM of an empty list.")
}

private fun lcm(a: Long, b: Long) = a * (b / gcd(a, b))

private fun gcd(a: Long, b: Long): Long {
var n1 = a
var n2 = b
while (n1 != n2) {
if (n1 > n2) n1 -= n2 else n2 -= n1
}
return n1
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class CollectionExtensionsTest {
@Nested
Expand Down Expand Up @@ -103,4 +104,28 @@ class CollectionExtensionsTest {
return binary
}
}

@Nested
inner class LowestCommonMultiple {
@Test
fun twoValues() {
val values = listOf(4L, 2L)
val lcm = values.lcm()
assertThat(lcm).isEqualTo(4)
}

@Test
fun oneValue() {
val values = listOf(10L)
val lcm = values.lcm()
assertThat(lcm).isEqualTo(10)
}

@Test
fun emptyList() {
val values = listOf<Long>()
val e = assertThrows<IllegalArgumentException> { values.lcm() }
assertThat(e.message).isEqualTo("Cannot find the LCM of an empty list.")
}
}
}

0 comments on commit 8e17706

Please sign in to comment.