1

Basically for an assignment I need to create a C# program that will take a number as input (n) then create a 2D array size n*n with the numbers 1 to (n*n). It needs to use a brute force method. I have done this but at the moment the program will just randomly generate the order of the numbers each time, so it will sometimes check the same order more than once. Obviously this means it takes a really long time to check any number above 3, and even for 3 it can take a few minutes. Basically I'm wondering if there is any way for me to make it only check each order once. I am only allowed to use "basic" C# functions, so just things like *, /, +, - and nothing like .Shuffle etc.

4

2 回答 2

3

让我确保我理解了这个问题:您希望枚举数字 1 到 n 平方的所有排列,并检查排列是否产生幻方。您现在正在随机生成排列,但您希望生成所有排列。

我写了一系列关于生成排列的文章;篇幅太长,无法在此简单概括。

http://ericlippert.com/2013/04/15/produce-permutations-part-one/

于 2014-01-19T17:48:51.557 回答
1

如您所见,选择随机顺序不是一个好主意。

我建议您将所有数字 1 ... (n*n) 放入 array ,然后找到所有排列。

当您拥有所有排列时,很容易创建正方形(1 .. n ==> 第一行,n+1 ... 2n ==> 第二行,依此类推)。

现在,找到所有的排列可以用递归的基本操作来完成

于 2014-01-19T17:27:20.957 回答