我的作业要求:
设计一个程序,模拟人们走进剧院时剧院座位的填充方式。该计划应通过尝试在最长的未占用座位序列中找到一个座位来最大化每个人之间的距离。程序应该询问用户座位数量,然后每次新人占用座位时打印出图表(每行一张图表)。
到目前为止,我有:
{
//...
System.out.println("Enter the amount of seats: ");
int seatNumber = input.nextInt();
boolean[] seatPosition = new boolean[seatNumber];
String result = "";
for(int n = 0; n < seatNumber; n++){
for(int i = 0; i < seatNumber; i++){
if(seatPosition[i] == false){
result += "_" + " ";
}else{
result += "X" + " ";
}
}
seatPosition[calculation(seatPosition)] = true;
result += "\n";
}
System.out.println(result);
}
public static int calculation(boolean[] values){
int position = 0;
int seatNumber = 0;
int largestCount = 0;
int count = 0;
for(int i = 0; i < values.length; i++){
if(values[seatNumber] == false){
while(values[seatNumber] == true){
count++;
seatNumber++;
}
}
if(count > largestCount){
position = seatNumber;
}
position = position + largestCount / 2 ;
}
return position;
}
十个席位的输出是:
_ _ _ _ _ _ _ _ _ _
_ _ _ _ _ X _ _ _ _
_ _ X _ _ X _ _ _ _
_ _ X _ _ X _ _ X _
_ X X _ _ X _ _ X _
_ X X _ X X _ _ X _
_ X X _ X X _ X X _
X X X _ X X _ X X _
X X X X X X _ X X _
X X X X X X X X X _
X X X X X X X X X X
我迷失了如何比较空座位的长度以及如何返回中间座位是最长的空座位序列。输出有11行,因为我假设在座位被占用之前显示座位,并且每次新座位被占用时。对不起,如果我不是非常具体,这是第一次在这个网站上提问。
答案 0 :(得分:1)
我会创建一个表示行上位置的变量。让那个位置成为空置座位线的起始位置。找到那个位置,然后计算到下一个占用座位的确切长度,将其除以2,然后将其添加到起始座位。算法的伪代码
int position
int seat#
int largest count
int count
repeat seat# times
if seat# isn't occupied
count number of seats until the next seat occupied.
if count > largest count
position = seat#
position = position + largest count / 2