1

Is there an easy way for me to select a random bit value from my enum variable?
For example:

[System.Flags]
public enum Direction{
    None = 0,
    Up = 1,
    Down = 2, 
    Left = 4, 
    Right = 8,
    All = ~None
}

public Direction someDir = Direction.Up | Direction.Down;

I would want to select a random positive bit value from someDir so that I could only have Direction.Up or Direction.Down?

Stephan Bauer
  • 8,611
  • 5
  • 37
  • 57
Alec Gamble
  • 411
  • 2
  • 6
  • 15
  • var gen = new Random(); var upOrDown = (Direction ) (gen.Next(1)+1); – mukh1n Mar 21 '17 at 10:03
  • well I want to get a new direction which is one of the values in the `someDir` variable so that I would ultimately get Direction.Up or Direction.Down, or one of whatever values are stored in someDir. – Alec Gamble Mar 21 '17 at 10:05

1 Answers1

2

You should use an array:

Direction validDirections = new[] { Direction.Up, Direction.Down };

and then:

Random rnd = new Random();
Direction selectedDirection = validDirections[rnd.Next(validDirections.Length)];

(remember to reuse the same Random rnd and not recreate it every time)

If you really really want to have a single Direction variable, then you could split it to a List<Direction>:

Direction someDir = Direction.Up | Direction.Down;

var someDir2 = new List<Direction>();

foreach (Direction dir in Enum.GetValues(typeof(Direction)))
{
    if (someDir.HasFlag(dir))
    {
        someDir2.Add(dir);
    }
}

Random rnd = new Random();
Direction selectedDirection = someDir2[rnd.Next(someDir2.Count)];

(see Most efficient way to parse a flagged enum to a list and the various comments about using HasFlag)

Community
  • 1
  • 1
xanatos
  • 106,283
  • 12
  • 188
  • 265
  • okay thanks :) I mean neither of these feel like the clean implementation that I wanted but I can understand the limitations and will work with this. Thanks a lot! :) – Alec Gamble Mar 21 '17 at 10:24