Headshot Headshot - 4 months ago 9
C# Question

Only allow 10 things in an array to be true

public static bool[] chosen = new bool[27];

private void pictureBoxTopLeft3_Click(object sender, EventArgs e)
{
n = 18;
cardSelect();
highlightCards();
} // There are many of these.

public static void cardSelect()
{
if (chosen[n] == false)
{
chosen[n] = true;
}
else if (chosen[n] == true)
{
chosen[n] = false;
}
}


There are multiple picture boxes. Once the picture box is clicked, in this example the picture box being "pictureBoxLeft3", it runs "cardSelect". This sets that picture box to true in the array "chosen". If clicked again, it is set to false.

There are 20 picture boxes in total. How can I make it so only 10 of those can be set to true at one time in the array "chosen". Thanks!

Answer

You could store state or calculate on the fly.

Storing state:

static int chosenCount = 0;

public static void cardSelect()
{
    if (chosen[n] == false)
    {
        if (chosenCount < 10)
        {
            chosen[n] = true;
            chosenCount++;
        }
        // else show a message maybe?
    }
    else if (chosen[n] == true)
    {
        chosen[n] = false;
        chosenCount--;
    }
}

Calculating:

using System.Linq;

public static void cardSelect()
{
    if (chosen[n] == false)
    {
         if (chosen.Count(c => c) < 10)
         {
            chosen[n] = true;
         }
    }
    else if (chosen[n] == true)
    {
        chosen[n] = false;
    }
}