查找使用简单几何级数创建的树的祖先节点(Finding the ancestral nodes of a tree created with a simple geometric progression)
我正在寻找一种算法,它可以为任何树中的任何节点提供祖先线,这些节点是使用几何系列创建的,其中
a = 1
,r
等于任何整数。 例如,下图中的树,r = 2
,而26
的祖先线是[26, 13, 6, 3, 1]
。我自己也有过这个问题,并且得出了一个答案,似乎给了我正确的答案,我已经尝试过
r
的值。 但在我创建一个使用此算法提供文件系统资源的应用程序之前,我想确保我不会错过某些边缘案例。 感觉就像那种问题必须有一个既定的解决方案,几乎肯定比我的更优雅。 有谁知道什么?# My python implementation. import math def findLevelOfFolder(folder): """ Find the 'level' on which a given folder sits. """ if folder == 1: return 1 else: level = 2 while True: lower, upper= boundsOfLevel(level) if folder >= lower and folder <= upper: return level level += 1 def sumOfProgression(r, upToAndIncludingTerm): """ Sums a simple geometric series. If r = 2, and upToAndIncludingTerm = 6, we'refinding the value of... pow(2, 0) + pow(2, 1) + pow(2, 3) + ... + pow(2, 5) """ rRepeated = [r] * upToAndIncludingTerm powers = range(0, upToAndIncludingTerm) return sum(map(pow, rRepeated, powers)) def boundsOfLevel(level): """ A levels 'bounds' refers to the number of the first folder and the last folder on that level. For example, when r == 2, and the level == 3, the bounds is (4, 7). The smallest possible level is 1, which, for any value of r always returns (1, 1). """ assert(level > 0, "Smallest possible level is 1.") if level == 1: return 1, 1 else: lower = sumOfProgression(foldersPerFolder, level-1) + 1 upper = lower + pow(foldersPerFolder, level-1) - 1 return lower, upper def ancestorsOfFolder(folder, ancestors): """ Find the shortest route from folder '1' for the specified folder value. On completion, ancestors will contain a list of numbers each of which represents a folder in the ancestral line of 'folder'. The first number in the list will always be 'folder' and the last number will always be 1.""" # First get the level... level = findLevelOfFolder(folder) lowerBoundOfPreviousLevel, _ = boundsOfLevel(level-1) relativePosition = folder - sumOfProgression(foldersPerFolder, level-1) parent = (lowerBoundOfPreviousLevel - 1) + math.ceil(relativePosition/foldersPerFolder) ancestors.append(parent) if parent != 1: ancestorsOfFolder(parent, ancestors) # 'r' value foldersPerFolder = 2 # looking for ancestral line of... folder = 23 print(ancestorsOfFolder(folder, [folder])) # -> [23, 11, 5, 2, 1]
I'm looking for an algorithm that will give me the ancestral line for any node in any tree that has been created using a geometric series where
a = 1
, andr
equals any whole number. For example the tree in the image below,r = 2
, and the ancestral line for26
is[26, 13, 6, 3, 1]
.I've had a go at this myself and have come up with an answer that appears to give me the correct answer for the values of
r
that I've tried. But before I create an app that uses this algorithm to provide file-system resources I want to be sure that I'm not missing some edge-case somewhere. It feels like the kind of problem that must have an established solution that is almost certainly more elegant that mine. Does anyone know of anything?# My python implementation. import math def findLevelOfFolder(folder): """ Find the 'level' on which a given folder sits. """ if folder == 1: return 1 else: level = 2 while True: lower, upper= boundsOfLevel(level) if folder >= lower and folder <= upper: return level level += 1 def sumOfProgression(r, upToAndIncludingTerm): """ Sums a simple geometric series. If r = 2, and upToAndIncludingTerm = 6, we'refinding the value of... pow(2, 0) + pow(2, 1) + pow(2, 3) + ... + pow(2, 5) """ rRepeated = [r] * upToAndIncludingTerm powers = range(0, upToAndIncludingTerm) return sum(map(pow, rRepeated, powers)) def boundsOfLevel(level): """ A levels 'bounds' refers to the number of the first folder and the last folder on that level. For example, when r == 2, and the level == 3, the bounds is (4, 7). The smallest possible level is 1, which, for any value of r always returns (1, 1). """ assert(level > 0, "Smallest possible level is 1.") if level == 1: return 1, 1 else: lower = sumOfProgression(foldersPerFolder, level-1) + 1 upper = lower + pow(foldersPerFolder, level-1) - 1 return lower, upper def ancestorsOfFolder(folder, ancestors): """ Find the shortest route from folder '1' for the specified folder value. On completion, ancestors will contain a list of numbers each of which represents a folder in the ancestral line of 'folder'. The first number in the list will always be 'folder' and the last number will always be 1.""" # First get the level... level = findLevelOfFolder(folder) lowerBoundOfPreviousLevel, _ = boundsOfLevel(level-1) relativePosition = folder - sumOfProgression(foldersPerFolder, level-1) parent = (lowerBoundOfPreviousLevel - 1) + math.ceil(relativePosition/foldersPerFolder) ancestors.append(parent) if parent != 1: ancestorsOfFolder(parent, ancestors) # 'r' value foldersPerFolder = 2 # looking for ancestral line of... folder = 23 print(ancestorsOfFolder(folder, [folder])) # -> [23, 11, 5, 2, 1]
原文:https://stackoverflow.com/questions/30514352
最满意答案
请检查以下内容。
if activity.activity_type?.id == LHActivityTypeID.Bike.rawValue { self?.allItems.append(activity) }
Please check the below.
if activity.activity_type?.id == LHActivityTypeID.Bike.rawValue { self?.allItems.append(activity) }
相关问答
更多-
Swift 2.0:表达式是不明确的,没有更多的上下文?(Swift 2.0: Type of Expression is ambiguous without more context?)[2022-12-01]
你可以给编译器更多的信息: let recordSettings : [String : Any] = [ AVFormatIDKey: kAudioFormatMPEG4AAC, AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue, AVEncoderBitRateKey : 320000, AVNumberOfChannelsKey: 2, AVSampleRateKey : 44100.0 ] To c ... -
我终于修复了问题,并且不确定它与错误消息本身有什么关系。 1)healthKitTypesToRead和write:从Set([])中删除[] 2)创建了一个新的完成重复 3)按照以下方式更改呼叫 例: let healthKitTypesToRead = Set( arrayLiteral: HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!, HK ...
-
修复了这个问题。 我必须将eventMonitor = EventMonitor(mask: .LeftMouseDownMask | .RightMouseDownMask) { [unowned self] event in eventMonitor = EventMonitor(mask: [.LeftMouseDownMask, .RightMouseDownMask]) { [unowned self] event in eventMonitor = EventMonitor(mask: .Lef ...
-
尝试这个: let attributes = [ NSFontAttributeName: UIFont(name: "Georgia", size: 15.0)!, NSForegroundColorAttributeName: UIColor.orangeColor(), NSStrikethroughStyleAttributeName: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue) ] let myTitl ...
-
表达式.now()返回一个结构体类型DispatchTime 。 let offsetTime = 0将变量初始化为Int 。 错误是误导,实际上它是一种类型不匹配 虽然编译器可以推断数字文字的类型 DispatchQueue.main.asyncAfter(deadline: .now() + 3) 将Int文字或变量添加到DispatchTime值的最可靠方法是具有关联值的DispatchTimeInterval情况。 DispatchQueue.main.asyncAfter(deadline: . ...
-
我有multipartFormData的错误参数。 这是有效的: multipartFormData: { multipartFormData in multipartFormData.append(imageData!, withName: "photo", fileName: "image.jpg", mimeType: "image/jpg") }, I had the wrong arguments for multipart ...
-
尝试这个: let seenIDS = objects?.map { ($0 as? NSDictionary)?.objectForKey("toUser") as! String } ?? [] Try this: let seenIDS = objects?.map { ($0 as? NSDictionary)?.objectForKey("toUser") as! String } ?? []
-
如何解决Xcode中的“表达式类型不明确,没有更多上下文”(How to fix “Type of expression is ambiguous without more context” in Xcode)[2023-05-08]
尝试这个: class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData: NSData? // Error occurs on the following line: do { sceneData ... -
我也是healthKit的新手,但尝试在typesToShare参数的nil处使用dataTypesToShare变量。更好的是使用与dataTypesToRead相同的方式创建dataTypesToShare。 并且此函数不返回任何内容。您可以尝试使用闭包来获得完成块成功。 func authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!) { healthStore?.requestAuthori ...
-
请检查以下内容。 if activity.activity_type?.id == LHActivityTypeID.Bike.rawValue { self?.allItems.append(activity) } Please check the below. if activity.activity_type?.id == LHActivityTypeID.Bike.rawValue { self?.allItems.append(activity) }