书中的问题:
一个经过充分研究的事实是,在洗手间里的男人通常更喜欢通过占据最长的无人位置序列的中间来最大化他们与已经被占用的隔间的距离。
例如,考虑十个摊位是空的情况。_ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _
The first visitor will occupy a middle position:
_ _ _ _ _ _ X _ _ _
The next visitor will be in the middle of the empty area at the left.
_ _ X _ _ X _ _ _ _
编写一个程序,读取档位的数量,然后在档位填满时以上述格式打印出图表,一次一张。提示:使用一个布尔值数组来指示一个档位是否被占用。
我正在努力编写这个问题,我对如何应用布尔值以及如何解决一般问题感到困惑。我已经编写了这段代码,但我认为它没有任何意义,非常感谢帮助。
import java.util.Random;
import java.util.Arrays;
public class Stall
{
public static void main(String[] args)
{
Random random = new Random();
String[] array = {"_"," _ "," _ "," _ "," _ "," _ "," _ "," _ "," _ "," _"};
boolean filled = true; // Checking to see if stalls are completely filled
while (filled = true)
{
for (int i = array.length - 1; i > 0 ; i--)
{
String number = array[i];
if (!(number.equals("X"))) // if filled,all stalls would be marked as X
{
filled = false;
}
}
}
boolean found = false; //checking if "X" is found
while (filled = false)
{
while (found = false) // if not found generate a new number for array and set it to "X";
{
int number1 = random.nextInt(10) + 1;
if (!(array[number1].equals("X")))
{
array[number1] = "X";
found = true;
}
}
while (found = true)
{
int number2 = random.nextInt(10) + 1;
for ( int i = 0; i < array.length; i++)
{
if (!(array[i].equals("X")))
{
array[number2] = "X";
found = false;
}
}
}
System.out.println(Arrays.toString(array));
}
}
}