84.3k views
0 votes
Write a program that reads the number of stalls and then prints out diagrams in the format given above when the stalls become filled, one at a time. Hint: Use an array of boolean values to indicate whether a stall is occupied.

User Kyla
by
4.4k points

1 Answer

5 votes

Answer:

/* package whatever; // don't place package name! */

import java.util.*;

import java.lang.*;

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

public class Ideone

{

public static final int STALL_COUNT = 10;

public static int find_stall(boolean[] stalls) {

int longest_count = -1;

int longest_length = 0;

int current_count = -1;

int current_length = 0;

boolean inRun = false;

for (int i = 0; i < stalls.length; i++) {

if (inRun && stalls[i]) {

inRun = false;

if (current_length >= longest_length) {

longest_length = current_length;

longest_count = current_count;

}

}

else if (!inRun && !stalls[i]) {

inRun = true;

current_count = i;

current_length = 1;

}

else if (inRun && !stalls[i]) {

current_length += 1;

}

}

if (inRun) {

if (current_length >= longest_length) {

longest_length = current_length;

longest_count = current_count;

}

}

return (longest_length - 1) / 2 + longest_count;

}

public static void print_pattern(boolean[] stalls) {

for (int i = 0; i < stalls.length; i++) {

if (stalls[i]) {

System.out.print("X ");

}

else {

System.out.print("_ ");

}

}

System.out.println();

}

public static void main (String[] args) throws java.lang.Exception

{

boolean[] stalls = new boolean[STALL_COUNT];

for (int i = 0; i < stalls.length; i++) {

stalls[find_stall(stalls)] = true;

print_pattern(stalls);

}

}

}

User Tahmid Ali
by
4.2k points