Question

I am working on a project and need a little help with the behavior of nested for loops. The following code is what I have tried to use

        for (int i = 0; i < 5; i++) {
            for (int j = 1; j < 5; j++) {
            // some code here
            }
        }

I am trying to compare cards in a players hand for a poker game. I want to check if the player has two cards of the same rank. Using the above code will double count some cards and I do not want this. I did some work and figured that to compare each card with another card once, I would need to check

          i=0 : j=1, j=2, j=3, j=4
          i=1 : j=2, j=3, j=4
          i=2 : j=3, j=4
          i=3 : j=4

I am not sure how to accomplish this check with nested for loops. Right now my nested for loop is checking

          i=0 : j=1, j=2, j=3, j=4
          i=1 : j=1, j=2, j=3, j=4
          i=2 : j=1, j=2, j=3, j=4
          i=3 : j=1, j=2, j=3, j=4

I have tried to increment j after each loop but it did not give me the results I wanted. Does anyone know how I can accomplish this?

Was it helpful?

Solution

Maybe you want this

    for (int i = 0; i < 5; i++) {
        for (int j = i + 1; j < 5; j++) {
        // some code here
        }
    }

note the j = i + 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top