public partial class Form1 : Form
{
const int block_size = 3;
const int size_button = 50;
public int[,] map = new int[block_size * block_size, block_size * block_size];
public Form1()
{
InitializeComponent();
GenerateMap();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void GenerateMap()
{
for (int i = 0; i < block_size * block_size; i++)
{
for (int j = 0; j < block_size * block_size; j++)
{
map[i, j] = (i * block_size + i / block_size + j) % (block_size * block_size) + 1;
}
}
MatrixTransposition();
SwapRowsInBlock();
SwapColumnsInBlock();
CreateMap();
}
public void SwapRowsInBlock()
{
Random rand = new Random();
var block = rand.Next(0, block_size);
var row1 = rand.Next(0, block_size);
var line1 = block * block_size * row1;
var row2 = rand.Next(0, block_size);
while (row1 == row2)
row2 = rand.Next(0, block_size);
var line2 = block * block_size * row2; ;
for (int i = 0; i < block_size * block_size; i++)
{
var temp = map[line1, i]; // тут пишет ошибку "Индекс находился вне границ массива."
map[line1, i] = map[line2, i];
map[line2, i] = temp;
}
}
public void SwapColumnsInBlock()
{
Random rand = new Random();
var block = rand.Next(0, block_size);
var row1 = rand.Next(0, block_size);
var line1 = block * block_size * row1;
var row2 = rand.Next(0, block_size);
while (row1 == row2)
row2 = rand.Next(0, block_size);
var line2 = block * block_size * row2; ;
for (int i = 0; i < block_size * block_size; i++)
{
var temp = map[i, line1];
map[i, line1] = map[ i, line2];
map[i, line2] = temp;
}
}
public void MatrixTransposition()
{
int[,] tmap = new int[block_size * block_size, block_size * block_size];
for (int i = 0; i < block_size * block_size; i++)
{
for (int j = 0; j < block_size * block_size; j++)
{
tmap[i, j] = map[j, i];
}
}
map = tmap;
}
public void CreateMap()
{
for (int i = 0; i < block_size * block_size; i++)
{
for (int j = 0; j < block_size * block_size; j++)
{
Button button = new Button();
button.Size = new Size(size_button, size_button);
button.Text = map[i, j].ToString();
button.Location = new Point(j * size_button, i * size_button);
this.Controls.Add(button);
}
}
}
}
}