Anda di halaman 1dari 11

Code only needs to be written where it states Add Your Code Here within the code.

Question:

The CharacterOrganizer class contains a constructor to set up an initial configuration.

It also contains methods to print out stacks as well as to reorganize stack content.

Methods are:

organizeCharacters()

fromSupportingStackToFinalStack()

putInSupportingStack()

Example of sequence of characters given:

'g' 'i' 'a' 'b' 'e' 'f' 'h' 'd' 'c'

with three supporting stacks #0, #1, and #2.

The top of the startStack is 'c', if you pushed all characters from left to right onto the startStack. Since
it is not the smallest, you need to push 'c' onto the supporting stack, say, #0.

The next character of the startStack is 'd'. It cannot be pushed onto the supporting stack #0 because it
is larger than the top of the supporting stack #0, which is 'c'. So we can push 'd' onto another
supporting stack, say #1.

Similarly, 'h' will be pushed onto the supporting stack #2.

Now, the next character 'f' can be pushed only onto the supporting stack #2 because that is the only
stack whose top is larger than 'f'. Remember, the content of each supporting stack needs to be
increasing order.

After pushing 'c', 'd', 'h', 'f', 'e', 'b' onto supporting stacks, the content of supporting stacks will be:

Supporting stack 0: [c, b]

Supporting stack 1: [d]

Supporting stack 2: [h, f, e]

The next character from the startStack is 'a', so this is pushed directly onto the finalStack.
At this point, the next smallest character 'b' is at the top of the supporting stack #0. So we pop it and
push it onto the finalStack. Then we will do the same for the character 'c'. We continue to pop from
the supporting stacks as long as the next smallest character is at the top of one of the supporting
stacks.

After popping 'b', 'c', 'd', 'e', and 'f', we have:

Supporting stack 0: []

Supporting stack 1: []

Supporting stack 2: [h]

// Description: This program will take out all characters in the start stack

// and put them into the final stack in their sorted order using supporting stacks.

import java.util.Stack;

public class CharacterOrganizer

private Stack<Character> startStack; //stack contains characters in an order specified by a user

private Stack<Character> finalStack; //stack to have characters in sorted order after running this
algorithm

private Stack<Character>[] supportingStacks; //stacks to hold some characters that are not in either
start or final stack

private int sizeOfStartStack; //the start stack size

private int numberOfSupportingStacks; //number of supporting stacks, specified by a user

private char smallestCharacter; //current smallest character that can be moved to the final stack

private int stackWithNextSmallest; //the index of supporting stack that contains the next smallest
character

private final int ASCII_FOR_a = ((int) 'a'); //ASCII number for a, we can use it to keep track of
smallest/largest characters

//Constructor to initialize member variables

public CharacterOrganizer(int sizeOfStartStack, int numOfSupportingStacks)


{

startStack = new Stack<Character>();

finalStack = new Stack<Character>();

this.sizeOfStartStack = sizeOfStartStack;

this.numberOfSupportingStacks = numOfSupportingStacks;

supportingStacks = new Stack[numberOfSupportingStacks];

for (int i=0; i< numberOfSupportingStacks; i++)

supportingStacks[i] = new Stack<Character>();

smallestCharacter = (char) (sizeOfStartStack+1-ASCII_FOR_a); //itinialize to a large character

stackWithNextSmallest = -1; //index of supporting stack containing the next smallest is unknown

//The addCharacterToStack adds the parameter character

//to the start stack

public void addCharacterToStack(char character1)

startStack.push(character1);

//The printSupportingStacks prints out the content

//of the supporting stacks

public void printSupportingStacks()

System.out.println("Supporting Stack Contents:\n");

for (int i = 0; i < numberOfSupportingStacks; i++)

System.out.println("Supporting Stack " + i + ": " + supportingStacks[i].toString());

System.out.println();
}

//The organizeCharacters method reorganizes the characters in the start stack

//into a sorted order in the final stack

public boolean organizeCharacters()

boolean success = true;

//the next character that should move to final stack is initially 'a'

char nextCharacterToFinalStack = 'a';

//Print out the start stack content

System.out.println("Start Stack Content:\n" + startStack.toString());

while(startStack.empty() == false)

//get the next character to move

char nextCharacter;

//get(pop) the next character to move from the start stack

//and assign it to "nextCharacter"

/****1. ADD Your Code Here ****/

if (nextCharacter == nextCharacterToFinalStack)

//if it is the next smallest character,

//then push it onto the final stack

/***2. ADD Your Code Here ****/

System.out.println("Move character " + nextCharacter

+ " from start stack to final stack");

//nextCharacterToOutputStack should be incremented now

//to loop for the next smallest character.

nextCharacterToFinalStack++;
//As long as the smallest character among all supporting stacks

//is same as the next character to move to final stack,

//process the following:

while (smallestCharacter == nextCharacterToFinalStack)

//look for the next smallest character among supporting stacks

//This will compute the smallest character and which supporting stack it belongs

fromSupportingStackToFinalStack();

nextCharacterToFinalStack++;

else

//put the next character into one of the supporting stack

if (putInSupportingStack(nextCharacter) == false)

success = false;

return success;

