SkyeBoniwell
SkyeBoniwell

Reputation: 7092

Keeping track of counters in nested loops

I have the following loop(s). This loop traverses through a collection of books and does some logic checks regarding the check-in and check-out dates. It then returns a new object. It also contatenates book titles

It works OK up until it gets to the end of the collection. Then my counters seem to get out-of-sync and it turns into an endless loop. I've tried different permiations, but I just can't get it to work right.

Could someone eyeball this see if it makes sense or if I'm doing something wrong?

Thanks!

    private static readonly TimeSpan gracePeriodTimeSpan = TimeSpan.Parse("23:00");

        //current posistion in books collection
        currentPos = pos % books.Count;

        //posistion to stop at
        var stopPos = books.Count;

        do
        {
            //start is current posistion
            var startPos = pos;

            //assign the next posistion
            var nextPos = (pos + 1) % books.Count;
            bookTitle = bookTitle + ";" + books[pos].Title;

            //loop until we hit the stop posistion - check book CheckInDate/CheckOutDate proximity
            while ((nextPos != stopPos || nextPos !=0) && books[pos].CheckInDate + gracePeriodTimeSpan >= books[nextPos].CheckOutDate)
            {                   
                pos = nextPos;
                nextPos = (pos + 1) % books.Count;
            }
            bookTitle = bookTitle + ";" + books[pos].Title;

            //return new book checkout object
            yield return
                CreateNewBookCheckout(bookTitle, books[pos], books[startPos].CheckOutDate,
                    books[pos].CheckInDate);

            bookTitle = "";
            pos = nextPos;

            //keep going til we hit the stop posistion
        } while (pos != stopPos);

Upvotes: 0

Views: 193

Answers (1)

serhiyb
serhiyb

Reputation: 4833

Just a quick observation:

Your pos is changing to nextPos which is (pos + 1) % books.Count. This operation will always return values between [0 and books.Count - 1] while your stopPos = books.Count which makes infinite loop.

Maybe you need to switch your stopPos to be a last book which is books.Count-1

Upvotes: 1

Related Questions