所以我今天花了几个小时写出逻辑,然后把它变成代码,但我完全陷入困境,我不知道该怎么做.我现在只用java编程了几个月,所以整个"逻辑"思维方式还没有完全实现.谁能帮助我思考如何在java中创建ulam螺旋的逻辑?
import java.util.Arrays;
public class GridMaker {
private static int gridRow = 5; // R = length
private static int gridCol = 5; // C = height
private static int[][] grid = new int[gridRow][gridCol];
private static int totalSteps = (gridRow * gridCol); // total blocks on the grid
private static int location = 1; // location refers to the number in the box, ie. 1, 2, 3, etc.
private static int rowLength = 1;
public static void main(String[] args) {
grid[Calc.findArrayCenter(gridRow)][Calc.findArrayCenter(gridRow)] = 1;
rowBrowser();
colBrowser();
for (int r = 0; r < gridRow; r++){
for (int c = 0; c < gridCol; c++){
System.out.print(grid[r][c] + " ");
}
System.out.println("");
}
}
public static void rowBrowser() {
int rowCount = 1;
int x = 1;
int stepsInvolved = 2;
if (x < stepsInvolved) {
if (Calc.isOdd(rowCount) == true) {
grid[Calc.findArrayCenter(gridRow)][Calc.findArrayCenter(gridCol) + x] = location + 1;
stepsInvolved++;
}
}
location++;
x++;
}
private static void colBrowser() {
}
}
Run Code Online (Sandbox Code Playgroud)
public class Calc {
public static int findArrayCenter(int center) {
int fcenter = 0;
if (center % 2 != 0)
fcenter = (int) ((center / 2));
else
fcenter = (center / 2);
return fcenter;
}
public static boolean isOdd(int num) {
boolean result = true;
if (num % 2 == 0)
result = false; // false = even, true = odd
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
在这一点上,我需要做些什么才能完成ulam螺旋?我现在正在做的是让数组跟踪一个位置,遍历一行中的每一步,然后下拉并运行一列中的步骤,然后向每个计数器添加1并继续.救命?抱歉可怕的格式化,这个网站在粘贴代码时并没有那么多帮助......:|
你不清楚你的代码有什么问题; 最好明确一下你想要什么样的行为以及你正在观察什么行为,以及你在哪些方面特别坚持使它们匹配.
但是,我建议您首先打印一个简单的数字螺旋图案.根据关于Ulam螺旋的维基百科文章,基本螺旋看起来像这样:

对螺旋的一点研究显示了一些有趣的特性.从中心开始(打印"1"),在对角线上向下和向右,您可以看到所有奇数正方形.(每行保存最后一个延伸超过正方形,包括(2k + 1)2 +1.)同样,在对角线向上和向左,你会看到形式的所有数字(2k)2 + 1(一加偶数方块).您可以使用这些属性来计算螺旋的每一行的边界.
假设您要打印2N + 1行和螺旋列(在图中,N = 3).设中心行为第0行,第0列,因此行和列索引的范围为-N到+ N(含).想象一下(2N + 1)×(2N + 1)个细胞矩阵是有意义的.我们的工作是决定如何填写这个矩阵.
此时,有几种方法可以解决这个问题.在一种方法中,您可以通过决定每个整数1,2,......等的位置来填充它,从单元格(0,0)处的"1"开始.另一种方法是为每个单元格(c,r)决定其中的整数.
我们采取后一种方法.我们可以观察到行r的以下属性:
r≤0
r≥0
根据这些规则,您应该能够创建一个算法来打印任何N> 0的螺旋线.我没有解决单元格之间垂直连接的问题,但是您可以应用类似的分析来发现绘制它们的规则.为了正确格式化,你应该为每个单元格选择一个固定的宽度(显然,对于最大的数字,它应该足够宽,(2N + 1)2).
| 归档时间: |
|
| 查看次数: |
3928 次 |
| 最近记录: |