Joe-K2018
Joe-K2018

Reputation: 13

Variable is not being reevaluated outside of loop

I'm working on a Hackerrank problem and my while loop is not working as I would expect. I have a variable external to the loop that is the sum of two other variables, one of which is updated each loop. Since I have a conditional statement in the loop that includes the variable that is external to the loop, I would expect it to be re-evaluated each loop, but it is not. I can work around this, but want to know why this is the case.

Please see my method below. I would expect kangaroo1Location and kangaroo2Location to be re-evaluated each loop to include the new values of kangaroo1DistanceJumped and kangaroo2DistanceJumped, but they are not.

    static string Kangaroo(int x1, int v1, int x2, int v2)
    {
        var kangaroo1DistanceJumped = v1;
        var kangaroo2DistanceJumped = v2;
        var kangaroo1Location = x1 + kangaroo1DistanceJumped;
        var kangaroo2Location = x2 + kangaroo2DistanceJumped;

        while (kangaroo1DistanceJumped <= 10000 && kangaroo2DistanceJumped <= 10000)
        {
            if (kangaroo1Location == kangaroo2Location)
            {
                return "YES";
            }

            kangaroo1DistanceJumped = kangaroo1DistanceJumped + v1;
            kangaroo2DistanceJumped = kangaroo2DistanceJumped + v2;

        }

        return "NO";
    }

I know I could just declare the kangaroo1Location and kangaroo2Location variables within the while loop but I've been told to not declare variables within loops, but maybe that advice is no longer relevant.

Upvotes: 0

Views: 660

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500515

You're not assigning new values to the kangaroo1Location or kangaroo2Location inside the loop. The only assignments to those variables are before the loop:

var kangaroo1Location = x1 + kangaroo1DistanceJumped;
var kangaroo2Location = x2 + kangaroo2DistanceJumped;

These variable assignments aren't declaring a sort of functional relationship that's always true - they're just evaluating an expression (e.g. x1 + kangaroo1DistanceJumped) and assigning the result to a variable.

As a simpler example, consider this code:

int x = 10;
int y = x;

x = 20;
Console.WriteLine(y);

The result will be 10 printed to the console, not 20. x and y are independent variables, it just so happens that y is initialized with the value of x at some point. Later changes to x don't affect y. Apply the same logic to your code, and you'll see why it's not working.

Upvotes: 2

Related Questions