Leo Gallegos Leo Gallegos - 14 days ago 21
Java Question

Having trouble with a one dimensional array

My assignment asks:

Design a program that will simulate how theater seats may fill as people walk into the theater. The program should maximize the distance between each person by trying to find a seat in the middle of the longest sequence of unoccupied seats. The program should ask the user for the amount of seats and then print out diagrams (one diagram per line) each time a new person occupies a seat.

So far I have:

{
//...
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;
}


The output for ten seats is:

_ _ _ _ _ _ _ _ _ _
_ _ _ _ _ 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


I'm lost on how to compare the length of the empty seats and how I would return what the middle seat is of the longest sequence of unoccupied seats. The output has 11 rows because I'm suppose to display the seats before they are occupied and each time a new seat gets occupied. Sorry if I'm not very specific this is the first time asking a question on this site.

Answer

I would create a variable that represents a location on the row. Let that position be the starting position of the line of unoccupied seats. Find that position, then calculate exactly how long it is until the next occupied seat, divide that by two, then add that to the starting seat. Pseudo code for the algorithm

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