Skip to content

Commit

Permalink
Solve 'Integers: Recreation One' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Jun 20, 2024
1 parent 504b0bd commit 3cdff5a
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.2.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>

Expand Down
54 changes: 54 additions & 0 deletions src/main/kotlin/integersrecreationone/SumSquaredDivisors.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package solution

import java.util.stream.LongStream
import java.util.stream.LongStream.range

/**
* https://www.codewars.com/kata/55aa075506463dac6600010d/train/kotlin
*/
object SumSquaredDivisors {

fun listSquared(m: Long, n: Long): String {
return (m..n)
.asSequence()
.map { Pair(it, it.divisors()) }
.map { pair -> pair.mapSecond(LongStream::squareSum) }
.filter { it.second.isSquare() }
.map { it.toList() }
.toList()
.toString()
}
}

fun Long.divisors(): LongStream {
return range(1, this + 1)
.takeWhile { it * it <= this }
.filter { this % it == 0L }
.flatMap {
if (it * it == this)
LongStream.of(it)
else
LongStream.of(it, this / it)
}
}

fun LongStream.squareSum(): Long {
return this.map { it * it }.sum()
}

fun Long.sqrt(): Long {
return kotlin.math.sqrt(this.toDouble()).toLong()
}

fun Long.isSquare(): Boolean {
val sqrt = this.sqrt()
return sqrt * sqrt == this
}

fun Pair<Long, Long>.toList(): List<Long> {
return listOf(this.first, this.second)
}

fun <A, B, C> Pair<A, B>.mapSecond(f: (B) -> C): Pair<A, C> {
return Pair(this.first, f(this.second))
}
13 changes: 13 additions & 0 deletions src/test/kotlin/integersrecreationone/SumSquaredDivisorsTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package solution

import org.junit.Test
import kotlin.test.assertEquals

class SumSquaredDivisorsTest {

@Test
fun basicTests() {
assertEquals("[[1, 1], [42, 2500], [246, 84100]]", SumSquaredDivisors.listSquared(1, 250))
assertEquals("[[42, 2500], [246, 84100]]", SumSquaredDivisors.listSquared(42, 250))
}
}

0 comments on commit 3cdff5a

Please sign in to comment.