我正在尝试通过随机连接N个节点来生成一个简单的图形。我正在寻找有效的算法,如下所示:
N
个节点数E
从N-1
到N(N-1)/2
答案 0 :(得分:2)
创建N
个节点的数组。 Fisher-Yates shuffle数组。扫描阵列并为阵列中相邻的每对节点创建边缘。结果是带有N-1
边的连通图。
如果附加边的数量很少,那么你可以随意添加边,直到你有足够的边。否则,创建一个未使用边的数组,Fisher-Yates对数组进行洗牌,并从数组中取出第一个(E - (N-1))
边。
答案 1 :(得分:-1)
这是一个非常简单的算法,可以随机连接每个节点和随机数量的其他节点。
//
// NSCoder.swift
// NoodleKit
//
// Created by Thom Morgan on 8/15/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
// MARK: - ** Import Modules **
import Foundation
// MARK: - ** NSCoder - _ObjectiveCBridgeable Encoding Compatibility **
extension NSCoder {
/// Encodes an `_ObjectiveCBridgeable` data structure.
/// - important: The objective-c class being bridged to must conform to
/// `NSCoding`.
/// - parameter object: The object to encode.
public func encodeObject<T: _ObjectiveCBridgeable>(object: T?) {
encodeObject(object?._bridgeToObjectiveC())
}
/// Encodes an `_ObjectiveCBridgeable` data structure as a root object.
/// - important: The objective-c class being bridged to must conform to
/// `NSCoding`.
/// - parameter object: The object to encode.
public func encodeRootObject<T: _ObjectiveCBridgeable>(object: T) {
encodeRootObject(object._bridgeToObjectiveC())
}
/// Encodes an `_ObjectiveCBridgeable` conditional data structure.
/// - important: The objective-c class being bridged to must conform to
/// `NSCoding`.
/// - parameter object: The object to encode.
public func encodeConditionalObject<T: _ObjectiveCBridgeable>(object: T?) {
encodeConditionalObject(object?._bridgeToObjectiveC())
}
/// Encodes an `_ObjectiveCBridgeable` data structure and maps it to a
/// specific `key`.
/// - important: The objective-c class being bridged to must conform to
/// `NSCoding`.
/// - parameter object: The object to encode.
/// - parameter key: The key to associate with this object.
public func encodeObject<T: _ObjectiveCBridgeable>(object: T?, forKey key: String) {
encodeObject(object?._bridgeToObjectiveC(), forKey: key)
}
/// Encodes an `_ObjectiveCBridgeable` conditional data structure and maps
/// it to a specific `key`.
/// - important: The objective-c class being bridged to must conform to
/// `NSCoding`.
/// - parameter object: The object to encode.
/// - parameter key: The key to associate with this object.
public func encodeConditionalObject<T: _ObjectiveCBridgeable>(object: T?, forKey key: String) {
encodeConditionalObject(object?._bridgeToObjectiveC(), forKey: key)
}
}