CowBoy
CowBoy

Reputation: 195

How can I randomly access my list elements by a percentage?

I have a list of points which are holding the coordinates (x,y) of the black pixels in my image.

List<Point> blackPixels = new List<Point>();

Does nay one know how I can randomly change the colour of the black pixels to white by a specific percentage? i.e. to turn 80% of the black pixels to white? many thanks

Upvotes: 0

Views: 182

Answers (3)

Uri Agassi
Uri Agassi

Reputation: 37409

Random rand = new Random();
foreach (Point p in blackPixels) {

   if (rnd.Next(100) < 80) {
     // turn p to white
   }

}

For each element in the list it generates a number between 0 and 99, which means that 80% of the time the number will be between 0 and 79. This way you turn 80% of the pixels to white.

If you want to change exactly 80% of the pixels, you can go the other way around:

var numberOfPixelsToTurn = blackPixels.Count * 0.8
var rand = new Random();

for (int i; i < numberOfPixelsToTurn ; i++) {
  int itemToTurn = rand.Next(blackPixels.Count);
  TurnToWhite(blackPixels[itemToTurn]);
  blackPixels.RemoveAt(itemToTurn);
}

Upvotes: 2

Pantelis Natsiavas
Pantelis Natsiavas

Reputation: 5369

Random rnd = new Random();    
for(int x=0;x<blackPixels.Length;x++){

    int randomNumber = rnd.next(100);
    if(randomNumber <= 80){

         blackPixels[x] = // add a white pixel
    }

}

Hope I helped!

Upvotes: -1

TypeIA
TypeIA

Reputation: 17258

Use the Random class. Iterate over each pixel. Call the Random.Next(int) method to generate a random integer between 0 and 100. If the random number is less than 80 (yielding an 80% chance), change the pixel to white.

Upvotes: 1

Related Questions