System.out.println("Final Stack Content:\n" + finalStack.toString());

return success;

//The fromSupportingStackToFinalStack moves the smallest element among

//all supporting stacks into the final stack.

//It also keeps track of the next smallest character and the supporting stack

//that contains in it.

public void fromSupportingStackToFinalStack()


{

if (stackWithNextSmallest >= 0

&& supportingStacks[stackWithNextSmallest].isEmpty() == false)

//remove(pop) the smallest character from its supporting stack

//and move(push) to the final stack

/****3. ADD Your Code Here ****/

System.out.println("Move character " + smallestCharacter + " from supporting stack#"

+ stackWithNextSmallest + " to final stack");

printSupportingStacks();

//Find the next smallest character and the supporting stack that contains it

//by checking the top of all supporting stacks

smallestCharacter = (char) (sizeOfStartStack + 1 - ASCII_FOR_a);

for (int i = 0; i < numberOfSupportingStacks; i++)

if (supportingStacks[i].isEmpty() == false

&& (supportingStacks[i].peek()).charValue() < smallestCharacter)

smallestCharacter = supportingStacks[i].peek().charValue();

stackWithNextSmallest = i;

//After the above loop, the variable "stackWithNextSmallest" should have an index

//of the holding stack contains the next smallest character

//AND the variable "smallestCharacter" should have the next smallestCharacter

//to move to the final stack.

}
//The putInSupportingStack tries to push the parameter character

//into the chosen stack, i.e., the one with the top element larger

//than the parameter character and also with the top element smallest among

//such supporting stacks.

//If it cannot find such supporting stack, it returns false.

public boolean putInSupportingStack(char character2)

int chosenStackIndex = -1; //initialize to a stack index that does not exists

char bestTop = (char) (sizeOfStartStack + 1 + ASCII_FOR_a); //initialize a larger character

for (int i = 0; i < numberOfSupportingStacks; i++)

//look for a non-empty stack that contains its top character which is larger than

//the parameter character to push into.

//The index of the supporting stack with smallest top should be the chosenStackIndex

//If the stack that you check is empty, go ahead and pick that supporting

//stack's index as the chosenStackIndex if the chosenStackIndex was not

//selected yet.

/****4. ADD Your Code Here ****/

//The process cannot be completed

//since all supporting stacks have its top character being smaller than

//the character to be inserted.

if (chosenStackIndex == -1)

return false;

//The process can continue, by pushing the parameter "character2"

//into the supporting stack of the chosenStackIndex

/****5. ADD Your Code Here ****/


System.out.println("Move the character " + character2 + " from start stack "

+ "to supporting stack#" + chosenStackIndex);

printSupportingStacks();

//update the variable "smallestCharacter" to the parameter character2

//and the variable "stackWithNextSmallest" to "chosenStackIndex"

//if character2 is smaller than "smallestCharacter"

/****6. ADD Your Code Here ****/

return true;

Assignment11 class nothing has to be fixed here, just simply to help make program run.

// Description: Assignment 11 class displays a menu of choices to a user

// and performs the chosen task. It will keep asking a user to

// enter the next choice until the choice of 'Q' (Quit) is entered.

import java.io.*;

public class Assignment11

public static void main (String[] args) throws IOException

char input1;

String line = new String();

printMenu();

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader stdin = new BufferedReader(isr);

do // will ask for user input

System.out.println("What action would you like to perform?");

line = stdin.readLine();

input1 = line.charAt(0);

input1 = Character.toUpperCase(input1);

if (line.length() == 1)

// matches one of the case statements

switch (input1)

case 'C': //Specify Problem parameters

try

System.out.print("Please specify how many characters will be used (the maximum is 26):\n");

int stackSize = Integer.parseInt(stdin.readLine().trim());

System.out.print("Please specify how many supporting stacks to use:\n");

int numberOfSupportingStacks = Integer.parseInt(stdin.readLine().trim());

if (stackSize > 0 && stackSize <= 26 && numberOfSupportingStacks > 0)

//Create an organizer object

CharacterOrganizer organizer = new CharacterOrganizer(stackSize, numberOfSupportingStacks);

//Read-in characters and add them to the stack


for (int i = 0; i < stackSize; i++)

System.out.print("Please enter a character:\n");

char character1 = stdin.readLine().trim().charAt(0);

organizer.addCharacterToStack(character1);

//sort the elements using stacks

boolean success = organizer.organizeCharacters();

if (success == true)

System.out.print("\norganization completed\n");

else

System.out.print("\norganization not completed\n");

else

System.out.print("Please enter a valid integer\n");

catch(NumberFormatException ex)

System.out.print("Please enter a valid number\n");

break;
case 'Q': //Quit

break;

case '?': //Display Menu

printMenu();

break;

default:

System.out.print("Unknown action\n");

break;

else

System.out.print("Unknown action\n");

} while (input1 != 'Q' || line.length() != 1);

/** The method printMenu displays the menu to a user**/

public static void printMenu()

System.out.print("Choice\t\tAction\n" +

"------\t\t------\n" +

"C\t\tSpecify Problem Parameters\n" +

"Q\t\tQuit\n" +

"?\t\tDisplay Help\n\n");

Anda mungkin juga menyukai