All Downloads are FREE. Search and download functionalities are using the official Maven repository.

loggersoft.kotlin.utils.graph.PathImpl.kt Maven / Gradle / Ivy

/*
 * Copyright (C) 2018 Alexander Kornilov ([email protected])
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package loggersoft.kotlin.utils.graph

import loggersoft.kotlin.utils.oneOrNull
import java.lang.IllegalStateException

internal class PathImpl(override val startFrom: V, override val endWith: V, override val edges: List>) : Path {

    override fun equals(other: Any?): Boolean
            = other != null && (this === other || (other is PathImpl<*, *> && edges == other.edges))

    override fun hashCode(): Int = edges.hashCode()

    override val size: Int
        get() = path.size

    override val weight: Double = edges.filter { it.hasWeight }.sumByDouble { it.weight }

    override fun get(index: Int): Pair> = path[index]

    override fun iterator(): Iterator>> = path.iterator()

    override fun compareTo(other: Path): Int = compareValuesBy(this, other, Path::weight)

    private val path: List>> by lazy { makePath() }

    private fun makePath(): List>> {
        require(edges.first().isStartFrom(startFrom))
        require(edges.last().isEndWith(endWith))
        return edges.mapIndexed { index, edge -> Pair(if (index > 0) intersectionOf(edges[index - 1], edge) ?: throw IllegalStateException() else startFrom, edge) }
    }

    private fun intersectionOf(incoming: Edge, outgoing: Edge): V?
            = incoming.incomingNodes().intersect(outgoing.outgoingNodes()).oneOrNull()

    private fun Edge.isStartFrom(value: V): Boolean = startFrom == value || (!isOriented && endWith == value)
    private fun Edge.isEndWith(value: V): Boolean = endWith == value || (!isOriented && startFrom == value)
    private fun Edge.incomingNodes(): Set = if (isOriented) setOf(endWith) else setOf(startFrom, endWith)
    private fun Edge.outgoingNodes(): Set = if (isOriented) setOf(startFrom) else setOf(startFrom, endWith)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy