Java 使用尽可能小的空间在一行中分布点
我有一行最多可以包含N个点。我想用尽可能小的空间,从中心向外分布该行内的x点 我已设法在行内均匀分布点,但它使用了所有可用空间。使用公式floori+0.5*N/x,考虑到N=9,我得到以下结果: 以下是上述输出中所示指数的图形表示示例: 我想基本上限制点远离中心太远,所以我得到的结果更像:Java 使用尽可能小的空间在一行中分布点,java,point,spacing,Java,Point,Spacing,我有一行最多可以包含N个点。我想用尽可能小的空间,从中心向外分布该行内的x点 我已设法在行内均匀分布点,但它使用了所有可用空间。使用公式floori+0.5*N/x,考虑到N=9,我得到以下结果: 以下是上述输出中所示指数的图形表示示例: 我想基本上限制点远离中心太远,所以我得到的结果更像: 4 3 5 3 4 5 2 3 5 6 2 3 4 5 6 1 2 3 5 6 7 1 2 3 4 5 6 7 0 1 2 3 5 6 7 8 0 1 2 3 4 5 6 7 8 以下是上
4
3 5
3 4 5
2 3 5 6
2 3 4 5 6
1 2 3 5 6 7
1 2 3 4 5 6 7
0 1 2 3 5 6 7 8
0 1 2 3 4 5 6 7 8
以下是上述输出中所示指数的图形表示示例:
我正在使用Java,这是我当前的代码
int rowLength = 9;
for (int points = 0; points <= rowLength; points++) {
for (float i = 0; i < points; i++) {
double result = Math.floor((i + 0.5) * rowLength / points);
System.out.print((int) result + " ");
}
System.out.println();
}
如何才能最好地实现第二幅图像中显示的结果,从而使代码的输出与第二个示例输出的输出相匹配?好的,让我们看看图片。在我看来,似乎有几行有共同之处: 意见: 蓝色线的中间点是填充的,橙色线的中间点是空的。 蓝色的有奇数,橙色的有偶数。 左边的空间是 在奇数情况下:行长-点数/2,例如9-1/2=4 在偶数情况下:行长-点-1/2,例如9-2-1/2=3 让我们把它写成代码。我在这里使用C,但Java应该非常类似:
int rowLength = 9;
for (int points = 0; points <= rowLength; points++) {
bool isOdd = points%2 == 1;
if (isOdd)
{
int spaceOnSide = (rowLength-points)/2;
for (int i=0; i<points;i++)
{
Console.Write(""+(i+spaceOnSide)+" ");
}
}
else // even
{
int spaceOnSide = (rowLength-1-points)/2;
for (int i=0; i<points/2;i++)
{
Console.Write(""+(i+spaceOnSide)+" ");
}
for (int i=points/2; i<points;i++)
{
Console.Write(""+(i+spaceOnSide+1)+" ");
}
}
Console.WriteLine();
}
给出与相同的结果
int spaceOnSide = (rowLength-points)/2;
没有-1
我们可以将奇数情况下的for循环分成两部分:
for (int i=0; i<points/2;i++)
{
Console.Write(""+(i+spaceOnSide)+" ");
}
for (int i=points/2; i<points;i++)
{
Console.Write(""+(i+spaceOnSide)+" ");
}
等于
(points+1)%2
最终,您得到了如下简单的代码
int rowLength = 9;
for (int points = 0; points <= rowLength; points++) {
int spaceOnSide = (rowLength-points)/2;
for (int i=0; i<points/2;i++)
{
Console.Write(""+(i+spaceOnSide)+" ");
}
for (int i=points/2; i<points;i++)
{
Console.Write(""+(i+spaceOnSide+(points+1)%2)+" ");
}
Console.WriteLine();
}
a我问的是如何得到我想要的,因为尽管我付出了努力,但我还没有达到我所拥有的程度。b图片是提供的输出的图形表示。我已经更新了问题,使其尽可能清楚。rowLength=8如何?你认为指数会在哪里?没有中间派,这是一个很好的观点。如果rowLength=8或任意偶数rowLength,则我的代码不起作用。理想情况下,我只想关心奇数。
(isOdd?0:1)
(points+1)%2
int rowLength = 9;
for (int points = 0; points <= rowLength; points++) {
int spaceOnSide = (rowLength-points)/2;
for (int i=0; i<points/2;i++)
{
Console.Write(""+(i+spaceOnSide)+" ");
}
for (int i=points/2; i<points;i++)
{
Console.Write(""+(i+spaceOnSide+(points+1)%2)+" ");
}
Console.WriteLine();
}