¿Por qué es el color del píxel aleatoria no tan al azar en mi aplicación C #?
Pregunta
He creado un código para cubrir al azar un mapa de bits de 2 colores diferentes, 7 de cada 10 veces el color sería azul, y 3 de cada 10 veces, el color sería verde. Sin embargo, cuando se hace lo que parece muy poco al azar, como se decidió poner 7 píxeles azules un par de veces, luego 3 píxeles verdes unas cuantas veces y así sucesivamente.
Ejemplo:
Mi código es:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FourEx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(canvas.Image);
System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
unsafe
{
int tempy = 0;
while (tempy < 600)
{
byte* row = (byte*)bmpdata.Scan0 + (tempy * bmpdata.Stride);
for (int x = 0; x <= 800; x++)
{
Random rand = new Random();
if (rand.Next(1,10) <= 7)
{
row[x * 4] = 255;
}
else
{
row[(x * 4) + 1] = 255;
}
}
tempy++;
}
}
bmp.UnlockBits(bmpdata);
canvas.Image = bmp;
}
}
}
Si necesita una información adicional, que me haga saber.
Solución
mover esta línea:
Random rand = new Random();
con el alcance más externa. Si crea éstos rápidamente muchos tendrán la misma semilla de tiempo (debido a la precisión del reloj) y va a generar la misma secuencia 'aleatoria'. Además, sólo se necesita realmente un caso al azar ...
private void Form1_Load(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(canvas.Image);
System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Random rand = new Random();
unsafe
{
// ....
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow