Skip to content

Commit

Permalink
helper class for repetitions of cyclic transformations
Browse files Browse the repository at this point in the history
  • Loading branch information
norganos committed Dec 15, 2023
1 parent a24a83b commit cdb1c89
Showing 1 changed file with 7 additions and 33 deletions.
40 changes: 7 additions & 33 deletions lib/src/main/kotlin/de/linkel/aoc/utils/repeatCycle/Repetition.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,14 @@ class RepetitionContext<T, H>(
private val iterations: Int,
private val transformation: (state: T) -> T,
private val hash: ((state: T) -> H)? = null,
private val maxHashes: Int = 100,
private val iterationsBeforeHashing: Int = 50
private val maxHashes: Int = 0
) {
fun <HO> withHashing(lambda: (state: T) -> HO): RepetitionContext<T, HO> {
fun <HO> withMemory(memorySize: Int, lambda: (state: T) -> HO): RepetitionContext<T, HO> {
return RepetitionContext<T, HO>(
iterations = this.iterations,
transformation = this.transformation,
hash = lambda,
maxHashes = this.maxHashes,
iterationsBeforeHashing = this.iterationsBeforeHashing
)
}
fun withMemorySize(value: Int): RepetitionContext<T, H> {
return RepetitionContext(
iterations = this.iterations,
transformation = this.transformation,
hash = this.hash,
maxHashes = value,
iterationsBeforeHashing = this.iterationsBeforeHashing
)
}
fun withMinimumTransformations(value: Int): RepetitionContext<T, H> {
return RepetitionContext(
iterations = this.iterations,
transformation = this.transformation,
hash = this.hash,
maxHashes = this.maxHashes,
iterationsBeforeHashing = value
)
}
fun withIterations(value: Int): RepetitionContext<T, H> {
return RepetitionContext(
iterations = value,
transformation = this.transformation,
hash = this.hash,
maxHashes = this.maxHashes,
iterationsBeforeHashing = value
maxHashes = memorySize,
)
}

Expand All @@ -51,7 +22,7 @@ class RepetitionContext<T, H>(
val hashLambda = hash
while (i < iterations) {
state = transformation(state)
if (iterationsBeforeHashing > i && hashLambda != null) {
if (hashLambda != null) {
val h = hashLambda(state)
val hi = lastIterations.indexOf(h)
if (hi > -1) {
Expand All @@ -72,3 +43,6 @@ class RepetitionContext<T, H>(
return state
}
}

fun <T> Int.repeatedTransformations(transformation: (state: T) -> T): RepetitionContext<T, Unit>
= RepetitionContext(this, transformation)

0 comments on commit cdb1c89

Please sign in to comment.