Can someone explain this to me?

I’m no good with for loops.

My friend wrote this and i didn’t fully understand it when he explained, so if anyone can explain simply how it works, i know what it is supposed to do but does not work, so i want to understand it before i fix it.

public bool CheckifDone()
    {

        bool done = true;
        for (int i = 0; i < Alive.Count; i++)
        {
            bool inDead = false;
            for (int x = 0; x < Dead.Count; x ++)
            {
                if (Alive[i] == Dead[x])
                {
                    Dead.Add (Alive [i]);
                }
            }
            if (inDead == false)
            {
                done = false;
                toKill.Add(Alive[i]);
            }

        }
        for (int y = 0; y < toKill.Count; y++)
        {
            Alive.Remove(toKill[y]);
        }

        return done;

    }

Ok, so what is it supposed to do?

That.

            for (int x = 0; x < Dead.Count; x ++)
            {
                if (Alive[i] == Dead[x])
                {
                    Dead.Add (Alive [i]);
                }
            }

And, the array is modified while you iterate over it… wait. If you enter that if-block, you’ll be stuck in an infinite loop, because the last element added to the Dead will be always Alive[i] .

Without knowing anything about the purpose of this code, and without knowing what these array types are, here are my comments as I read through it:

public bool CheckifDone() {                   // we're checking if something is done

    bool done = true;                         // initialize done to true
    for(int i = 0; i < Alive.Count; i++) {    // for each alive thing
        bool inDead = false;                  // initialize inDead to false
        for(int x = 0; x < Dead.Count; x++) { // for each dead thing
            if(Alive[i] == Dead[x]) {         // if the dead thing is the same object as the alive thing
                Dead.Add(Alive[i]);           // add the alive thing to the dead list (isn't it already in the list??)
            }
        }
        if(inDead == false) {                 // this is guaranteed false, because nothing changed it from earlier
            done = false;                     // guaranteed to be set, due to above
            toKill.Add(Alive[i]);             // kill the alive thing (this will be done for all alive things, due to above)
        }

    }
    for(int y = 0; y < toKill.Count; y++) {   // loop through all things to kill (all alive things, due to above)
        Alive.Remove(toKill[y]);              // remove them from the alive list (Alive list now empty)
    }

    return done;                              // this will always return false, due to above

}
1 Like