R
R
Rag'n' Code Man2021-11-01 21:44:20
C++ / C#
Rag'n' Code Man, 2021-11-01 21:44:20

Is the problem in the "non-random" randomness or an implementation error?

I have a function that paints random pixels on a photo depending on the specified degree of "corruption" of the photo.

public Bitmap Break(float ratio)
        {
            if (ratio < 0 || ratio > 1)
            {
                throw new ArgumentException("Ratio must be in range 0..1");
            }
            
            var bitmap = new Bitmap(_path);
            
            var width = bitmap.Size.Width;
            var height = bitmap.Size.Height;

            var pixelsToBrake = Math.Floor(width * height * ratio);

            for (int i = 0; i <= pixelsToBrake; i++)
            {
                bitmap.SetPixel(new Random().Next(0, width), new Random().Next(0, height), Color.White);
            }

            return bitmap;
        }

But the result always turns out to be somehow strange: there is a certain priority in painting

61803567e73fa675205831.jpeg
. Is this the result of the "synthetic" randomness in C # or did I write something wrong somewhere?

If you remove the check for the ratio and put some brutal coefficient, then the result is even more visible

618036cba5a90075584464.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-11-01
@iDmitriyWinX

In C#, when a Random object is created without a parameter, it is initialized with the system time, which has finite resolution. If two objects are created with the same initializer value, they will produce the same sequence.
In your case, you need to create a Random object once before the loop, and only call its Next method in the loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question