C#:两种不同数据结构中的递归搜索
我需要在 C# 中的两个不同数据结构中执行搜索,具体情况如下: 我有一个名字(这是一个字符串),我想执行一项搜索。我有一个名为 Exists
的函数,它将返回一个 bool
指示它是否存在。
如果存在,我会增加名称(只需在字符串末尾添加 1),然后我需要再次执行搜索(通过方法 exists
)以查看是否存在具有新名称已存在。
这将一直持续下去,直到出现一个未使用的名称(我可以使用该名称),但是,如果它不存在,现在我应该执行搜索另一个包含已删除对象的数据结构,如果在那里找到该字符串,那么我就必须再次增加名称,并从头开始搜索。 如果既没有使用 Exists 方法,也没有在所有已删除对象所在的数据结构中存在具有该名称的对象,这一切都会结束。
我该如何解决这个问题?
我希望我清楚地表达了自己的意思:-)
提前非常感谢!
I need to perform a search in two different data structures in C#, and here's the deal:
I have one name (which is a string) and I want to perform a search. I have a function called Exists
which will return a bool
indicating whether it exists or not.
In case it exists, I increase the name (simply adding a 1 at the end of the string), and then I need to perform the search again (via method exists
) to see if an object with the new name exists.
This would go on until there's an unused name, which I could use, BUT, in case it doesn't exist, now I should perform a search another data structure which contains the objects that were deleted, and if the string is found there, then I'd have to increase the name again, and start searching since the beginning.
This would all end in case there's no object with such name neither using Exists
method nor in the data structure where all the deleted objects are.
How could I approach this problem?
I hope I expressed myself clearly :-)
Thanks a lot in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者我错过了什么?
使用for循环:
顺便说一句,我猜你的名称增量算法比简单地添加1更复杂:名称,名称1,名称2,...基本上,如果名称不以数字结尾,则附加“1”。如果是,则增加该数字。正确的?
Or did I miss something?
Using a for loop:
BTW, I guess your name incrementation algorithm is more complex than simply adding 1: name, name1, name2,... Basically, if the name doesn't end in a number, you append "1". If it does, you increment that number. right?
非递归且简单的解决方案可能是这样的(在这种情况下我认为不需要递归)
a non recursive and simple solution could be something like this ( I don't see any need of recursion in this case)
为什么要使用循环? (我知道 LINQ 会在幕后)
Why use a loop at all?? (I know LINQ will under the hood)
这个怎么样:
How about this one:
如果您为这两种数据结构创建
Exists
方法,则可以使用递归进行搜索,如下所示:伪代码:
if you create
Exists
methods for both data structures, you can search with recursion like this:pseudo code:
要解决此问题,请运行一系列检查和更新,直到找到主集合或已删除项目集合中都没有出现的唯一名称。下面是在 C# 中实现此目的的一种有组织的方法:
示例:
公共字符串 GetUniqueName(string baseName)
{
字符串当前名称 = 基本名称;
To address this issue, run a series of checks and updates until you locate a unique name that does not appear in either the main collection or the deleted items collection. Here's an organised way to accomplish this in C#:
example:
public string GetUniqueName(string baseName)
{
string currentName = baseName;