# How to make sure that at least one element in a collection has a certain value?

In my game, I assign each agent a random direction. However, at least one of these agents has to have a direction of Vector2.up. How can I ensure that?

private void AssignRandomDirection()
{
var directions = new List<Vector2>
{
Vector2.up,
Vector2.down,
Vector2.left,
Vector2.right
};

foreach (var agent in FindObjectsOfType<Agent>())
{
var random = Random.Range(0, directions.Count);
agent.direction = directions[random];
}
}

• Presumably you considered checking whether any of the entries is up after random assignment, and if not, choosing one at random to reassign to up? Did you have any trouble making something like this work? – DMGregory Sep 17 at 0:20
• @DMGregory I don't know how to check if any elements in a list has a certain value. – Sean Carey Sep 17 at 0:43
• ....with the == operator? You have the foreach already, so you know how to iterate over the items. Can you clarify where you're stuck? – DMGregory Sep 17 at 0:45
• @DMGregory I know how to use the foreach to iterate over the items and check if all of them have a Vector2.up value, but I don't know how to iterate through the list to see if any of them have that value. – Sean Carey Sep 17 at 0:54

## 1 Answer

Just use a boolean to keep track of whether you've ever assigned a value of up. If not, inject a value of up at a random position in your collection.

private void AssignRandomDirection()
{
// No need for this to be a list, since you never add/remove elements.
var directions = new Vector2[]
{
Vector2.up,
Vector2.down,
Vector2.left,
Vector2.right
};

boolHasAssignedUp = false;

var agents =  FindObjectsOfType<Agent>();

foreach (var agent in agents)
{
var random = Random.Range(0, directions.Length);
hasAssignedUp |= (random == 0);
agent.direction = directions[random];
}

if(hasAssignedUp == false)
agents[Random.Range(0, agents.Length)].direction = directions[0];
}

• What does |= mean? – Sean Carey Sep 17 at 1:20
• Did you google it? Never underestimate your ability to find your own answers. :) – DMGregory Sep 17 at 1:33
• I honestly did, and all I came up with is some cryptic info from msdn and stackoverflow. If it means +=, then how would it apply to a bool? Also, I posted an answer that implement's your original solution. Can you tell me what you think of it? – Sean Carey Sep 17 at 1:39
• | is the OR operator, and = is the assignment operator. A |= B means "Assign the value of A OR B back into A". Just like A += B means "Assign the value of A + B back into A" – DMGregory Sep 17 at 1:47