gpt4 book ai didi

c# - 我将如何在一个简单的有向图中倒数?

转载 作者:行者123 更新时间:2023-11-30 21:51:26 25 4
gpt4 key购买 nike

所以我有这张图表,其中包含我正在遍历并打印出来的书籍。

public class Books : IBookFinder
{
private Books(Books next, string book)
{
Next = next;
Book = book;
}

public Books Next { get; }
public string Book { get; }

public Books Previous(string book)
{
return new Books(this, book);
}

public static Books Create(string book)
{
return new Books(null, book);
}

public string FromLeft(Books books, int numberFromLeft)
{
for (int i = 1; i < numberFromRight; i++)
{
books = books?.Next; //Go through the books and return null if books is null.
}

return books.book; //Should probably check for null here as it crashes if the input number is out of book range (something else than 1-4)
}

public string FromRight(Books books, int numberFromRight
{
//How to implement this bad boy?
}
}

一切都很好,但我想实现一个 FromRight 方法,这样我就可以在给定数字输入的情况下,根据书在图中的位置写出书名。例如,如果输入“3”,它应该输出“指环王”。我该怎么做呢?非常感谢任何提示。

class Program
{
static void Main(string[] args)
{
var curr = Books
.Create("Harry Potter")
.Previous("Lord of the Rings")
.Previous("Twilight")
.Previous("Da Vinci Code");

while (curr != null)
{
if (curr.Next != null)
{
Console.Write(curr.Book + " --- ");
}
else
{
Console.WriteLine(curr.Book);
}
curr = curr.Next;
}

Console.WriteLine("Input number to pick a book");

var bookNumber = Console.ReadLine();
int n;

if (int.TryParse(bookNumber, out n)) //Checking if the input is a #
{

}
else
{
Console.WriteLine("Input was not a number!");
}
Console.WriteLine(bookNumber);

Console.ReadLine();
}
}

更新:

我已经设法找到一种方法来做到这一点,而不必制作双向链表,尽管这当然可能是解决此问题的最佳解决方案。

我创建了一个辅助函数 Count(),它获取列表并对条目进行计数:

    private int Count(Books books)
{
int count = 1;
while (books.Next != null)
{
books = books.Next;
count++;
}

return count;
}

然后我使用此方法的返回值从右侧选择书籍:

    public string FromRight(Books books, int numberFromRight)
{
var bookCount = Count(books); //Getting the amount of books.
for (int i = numberFromRight; i < bookCount; i++)
{
books = boos?.Next;
}

return books.Book;
}

最佳答案

由于您像创建链表一样创建它,因此要倒退,您需要创建一个双向链表:https://en.wikipedia.org/wiki/Doubly_linked_list

您当前的代码没有表示前一个节点。在创建下一个节点时将前一个节点设置为当前节点,然后它的迭代就像你最初做的那样。

迭代直到没有Next,然后打印直到没有previous。

关于c# - 我将如何在一个简单的有向图中倒数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35639447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com