jubibanna
jubibanna

Reputation: 1185

Count computation steps in a method with ternaries

I'm looking for a way to somehow count amount of steps:

public static int Calculate0(int end, int init, int lim, int bon)
{
    return end <= 0
        ? 0

        : Math.Min(2 * lim, bon == 0 ? init : init + (2 * bon - lim / bon) * end);
}

I guess my problem kind of two fold:

  1. I dont understand the the special :? operator in C# and
  2. I don't know where to input some kind of variable into the Calculate0 method.

Been trying to read about the :? operator through Microsoft's guide but I still struggle with understanding what happens inside Calculate0.

My code is currently looking like this. Can this be correct?

using System;

namespace TestProject {
    internal class Program
    {
        private int calc0Steps = 0;

        public static void Main() {

            var calc0 = Program.Calculate0(1, 0, 1, 2);
            Console.WriteLine("Calculate: {0} | Steps: {1}", calc, calc0Steps);

        }

        public static int Calculate0(int end, int init, int lim, int bon)
        {
            return end <= 0
                ? 0

                : calc0Steps; Math.Min(2 * lim, bon == 0 ? init : init + (2 * bon - lim / bon) * end);
        }
    }
}

Update

I'm sorry for being confusing. I'll try to narrow it down: How can I put a counter into Calculate0?

The main scope of my assignment is to do a full test coverage of the method fhcimolin provided and compare this method to Calculate0. A small side task is to count the computational steps. But I had no idea how I implemented a counter in Calculate0 in the first place.

I'm having another version of Calculate0 looking like fhcimolin's answer, where I can put in a counter. And I need to count how many computation steps there are in both.

Upvotes: 1

Views: 79

Answers (1)

fhcimolin
fhcimolin

Reputation: 614

If I got your logic right, you might want your Calculate0 method to look like this:

public static int Calculate0(int end, int init, int lim, int bon)
{
    return end <= 0 ? calc0Steps : Math.Min(2 * lim, bon == 0 ? init : init + (2 * bon - lim / bon) * end);
}

Which would the be equivalent of:

public static int Calculate0(int end, int init, int lim, int bon)
{
    if (end <= 0)
    {
        return calc0Steps;
    }
    else
    {
        int aux;

        if (bon == 0) {
            aux = init;
        }
        else
        {
            aux = init + (2 * bon - lim / bon) * end;
        }

        return Math.Min(2 * lim, aux);
    }
}

Upvotes: 1

Related Questions