mirror of
https://github.com/pgpainless/pgpainless.git
synced 2024-12-24 11:57:59 +01:00
Implement Cost
This commit is contained in:
parent
71f859af9b
commit
ec9753ad71
2 changed files with 65 additions and 0 deletions
|
@ -0,0 +1,36 @@
|
||||||
|
// SPDX-FileCopyrightText: 2023 Heiko Schaefer <heiko@schaefer.name>
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package org.pgpainless.wot.dijkstra
|
||||||
|
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A path's "cost".
|
||||||
|
*
|
||||||
|
* This Cost type is used for comparison in Dijkstra's algorithm.
|
||||||
|
*/
|
||||||
|
internal class Cost(
|
||||||
|
// The path's length (i.e., the number of hops to the target).
|
||||||
|
// *Less* length is "cheaper" (short paths require less "depth" in delegations).
|
||||||
|
val length: Int,
|
||||||
|
|
||||||
|
// The trust amount along this path.
|
||||||
|
// Smaller trust amount is "more expensive"
|
||||||
|
// (paths with a low trust amount are more constraining and thus less desirable).
|
||||||
|
val amount: Int,
|
||||||
|
) : Comparable<Cost> {
|
||||||
|
|
||||||
|
// "Smaller than" means: the path is "cheaper", and thus preferable:
|
||||||
|
// - A small length (requiring fewer hops).
|
||||||
|
// - For equal length: A higher "trust amount" (which is less constraining)
|
||||||
|
override fun compareTo(other: Cost) =
|
||||||
|
compareValuesBy(this, other, { it.length }, { -it.amount })
|
||||||
|
|
||||||
|
override fun toString() = "length $length, amount $amount"
|
||||||
|
|
||||||
|
/** Calculate the cost of a path, when adding a new segment with trust amount `amount` */
|
||||||
|
fun extendBy(amount: Int) = Cost(this.length + 1, min(amount, this.amount))
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
// SPDX-FileCopyrightText: 2023 Heiko Schaefer <heiko@schaefer.name>
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package org.pgpainless.wot.dijkstra
|
||||||
|
|
||||||
|
import kotlin.test.Test
|
||||||
|
|
||||||
|
class CostTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun cost() {
|
||||||
|
val cost1 = Cost(1, 60)
|
||||||
|
val cost2 = Cost(1, 120)
|
||||||
|
|
||||||
|
val cost3 = Cost(2, 60)
|
||||||
|
val cost4 = Cost(2, 120)
|
||||||
|
|
||||||
|
assert(cost1 > cost2) // cost2 is "cheaper": it constrains the amount of the path less
|
||||||
|
assert(cost1 < cost3) // cost2 is "cheaper": it costs fewer hops
|
||||||
|
|
||||||
|
assert(cost2 < cost3)
|
||||||
|
assert(cost3 > cost4)
|
||||||
|
|
||||||
|
assert(cost1 < cost4) // cost1 is "cheaper": even though it constrains the amount more, it costs fewer hops
|
||||||
|
assert(cost2 < cost4)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in a new issue