C#:两种不同数据结构中的递归搜索

发布于 2024-12-11 20:01:22 字数 446 浏览 0 评论 0原文

我需要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

抚你发端 2024-12-18 20:01:22
string BuildNextName(string originalName)
{
  string name = originalName;
  while( Exists(name) || deletedNames.Contains(name))
  {
    name = Increment(name);
  }

  return name;
}

或者我错过了什么?

使用for循环:

string BuildNextName(string originalName)
{
  for (string name=originalName; 
       Exists(name) || deletedNames.Contains(name);
       name = Increment(name));

  return name;
}

顺便说一句,我猜你的名称增量算法比简单地添加1更复杂:名称,名称1,名称2,...基本上,如果名称不以数字结尾,则附加“1”。如果是,则增加该数字。正确的?

string BuildNextName(string originalName)
{
  string name = originalName;
  while( Exists(name) || deletedNames.Contains(name))
  {
    name = Increment(name);
  }

  return name;
}

Or did I miss something?

Using a for loop:

string BuildNextName(string originalName)
{
  for (string name=originalName; 
       Exists(name) || deletedNames.Contains(name);
       name = Increment(name));

  return name;
}

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?

与君绝 2024-12-18 20:01:22

非递归且简单的解决方案可能是这样的(在这种情况下我认为不需要递归)

   //pseudocode

    String name;
    bool condition = true;

    while(condition)
    {
        if(ExistInFirstDataStructure(name))
        {
           //increment name
        }
        else
        {
           if(ExistInDeletedDataStructure(String name))
           {
               //increment name
           }
           else
           {
               condition = false;
           }

        }
    }


    bool ExistInFirstDataStructure(String name)
    {

    }

    bool ExistInDeletedDataStructure(String name)
    {

    }

a non recursive and simple solution could be something like this ( I don't see any need of recursion in this case)

   //pseudocode

    String name;
    bool condition = true;

    while(condition)
    {
        if(ExistInFirstDataStructure(name))
        {
           //increment name
        }
        else
        {
           if(ExistInDeletedDataStructure(String name))
           {
               //increment name
           }
           else
           {
               condition = false;
           }

        }
    }


    bool ExistInFirstDataStructure(String name)
    {

    }

    bool ExistInDeletedDataStructure(String name)
    {

    }
-柠檬树下少年和吉他 2024-12-18 20:01:22

为什么要使用循环? (我知道 LINQ 会在幕后)

var LastUsedObjectName =
    MyObjects.Select(mo => mo.Name)
             .Union( MyDeletedObjects.Select(mo => mo.Name))
             .OrderByDescending(name => /*Function to order by integer part of name*/).First();

// Now add 1 to LastUseObjectName and use that.

Why use a loop at all?? (I know LINQ will under the hood)

var LastUsedObjectName =
    MyObjects.Select(mo => mo.Name)
             .Union( MyDeletedObjects.Select(mo => mo.Name))
             .OrderByDescending(name => /*Function to order by integer part of name*/).First();

// Now add 1 to LastUseObjectName and use that.
二智少女 2024-12-18 20:01:22

这个怎么样:

var listOfExistingNames = new List<string> { "MyName", "MyName1", "MyName3" };
var listOfDeletedNames = new List<string> { "MyName2", "MyName5" };

int counter = 0;
string baseToFindFreePlace = "MyName";
string newName = baseToFindFreePlace;

var allNames = listOfExistingNames.Concat(listOfDeletedNames);

while (allNames.Contains(newName))
{
    counter++;
    newName = baseToFindFreePlace + counter;
}

listOfExistingNames.Add(newName);

How about this one:

var listOfExistingNames = new List<string> { "MyName", "MyName1", "MyName3" };
var listOfDeletedNames = new List<string> { "MyName2", "MyName5" };

int counter = 0;
string baseToFindFreePlace = "MyName";
string newName = baseToFindFreePlace;

var allNames = listOfExistingNames.Concat(listOfDeletedNames);

while (allNames.Contains(newName))
{
    counter++;
    newName = baseToFindFreePlace + counter;
}

listOfExistingNames.Add(newName);
话少情深 2024-12-18 20:01:22

如果您为这两种数据结构创建 Exists 方法,则可以使用递归进行搜索,如下所示:
伪代码:

string resultName;
void Search(string name)
{
  if(ExistsInFirstStructure(name)) //name is in first data structure
    Search(name + "1"); //add 1 and try again
  else
    if(ExistsInSecondStructure(name)) //name exists in second data structure
      Search(name + "1"); //perform search again
    else
      resultName = name; //current name wasn't found in first and second data structures - we have result
}

if you create Exists methods for both data structures, you can search with recursion like this:
pseudo code:

string resultName;
void Search(string name)
{
  if(ExistsInFirstStructure(name)) //name is in first data structure
    Search(name + "1"); //add 1 and try again
  else
    if(ExistsInSecondStructure(name)) //name exists in second data structure
      Search(name + "1"); //perform search again
    else
      resultName = name; //current name wasn't found in first and second data structures - we have result
}
简单 2024-12-18 20:01:22

要解决此问题,请运行一系列检查和更新,直到找到主集合或已删除项目集合中都没有出现的唯一名称。下面是在 C# 中实现此目的的一种有组织的方法:

  1. 使用 Exists 方法来确定该名称是否存在于主集合中。
  2. 如果存在,请通过添加“1”来更改名称,然后再次检查。
  3. 如果更新后的名称仍然存在,请继续该过程,直到找到主集合中未出现的名称。
  4. 当您遇到主集合中未出现的名称时,请查看它是否在已删除项目集合中。
  5. 如果它仍然存在于已删除项目集合中,请更改名称并重新启动验证过程。
  6. 继续,直到找到一个未出现在两个集合中的名称。

示例:

公共字符串 GetUniqueName(string baseName)
{
字符串当前名称 = 基本名称;

    while (true)
    {
        // Check if the current name exists in the main collection
        if (_exists(currentName))
        {
            // Modify the name by appending '1'
            currentName = IncrementName(currentName);
        }
        else
        {
            // Check if the current name exists in the deleted objects collection
            if (_deletedObjects.Contains(currentName))
            {
                // Modify the name by appending '1'
                currentName = IncrementName(currentName);
            }
            else
            {
                // Name is unique in both collections
                return currentName;
            }
        }
    }
}

private string IncrementName(string name)
{
    return name + "1";
}

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#:

  1. Use the Exists method to determine whether the name exists in the main collection.
  2. If it exists, change the name by adding a '1' and check again.
  3. If the updated name still remains, continue the procedure until you locate a name that does not appear in the main collection.
  4. When you come across a name that does not appear in the main collection, see whether it is in the deleted items collection.
  5. If it still persists in the deleted items collection, change the name and restart the verification process.
  6. Continue until you locate a name that does not appear in both collections.

example:

public string GetUniqueName(string baseName)
{
string currentName = baseName;

    while (true)
    {
        // Check if the current name exists in the main collection
        if (_exists(currentName))
        {
            // Modify the name by appending '1'
            currentName = IncrementName(currentName);
        }
        else
        {
            // Check if the current name exists in the deleted objects collection
            if (_deletedObjects.Contains(currentName))
            {
                // Modify the name by appending '1'
                currentName = IncrementName(currentName);
            }
            else
            {
                // Name is unique in both collections
                return currentName;
            }
        }
    }
}

private string IncrementName(string name)
{
    return name + "1";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文