Efforts in iteration - FizzBuzz

北城以北 提交于 2019-12-01 14:01:38
StringBuilder result = new StringBuilder();

For a fixed upper bound (100) I wouldn’t bother with this but ok …

StringBuilder line = new StringBuilder();

But this StringBuilder isn’t only redundant, it’s really inefficient. And I don’t even need to benchmark to know this.

if (line.Length == 0)

And this just obscures the logic (this is supposed to implement the “fizzbuzz” problem, right?). Make the logic explicit.

Please consider both performance and maintainability.

That’s the wrong way round. Maintainability first, performance second (if at all). Your code is actually quite inefficient but that’s irrelevant: there are 100 iterations – performance doesn’t matter at all.

Furthermore, what maintainability overhead does this code have? It’s a toy sample with fixed specs. There are no maintainability issues. I wouldn’t even bother with anything fancy here, Linq solves this automagically:

return Enumerable.Range(1, bound - 1).Aggregate("",
    (accu, i) =>
        string.Format("{0}\n{1}", accu,
            i % 15 == 0 ? "fizzbuzz" :
            i % 3 == 0 ? "fizz" :
            i % 5 == 0 ? "buzz" : i.ToString()));

But I agree that this may strain readability if one isn’t used to the Aggregate function. So make it more explicit:

var result = new StringBuilder();
for (int i = 1; i < bound; i++)
    result.AppendLine(
        i % 15 == 0 ? "fizzbuzz" :
        i % 3 == 0 ? "fizz" :
        i % 5 == 0 ? "buzz" : i.ToString());
return result.ToString();

Everything else is over-engineering.

Assuming that your code is just an example of what you want to achieve... a proposal to create less StringBuilders:

{
      StringBuilder result = new StringBuilder();
      for (int i = 1; i < 101; i++)
      {
           var rest3 = i % 3;
           var rest5 = i % 5;

           if (rest3 == 0) result.Append("fizz");
           if (rest5 == 0) result.Append("bang");
           if (rest3 != 0 && rest5 != 0)
               result.Append(i);

           result.Append(System.Environment.NewLine);
      }
}

What if we make things a bit more difficult? 1) No division or modulo operations allowed; 2) The loop must skip all unnecessary iterations. Here is the answer:

int n3 = 3;
int n5 = 5;
int i = 3;
while (i <= 100)
{
    Console.Write(i.ToString() + " - ");

    if (i == n3)
    {
        Console.Write("fizz");

        n3 = n3 + 3;
    }

    if (i == n5)
    {
        Console.Write("buzz");

        n5 = n5 + 5;
    }

    Console.WriteLine();

    i = n3 < n5 ? n3 : n5;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!