我有5件物品: A,B,C,d,E
我需要将它们分配给2x8数组,但是我需要尽可能远地放置类似的项目,如果可能的话,还要设置simetric地方
例如,如果每个项目的数量包含以下
A = 2,B = 2,C = 3,D = 4,E = 5
手动我可以执行以下操作
E C D A B C E D
D E C B A D E E
我随机尝试了太多东西,但程序挂起了循环
你能不能给我任何想法
由于
答案 0 :(得分:0)
private void button2_Click_1(object sender, EventArgs e)
{
Random rnd = new Random();
richTextBox3.Text = "";
// I have 5 kind of material, each of them have the following amount:
// type A=2
// type B=2
// type C=3
// type D=4
// type E=5
int[] materials = { 2, 2, 3, 4, 5 };
int Xa = materials[0]; // material A amount
int Xb = materials[1]; // material B amount
int Xc = materials[2];
int Xd = materials[3];
int Xe = materials[4];
// I need to place them in 2 row * 8 column
// when doing this assignment I should place the similar materials far away as possible
// It possible symetric order
string[,] array = new string[2,8];
Array.Clear(array, 0, array.Length);
array[0, 0] = "E"; // As beginnig I assigned to (0,0) the most biggest material(E)
Xe = Xe - 1;
array[1, 0] = "D";// For the second row (1,0) the second biggest material (D)
Xd = Xd - 1;
// first row
for (int j = 1; j < 8; j++) // I used the first column for D and E material
{
int random = rnd.Next(0, 5); // I randomly choose one of the material
// if the column is blank (not assigned before and
// If the random material is 0 (A type) and the amount of A is not 0
// and the previous column is not assigned with A type
if (array[0,j]=="" && random == 0 && Xa != 0 && array[0,j-1]!="A")
{
array[0,j] = "A"; // assign A to this column
Xa = Xa - 1; // reduce A amount
richTextBox3.Text += "A"; // write "A" in text box
richTextBox3.Text += " ";
}
// B type condition
else if (array[0,j]=="" && random == 1 && Xb != 0 && array[0,j-1]!="B")
{
array[0,j] = "B"; // assign B to this column
Xb = Xb - 1; // reduce B amount
richTextBox3.Text += "B"; // write "B" in text box
richTextBox3.Text += " ";
}
// C type condition
else if (array[0, j] == "" && random == 2 && Xc != 0 && array[0, j - 1] != "C")
{
array[0, j] = "C"; // assign C to this column
Xc = Xc - 1; // reduce C amount
richTextBox3.Text += "C"; // write "C" in text box
richTextBox3.Text += " ";
}
// D type condition
else if (array[0, j] == "" && random == 3 && Xd != 0 && array[0, j - 1] != "D")
{
array[0, j] = "D"; // assign D to this column
Xd = Xd - 1; // reduce D amount
richTextBox3.Text += "D"; // write "D" in text box
richTextBox3.Text += " ";
}
// E type condition
else if (array[0, j] == "" && random == 4 && Xd != 0 && array[0, j - 1] != "E")
{
array[0, j] = "E"; // assign E to this column
Xe = Xe - 1; // reduce E amount
richTextBox3.Text += "E"; // write "C" in text box
richTextBox3.Text += " ";
}
else j = j - 1; // if all above not true try again
}
}