C#C
C#5mo ago
0ri3lla-

✅ help w homework

i know it so basic but i dont know what to do (im new to c#)
i got a task to do randomize numbers in an array of buttons (4X4) etc.. but the part where
i need to randomize the numbers (strings of numbers) between 1-15 on the buttons is not good because there are numbers that repet themselves and idk how to fix it (i tried stuf and it didnt work).
how can i fix it?
//btw there needs to be one button that we cant see (visible = false).

thecode i did:
C#
using System;

namespace WinFormsApp5
{
    public partial class Form1 : Form
    {
        Button[] buttons = new Button[16];

        private void shuffle()
        {
            Random r = new Random();

            int len = buttons.Length;
            for (int i = len - 1; i > 0; i--)
            {
                int num = r.Next(i + 1);

                Button temp = buttons[i];
                buttons[i] = buttons[num];
                buttons[num] = temp;
            }
        }
        public Form1()
        {
            Random rand = new Random();

            InitializeComponent();
            for (int i = 0; i < 16; i++)
            {
                Random dnar = new Random();
                int nums = dnar.Next(1, 16);//1-15

                buttons[i] = new Button();
                buttons[i].Size = new Size(80, 80);
                buttons[i].BackColor = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
                int row = i / 4;
                int col = i % 4;
                int inbetween = 5;
                int size = 80;
                int x = row * (size + inbetween);
                int y = col * (size + inbetween);
                buttons[i].Location = new Point(x, y);
                buttons[i].Text = nums.ToString();
                this.Controls.Add(buttons[i]);

                if (i == 15)
                {
                    buttons[i].Visible = false;
                }
            }
        }
    }
}
image.png
image.png
Was this page helpful?