gpt4 book ai didi

c# - Eric Lippert 的挑战 "comma-quibbling",最佳答案?

转载 作者:IT王子 更新时间:2023-10-29 04:25:19 24 4
gpt4 key购买 nike

我想让这个挑战引起 stackoverflow 社区的注意。原始问题和答案是here .顺便说一句,如果你之前没有遵循它,你应该尝试阅读 Eric 的博客,这是纯粹的智慧。

总结:

编写一个接受非空 IEnumerable 并返回具有以下特征的字符串的函数:

  1. 如果序列为空,则结果字符串为“{}”。
  2. 如果序列是单个项目“ABC”,则结果字符串是“{ABC}”。
  3. 如果序列是两项序列“ABC”、“DEF”,则结果字符串是“{ABC and DEF}”。
  4. 如果序列有两个以上的项目,比如“ABC”、“DEF”、“G”、“H”,那么结果字符串是“{ABC, DEF, G and H}”。 (注意:没有牛津逗号!)

正如您所见,即使是我们自己的 Jon Skeet(是的,众所周知 he can be in two places at the same time )也发布了一个解决方案,但他的(恕我直言)并不是最优雅的,尽管您可能无法击败它的性能。

你怎么看?那里有很好的选择。我真的很喜欢涉及选择和聚合方法的解决方案之一(来自 Fernando Nicolet)。 Linq 非常强大,花一些时间来应对这样的挑战会让你学到很多东西。我对它进行了一些改动,使其更高效、更清晰(通过使用 Count 并避免 Reverse):

public static string CommaQuibbling(IEnumerable<string> items)
{
int last = items.Count() - 1;
Func<int, string> getSeparator = (i) => i == 0 ? string.Empty : (i == last ? " and " : ", ");
string answer = string.Empty;

return "{" + items.Select((s, i) => new { Index = i, Value = s })
.Aggregate(answer, (s, a) => s + getSeparator(a.Index) + a.Value) + "}";
}

最佳答案

效率低下,但我认为清晰。

public static string CommaQuibbling(IEnumerable<string> items)
{
List<String> list = new List<String>(items);
if (list.Count == 0) { return "{}"; }
if (list.Count == 1) { return "{" + list[0] + "}"; }

String[] initial = list.GetRange(0, list.Count - 1).ToArray();
return "{" + String.Join(", ", initial) + " and " + list[list.Count - 1] + "}";
}

如果我要维护代码,我更喜欢这个版本而不是更聪明的版本。

关于c# - Eric Lippert 的挑战 "comma-quibbling",最佳答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/788535/

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