Compare commits

...

8 Commits

Author SHA1 Message Date
hectr 824a7d8c9b Release 0.4.0 2019-08-11 19:39:23 +02:00
hectr e9ddc48972 Move Vector and Matrix2D to Idioms package 2019-08-11 19:39:02 +02:00
hectr e7ea5a92a8 Rename Matrix to Matrix2D 2019-07-15 00:29:26 +02:00
hectr 7a87ec23a7 Release 0.3.0 2019-07-14 23:35:50 +02:00
hectr 5369124c60 Update package to swift-tools 5.0 2019-07-14 23:35:02 +02:00
hectr b55c0d8e96 Release 0.2.0 2018-12-10 23:00:20 +01:00
hectr c4f0749f1c Use Array shorthand syntactic sugar 2018-12-10 22:56:02 +01:00
hectr 347691d331 Use Array instead of Vector where possible 2018-12-10 00:41:22 +01:00
24 changed files with 137 additions and 369 deletions

View File

@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'ElementaryCycles'
s.version = '0.1.0'
s.version = '0.4.0'
s.summary = 'Find all elementary cycles in a directed graph'
s.description = <<-DESC
Swift port of an algorythm by Donald B. Johnson to find all the cycles in a directed graph.
@ -14,5 +14,5 @@ Swift port of an algorythm by Donald B. Johnson to find all the cycles in a dire
s.source = { :git => 'https://github.com/hectr/swift-elementary-cycles.git', :tag => s.version.to_s }
s.source_files = 'Sources/ElementaryCycles/**/*'
s.dependency 'ElementaryCyclesSearch'
s.swift_version = '4.2'
s.swift_version = '5.0'
end

View File

@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'ElementaryCyclesSearch'
s.version = '0.1.0'
s.version = '0.4.0'
s.summary = 'Elementary Circuits of a Directed Graph'
s.description = <<-DESC
The implementation is pretty much generic, all it needs is a adjacency-matrix of your graph and the objects of your nodes. Then you get back the sets of node-objects which build a cycle.
@ -13,5 +13,6 @@ The implementation is pretty much generic, all it needs is a adjacency-matrix of
s.osx.deployment_target = '10.13'
s.source = { :git => 'https://github.com/hectr/swift-elementary-cycles.git', :tag => s.version.to_s }
s.source_files = 'Sources/ElementaryCyclesSearch/**/*'
s.swift_version = '4.2'
s.dependency 'Idioms'
s.swift_version = '5.0'
end

16
Package.resolved Normal file
View File

@ -0,0 +1,16 @@
{
"object": {
"pins": [
{
"package": "Idioms",
"repositoryURL": "https://github.com/hectr/swift-idioms.git",
"state": {
"branch": null,
"revision": "320c051b0f4775d2ccca6120ab673416300679f9",
"version": "1.4.0"
}
}
]
},
"version": 1
}

View File

@ -1,4 +1,4 @@
// swift-tools-version:4.2
// swift-tools-version:5.0
import PackageDescription
@ -16,6 +16,7 @@ let package = Package(
targets: ["ElementaryCyclesSearchExample"]),
],
dependencies: [
.package(url: "https://github.com/hectr/swift-idioms.git", from: "1.4.0"),
],
targets: [
.target(
@ -23,7 +24,7 @@ let package = Package(
dependencies: ["ElementaryCyclesSearch"]),
.target(
name: "ElementaryCyclesSearch",
dependencies: []),
dependencies: ["Idioms"]),
.target(
name: "ElementaryCycles",
dependencies: ["ElementaryCyclesSearch"]),

View File

@ -12,9 +12,10 @@
*/
import Swift
import Idioms
import ElementaryCyclesSearch
extension Matrix where Element == Bool {
extension Matrix2D where Element == Bool {
enum Error: Swift.Error {
case indexNotFound(node: AnyHashable, nodes: [AnyHashable])
}
@ -24,7 +25,7 @@ extension Matrix where Element == Bool {
for (offset, node) in nodes.enumerated() {
if let adjacentNodes = adjacencyDictionary[node] {
for adjacentNode in adjacentNodes {
guard let adjacentIndex = nodes.index(of: adjacentNode) else {
guard let adjacentIndex = nodes.firstIndex(of: adjacentNode) else {
throw Error.indexNotFound(node: adjacentNode, nodes: nodes)
}
matrix[offset][adjacentIndex] = true

View File

@ -12,9 +12,10 @@
*/
import Swift
import Idioms
import ElementaryCyclesSearch
extension Matrix where Element == Bool {
extension Matrix2D where Element == Bool {
static func getNodes<Node: Hashable>(graph: [Node: [Node]], sort: ((Node, Node) -> Bool)?) -> [Node] {
var nodes = [Node]()
for (node, adjacentNodes) in graph {

View File

@ -15,7 +15,7 @@ import Swift
import ElementaryCyclesSearch
extension ElementaryCyclesSearch {
static func toArray(elementaryCycles: Vector<Vector<Node>>) -> [[Node]] {
static func toArray(elementaryCycles: [[Node]]) -> [[Node]] {
var cycles = [[Node]]()
for vector in elementaryCycles {
var cycle = [Node]()

View File

@ -12,13 +12,14 @@
*/
import Swift
import Idioms
import ElementaryCyclesSearch
public struct ElementaryCycles {
public static func find<Node: Hashable>(graph: [Node: [Node]], sort: ((Node, Node) -> Bool)? = nil) -> [[Node]] {
let nodes = AdjacencyMatrix.getNodes(graph: graph, sort: sort)
let adjacencyMatrix = try! AdjacencyMatrix.getAdjacencyMatrix(nodes: nodes, adjacencyDictionary: graph)
let elementaryCycles = ElementaryCyclesSearch.getElementaryCycles(adjacencyMatrix: adjacencyMatrix, graphNodes: Vector(array: nodes))
let elementaryCycles = ElementaryCyclesSearch.getElementaryCycles(adjacencyMatrix: adjacencyMatrix, graphNodes: nodes)
return ElementaryCyclesSearch.toArray(elementaryCycles: elementaryCycles)
}
}

View File

@ -15,6 +15,7 @@
*/
import Swift
import Idioms
/**
* Calculates the adjacency-list for a given adjacency-matrix.
@ -24,7 +25,7 @@ import Swift
* @version 1.0, 26.08.2006
*
*/
extension Matrix where Element == Int {
extension Matrix2D where Element == Int {
/**
* Calculates a adjacency-list for a given array of an adjacency-matrix.
*
@ -35,20 +36,20 @@ extension Matrix where Element == Int {
* adjacency, the second dimension represents the indicies of those nodes,
* that are direct successornodes of the node.
*/
static func getAdjacencyList(adjacencyMatrix: AdjacencyMatrix) -> Matrix<Int> {
let list = Matrix<Int>(adjacencyMatrix.reservedLength)
static func getAdjacencyList(adjacencyMatrix: AdjacencyMatrix) -> Matrix2D<Int> {
let list = Matrix2D<Int>(adjacencyMatrix.reservedLength)
for i in 0 ..< adjacencyMatrix.reservedLength {
let v = Vector<Int>()
var v = [Int]()
for j in 0 ..< adjacencyMatrix[i].reservedLength {
if let isAdjacent = adjacencyMatrix[i]?[j], isAdjacent {
v.add(j)
v.append(j)
}
}
list[i] = Vector(v.size)
for j in 0 ..< v.size {
let integer = v.get(j)
list[i] = Vector(v.count)
for j in 0 ..< v.count {
let integer = v[j]
list[i][j] = integer
}
}

View File

@ -15,5 +15,6 @@
*/
import Swift
import Idioms
typealias AdjacencyList = Matrix<Int>
typealias AdjacencyList = Matrix2D<Int>

View File

@ -15,6 +15,7 @@
*/
import Swift
import Idioms
/**
* This is a helpclass for the search of all elementary cycles in a graph
@ -77,7 +78,7 @@ class StrongConnectedComponents {
private var visited: Vector<Bool>!
/** Helpattribute for finding scc's */
private var stack: Vector<Int>!
private var stack: [Int]!
/** Helpattribute for finding scc's */
private var lowlink: Vector<Int>!
@ -89,7 +90,7 @@ class StrongConnectedComponents {
private var strongConnectedComponentsCounter = 0;
/** Helpattribute for finding scc's */
private var currentStrongConnectedComponents: Vector<Vector<Int>>!
private var currentStrongConnectedComponents: [[Int]]!
/**
* Constructor.
@ -116,9 +117,9 @@ class StrongConnectedComponents {
lowlink = Vector<Int>(self.adjacencyListOriginal.reservedLength)
number = Vector<Int>(self.adjacencyListOriginal.reservedLength)
visited = Vector<Bool>(self.adjacencyListOriginal.reservedLength)
stack = Vector<Int>()
currentStrongConnectedComponents = Vector<Vector<Int>>()
stack = [Int]()
currentStrongConnectedComponents = [[Int]]()
makeAdjacencyListSubgraph(node: node);
for i in node ..< self.adjacencyListOriginal.reservedLength {
@ -153,17 +154,17 @@ class StrongConnectedComponents {
adjacencyList = AdjacencyList(adjacencyListOriginal.reservedLength, 0)
for i in node ..< adjacencyList.reservedLength {
let successors = Vector<Int>()
var successors = [Int]()
for j in 0 ..< self.adjacencyListOriginal[i].reservedLength {
guard let original = adjacencyListOriginal[i]?[j] else { continue }
if original >= node {
successors.add(original)
successors.append(original)
}
}
if successors.size > 0 {
adjacencyList[i] = Vector(successors.size)
for j in 0 ..< successors.size {
let succ = successors.get(j)
if successors.count > 0 {
adjacencyList[i] = Vector(successors.count)
for j in 0 ..< successors.count {
let succ = successors[j]
adjacencyList[i][j] = succ
}
}
@ -176,14 +177,14 @@ class StrongConnectedComponents {
*
* @return Vector::Integer of the strongConnectedComponents containing the lowest nodenumber
*/
private func getLowestIdComponent() -> Vector<Int>? {
private func getLowestIdComponent() -> [Int]? {
var min = adjacencyList.reservedLength;
var currScc: Vector<Int>?
var currScc: [Int]?
for i in 0 ..< currentStrongConnectedComponents.size {
let strongConnectedComponents = currentStrongConnectedComponents.get(i)
for j in 0 ..< strongConnectedComponents.size {
let node = strongConnectedComponents.get(j)
for i in 0 ..< currentStrongConnectedComponents.count {
let strongConnectedComponents = currentStrongConnectedComponents[i]
for j in 0 ..< strongConnectedComponents.count {
let node = strongConnectedComponents[j]
if node < min {
currScc = strongConnectedComponents
min = node
@ -199,14 +200,14 @@ class StrongConnectedComponents {
* strong connected component with least vertex in the currently viewed
* subgraph
*/
private func getAdjList(nodes: Vector<Int>?) -> AdjacencyList? {
private func getAdjList(nodes: [Int]?) -> AdjacencyList? {
guard let nodes = nodes else { return nil }
let lowestIdAdjacencyList = AdjacencyList(adjacencyList.reservedLength)
for i in 0 ..< lowestIdAdjacencyList.reservedLength {
lowestIdAdjacencyList[i] = Vector<Int>()
}
for i in 0 ..< nodes.size {
let node = nodes.get(i)
for i in 0 ..< nodes.count {
let node = nodes[i]
guard let adjListNode = adjacencyList[node] else { continue }
for j in 0 ..< adjListNode.reservedLength {
guard let succ = adjacencyList[node]?[j] else { continue }
@ -228,8 +229,8 @@ class StrongConnectedComponents {
strongConnectedComponentsCounter += 1
lowlink[root] = strongConnectedComponentsCounter
number[root] = strongConnectedComponentsCounter
visited[root] = true;
stack.add(root);
visited[root] = true
stack.append(root)
for i in 0 ..< adjacencyList[root].reservedLength {
guard let w = adjacencyList[root]?[i] else { continue }
@ -244,19 +245,19 @@ class StrongConnectedComponents {
}
// found strongConnectedComponents
if (lowlink[root] == number[root]) && (stack.size > 0) {
if (lowlink[root] == number[root]) && (stack.count > 0) {
var next = -1;
let strongConnectedComponents = Vector<Int>()
var strongConnectedComponents = [Int]()
repeat {
next = stack.get(stack.size - 1)
stack.remove(at: stack.size - 1)
strongConnectedComponents.add(next)
guard let popped = stack.popLast() else { break }
next = popped
strongConnectedComponents.append(next)
} while number[next]! > number[root]!
// simple scc's with just one node will not be added
if strongConnectedComponents.size > 1 {
currentStrongConnectedComponents.add(strongConnectedComponents);
if strongConnectedComponents.count > 1 {
currentStrongConnectedComponents.append(strongConnectedComponents);
}
}
}

View File

@ -15,10 +15,11 @@
*/
import Swift
import Idioms
public typealias AdjacencyMatrix = Matrix<Bool>
public typealias AdjacencyMatrix = Matrix2D<Bool>
extension Matrix where Element == Bool {
extension Matrix2D where Element == Bool {
public convenience init(_ reservedRows: Int, _ reservedColumns: Int = 0, builder: (AdjacencyMatrix) -> Void) {
self.init(reservedRows, reservedColumns)
builder(self)

View File

@ -15,6 +15,7 @@
*/
import Swift
import Idioms
/**
* Searchs all elementary cycles in a given directed graph. The implementation
@ -42,22 +43,22 @@ import Swift
*/
public class ElementaryCyclesSearch<Node> {
/** List of cycles */
private var cycles: Vector<Vector<Node>>
private var cycles: [[Node]]
/** Adjacency-list of graph */
private var adjacencyList: AdjacencyList
/** Graphnodes */
private var graphNodes: Vector<Node>
private var graphNodes: [Node]
/** Blocked nodes, used by the algorithm of Johnson */
private var blocked: Vector<Bool>
/** B-Lists, used by the algorithm of Johnson */
private var B: Matrix<Int>
private var B: Matrix2D<Int>
/** Stack for nodes, used by the algorithm of Johnson */
private var stack: Vector<Int>
private var stack: [Int]
/**
* Returns List::List::Object with the Lists of nodes of all elementary
@ -70,7 +71,7 @@ public class ElementaryCyclesSearch<Node> {
*
* @return List::List::Object with the Lists of the elementary cycles.
*/
public static func getElementaryCycles(adjacencyMatrix: AdjacencyMatrix, graphNodes: Vector<Node>) -> Vector<Vector<Node>> {
public static func getElementaryCycles(adjacencyMatrix: AdjacencyMatrix, graphNodes: [Node]) -> [[Node]] {
let ecs = ElementaryCyclesSearch(adjacencyMatrix: adjacencyMatrix, graphNodes: graphNodes)
return ecs.getElementaryCycles()
}
@ -83,13 +84,13 @@ public class ElementaryCyclesSearch<Node> {
* build sets of the elementary cycles containing the objects of the original
* graph-representation
*/
private init(adjacencyMatrix: AdjacencyMatrix, graphNodes: Vector<Node>) {
private init(adjacencyMatrix: AdjacencyMatrix, graphNodes: [Node]) {
self.graphNodes = graphNodes;
self.adjacencyList = AdjacencyList.getAdjacencyList(adjacencyMatrix: adjacencyMatrix)
cycles = Vector<Vector<Node>>()
cycles = [[Node]]()
blocked = Vector<Bool>(adjacencyList.reservedLength)
B = Matrix<Int>(adjacencyList.reservedLength)
stack = Vector<Int>()
B = Matrix2D<Int>(adjacencyList.reservedLength)
stack = [Int]()
}
/**
@ -98,7 +99,7 @@ public class ElementaryCyclesSearch<Node> {
*
* @return List::List::Object with the Lists of the elementary cycles.
*/
private func getElementaryCycles() -> Vector<Vector<Node>> {
private func getElementaryCycles() -> [[Node]] {
let sccs = StrongConnectedComponents(adjacencyList: adjacencyList)
var s = 0
@ -135,20 +136,20 @@ public class ElementaryCyclesSearch<Node> {
*/
private func findCycles(v: Int, s: Int, adjacencyList: AdjacencyList) -> Bool {
var f = false
stack.add(v)
stack.append(v)
blocked[v] = true
for i in 0 ..< adjacencyList[v].size {
let w = adjacencyList[v].get(i)
// found cycle
if w == s {
let cycle = Vector<Node>()
for j in 0 ..< stack.size {
let index = stack.get(j)
guard let node = graphNodes[index] else { continue }
cycle.add(node)
var cycle = [Node]()
for j in 0 ..< stack.count {
let index = stack[j]
let node = graphNodes[index] // WARNING guard
cycle.append(node)
}
cycles.add(cycle)
cycles.append(cycle)
f = true
} else if !(blocked[w] ?? false) {
if findCycles(v: w, s: s, adjacencyList: adjacencyList) {
@ -167,8 +168,10 @@ public class ElementaryCyclesSearch<Node> {
}
}
}
stack.remove(element: v)
if let index = stack.firstIndex(of: v) {
stack.remove(at: index)
}
return f
}

View File

@ -1,41 +0,0 @@
/*
(BSD-2 license)
Copyright (c) 2018, Hèctor Marquès
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Swift
public struct MatrixIterator<Element>: IteratorProtocol {
private let matrix: Matrix<Element>
private var currentIndex = -1
private var currentIterator: VectorIterator<Element>?
fileprivate init(matrix: Matrix<Element>) {
self.matrix = matrix
}
mutating public func next() -> Element? {
if let element = currentIterator?.next() {
return element
}
currentIndex += 1
guard matrix.reservedLength > currentIndex else { return nil }
let vector = matrix[currentIndex]
currentIterator = vector?.makeIterator()
return next()
}
}
extension Matrix: Sequence {
public func makeIterator() -> MatrixIterator<Element> {
return MatrixIterator(matrix: self)
}
}

View File

@ -1,71 +0,0 @@
/*
(BSD-2 license)
Copyright (c) 2018, Hèctor Marquès
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Swift
public final class Matrix<Element> {
private var vector: Vector<Vector<Element>>
public subscript(_ row: Int) -> Vector<Element>! {
get {
return vector[row]
}
set(newValue) {
vector[row] = newValue
}
}
public init(_ reservedRows: Int, _ reservedColumns: Int = 0) {
self.vector = Vector<Vector<Element>>(reservedRows)
for i in 0 ..< reservedLength {
vector[i] = Vector<Element>(reservedColumns)
}
}
public convenience init(rows: [[Element]]) {
var reservedColumns = 0
for row in rows {
reservedColumns = Swift.max(reservedColumns, row.count)
}
self.init(rows.count, reservedColumns)
for (offset, row) in rows.enumerated() {
self[offset] = Vector(array: row, reservedLength: reservedColumns)
}
}
public var reservedLength: Int {
return vector.reservedLength
}
}
extension Matrix: CustomDebugStringConvertible {
public var debugDescription: String {
return vector.debugDescription
}
}
extension Matrix: CustomStringConvertible {
public var description: String {
return vector.description
}
}
extension Matrix: Equatable where Element: Equatable {
public static func == (lhs: Matrix<Element>, rhs: Matrix<Element>) -> Bool {
guard lhs.reservedLength == rhs.reservedLength else { return false }
for index in 0 ..< lhs.reservedLength {
guard lhs[index] == rhs[index] else { return false }
}
return true
}
}

View File

@ -1,36 +0,0 @@
/*
(BSD-2 license)
Copyright (c) 2018, Hèctor Marquès
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Swift
public struct VectorIterator<Element>: IteratorProtocol {
private let vector: Vector<Element>
private var currentIndex = -1
fileprivate init(vector: Vector<Element>) {
self.vector = vector
}
mutating public func next() -> Element? {
currentIndex += 1
guard vector.size > currentIndex else { return nil }
guard let element = vector[currentIndex] else { return next() }
return element
}
}
extension Vector: Sequence {
public func makeIterator() -> VectorIterator<Element> {
return VectorIterator(vector: self)
}
}

View File

@ -1,115 +0,0 @@
/*
(BSD-2 license)
Copyright (c) 2018, Hèctor Marquès
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Swift
public final class Vector<Element> {
private var array: [Element?] {
didSet {
reservedLength = Swift.max(reservedLength, array.count)
}
}
public private(set) var reservedLength: Int {
didSet {
assert(reservedLength >= size)
}
}
public subscript(_ index: Int) -> Element? {
get {
guard array.count > index || index >= reservedLength else { return nil }
return array[index]
}
set(newValue) {
while index >= array.count && index < reservedLength {
array.append(nil)
}
array[index] = newValue
}
}
public init(array: [Element], reservedLength: Int? = nil) {
self.array = array
self.reservedLength = Swift.max(reservedLength ?? 0, array.count)
}
public init(_ reservedLength: Int = 0) {
self.array = [Element?]()
self.reservedLength = reservedLength
}
public var size: Int {
return array.count
}
public func get(_ index: Int) -> Element {
guard let element = self[index] else { fatalError("\(#function): index (\(index)) out of bounds (\(reservedLength))") }
return element
}
public func add(_ newElement: Element) {
array.append(newElement)
}
@discardableResult
public func remove(at index: Int) -> Element? {
var removedObject: Element?
if index < array.count {
removedObject = array[index]
array.remove(at: index)
} else if index >= reservedLength {
preconditionFailure("Index out of range: \(index) is beyond count (\(array.count) and reservedLength \(reservedLength)")
}
reservedLength -= 1
return removedObject
}
}
extension Vector where Element: Equatable {
func contains(_ element: Element) -> Bool{
return array.contains(element)
}
@discardableResult
func remove(element: Element) -> Bool {
if let index = array.index(of: element) {
array.remove(at: -index.distance(to: 0))
return true
}
return false
}
}
extension Vector: CustomDebugStringConvertible {
public var debugDescription: String {
return array.debugDescription
}
}
extension Vector: CustomStringConvertible {
public var description: String {
return array.description
}
}
extension Vector: Equatable where Element: Equatable {
public static func == (lhs: Vector<Element>, rhs: Vector<Element>) -> Bool {
guard lhs.reservedLength == rhs.reservedLength else { return false }
guard lhs.size == rhs.size else { return false }
for index in 0 ..< lhs.size {
guard lhs[index] == rhs[index] else { return false }
}
return true
}
}

View File

@ -26,12 +26,12 @@ import ElementaryCyclesSearch
typealias Node = String
private func printCycles(_ cycles: Vector<Vector<Node>>) {
for i in 0 ..< cycles.size {
let cycle = cycles.get(i)
for j in 0 ..< cycle.size {
let node = cycle.get(j)
if j < (cycle.size - 1) {
private func printCycles(_ cycles: [[Node]]) {
for i in 0 ..< cycles.count {
let cycle = cycles[i]
for j in 0 ..< cycle.count {
let node = cycle[j]
if j < (cycle.count - 1) {
print(node + " -> ", terminator: "")
} else {
print(node, terminator: "")
@ -41,10 +41,10 @@ private func printCycles(_ cycles: Vector<Vector<Node>>) {
}
}
let nodes: Vector<Node> = {
let vector = Vector<Node>(10)
let nodes: [Node] = {
var vector = [Node]()
for i in 0 ..< 10 {
vector[i] = "Node \(i)"
vector.append("Node \(i)")
}
return vector
}()

View File

@ -1,4 +1,5 @@
import XCTest
import Idioms
@testable import ElementaryCyclesSearch
final class AdjacencyListTests: XCTestCase {
@ -16,7 +17,7 @@ final class AdjacencyListTests: XCTestCase {
}
}
var sut: ((AdjacencyMatrix) -> Matrix<Int>)!
var sut: ((AdjacencyMatrix) -> Matrix2D<Int>)!
override func setUp() {
super.setUp()

View File

@ -1,4 +1,5 @@
import XCTest
import Idioms
@testable import ElementaryCyclesSearch
final class AdjacencyMatrixTests: XCTestCase {
@ -22,9 +23,9 @@ final class AdjacencyMatrixTests: XCTestCase {
func testConvenienceInit() {
let rows = [["a"],[],["b", "c"]]
let matrix = Matrix<String>(rows: rows)
let expectedMatrix: Matrix<String> = {
let matrix = Matrix<String>(3, 2)
let matrix = Matrix2D<String>(rows: rows)
let expectedMatrix: Matrix2D<String> = {
let matrix = Matrix2D<String>(3, 2)
matrix[0][0] = "a"
matrix[2][0] = "b"
matrix[2][1] = "c"
@ -34,7 +35,7 @@ final class AdjacencyMatrixTests: XCTestCase {
}
func testSequence() {
let matrix = Matrix<Int>(4, 4)
let matrix = Matrix2D<Int>(4, 4)
matrix[0][1] = 1
matrix[1][2] = 2
matrix[3][0] = 3

View File

@ -6,10 +6,10 @@ final class ElementaryCyclesSearchTests: XCTestCase {
private typealias Node = String
private var nodes: Vector<Node> {
let nodes = Vector<Node>(10)
private var nodes: [Node] {
var nodes = [Node]()
for i in 0 ..< 10 {
nodes[i] = "Node \(i)"
nodes.append("Node \(i)")
}
return nodes
}
@ -29,15 +29,15 @@ final class ElementaryCyclesSearchTests: XCTestCase {
matrix[6][1] = true
}
private var sut: ((AdjacencyMatrix, Vector<Node>) -> Vector<Vector<Node>>)!
private var sut: ((AdjacencyMatrix, [Node]) -> [[Node]])!
private func prettify(cycles: Vector<Vector<Node>>) -> String {
private func prettify(cycles: [[Node]]) -> String {
var description = ""
for i in 0 ..< cycles.size {
let cycle = cycles.get(i)
for j in 0 ..< cycle.size {
let node = cycle.get(j)
if j < (cycle.size - 1) {
for i in 0 ..< cycles.count {
let cycle = cycles[i]
for j in 0 ..< cycle.count {
let node = cycle[j]
if j < (cycle.count - 1) {
description.append(node + " -> ")
} else {
description.append(node)

View File

@ -1,4 +1,5 @@
import XCTest
import Idioms
@testable import ElementaryCyclesSearch
final class StrongConnectedComponentsTests: XCTestCase {
@ -7,7 +8,7 @@ final class StrongConnectedComponentsTests: XCTestCase {
func test1() {
let adjMatrix = Matrix(10, 10) { matrix in
let adjMatrix = Matrix2D(10, 10) { matrix in
matrix[0][1] = true
matrix[1][2] = true
matrix[2][0] = true; matrix[2][6] = true
@ -20,7 +21,7 @@ final class StrongConnectedComponentsTests: XCTestCase {
matrix[6][1] = true
}
let adjacencyList: Matrix<Int> = AdjacencyList.getAdjacencyList(adjacencyMatrix: adjMatrix)
let adjacencyList: Matrix2D<Int> = AdjacencyList.getAdjacencyList(adjacencyMatrix: adjMatrix)
let sccs = StrongConnectedComponents(adjacencyList: adjacencyList)
var description = ""
@ -91,7 +92,7 @@ i: 9
}
func test2() {
let adjMatrix: AdjacencyMatrix = Matrix(10, 10) { matrix in
let adjMatrix: AdjacencyMatrix = Matrix2D(10, 10) { matrix in
matrix[0][1] = true
matrix[1][2] = true
matrix[2][0] = true
@ -106,7 +107,7 @@ i: 9
matrix[9][6] = true
}
let adjacencyList: Matrix<Int> = AdjacencyList.getAdjacencyList(adjacencyMatrix: adjMatrix)
let adjacencyList: Matrix2D<Int> = AdjacencyList.getAdjacencyList(adjacencyMatrix: adjMatrix)
let sccs = StrongConnectedComponents(adjacencyList: adjacencyList)
var description = ""

View File

@ -31,10 +31,10 @@ final class AdjacencyMatrixShould: XCTestCase {
"IT": ["FR"]]
let nodes = AdjacencyMatrix.getNodes(graph: graph, sort: nil)
let adjacencyMatrix = try! AdjacencyMatrix.getAdjacencyMatrix(nodes: nodes, adjacencyDictionary: graph)
let es = nodes.index(of: "ES")!
let pt = nodes.index(of: "PT")!
let fr = nodes.index(of: "FR")!
let it = nodes.index(of: "IT")!
let es = nodes.firstIndex(of: "ES")!
let pt = nodes.firstIndex(of: "PT")!
let fr = nodes.firstIndex(of: "FR")!
let it = nodes.firstIndex(of: "IT")!
XCTAssertTrue(adjacencyMatrix[es][pt] ?? adjacencyMatrix[pt][es] ?? false)
XCTAssertTrue(adjacencyMatrix[es][fr] ?? adjacencyMatrix[fr][es] ?? false)
XCTAssertTrue(adjacencyMatrix[fr][it] ?? adjacencyMatrix[it][fr] ?? false)

View File

@ -7,10 +7,10 @@ final class ElementaryCyclesSearchShould: XCTestCase {
private typealias Node = String
private var nodes: Vector<Node> {
let nodes = Vector<Node>(10)
private var nodes: [Node] {
var nodes = [Node]()
for i in 0 ..< 10 {
nodes[i] = "Node \(i)"
nodes.append("Node \(i)")
}
return nodes
}