for loop with multiple inputs not stopping - java

I am having some trouble with a for loop that doesn't appear to be stopping. When i call outPutGenerator the first time with only one item in the custom list it works perfectly. When i run it again with 9 items it just keeps running. Could you please point me in the right direction?
edit: I can get the test to run the second time, but nothing after that.
input:
1
5
3
3 2 4
1 5 2
3 6 4
1
6
2
5 6
6 7
Code:
public static void outputGenerator (CustomList [] list, PrintWriter printWriter) {
int size2;
int valueToPrint;
CustomList listToBuild;
int length;
length = list.length;
System.out.println("len: " + length);
//print out the results to a .txt file
try {
printWriter.println("Matrix read: ");
printWriter.println();
printWriter.println("------------------" +
"---------------------");
printWriter.println();
printWriter.flush();
for (int x = 0; x < length; x++){
System.out.println("test");
listToBuild = list[x];
size2 = listToBuild.sizeOfList();
System.out.println("size2 " + size2);
for (int y = 0; y < size2; y++) {
System.out.println("y: " + y);
valueToPrint = listToBuild.ValueOfNode(y);
printWriter.println(valueToPrint);
System.out.println("val" + valueToPrint);
printWriter.flush();
}
printWriter.println();
}
return;
}catch (Exception e) {
e.printStackTrace();
}
}
Custom Linked List Code:
public class CustomList {
private Node firstNode;
private Node end;
private Node header;
private int sizeOfMatrix;
private int sizeOfList;
//constructor to set all to blank
public CustomList() {
firstNode = null;
end = null;
header = null;
sizeOfMatrix = 0;
sizeOfList = 0;
}
public void addToList(int dataToSave) {
Node node = new Node (dataToSave);
if (firstNode == null) {
firstNode = node;
firstNode.next = end;
firstNode.before = header;
}
else if (end == null) {
end = node;
end.before = firstNode;
firstNode.next = end;
}
else
end.next = node;
node.before = end;
end = node;
sizeOfMatrix++;
}
public void setHeader (int dataToUse){
Node headerNode = new Node(dataToUse);
header = headerNode;
header.next = firstNode;
}
public void print() {
Node zNode = firstNode;
System.out.println("Test");
if(firstNode == null){
System.out.print("EMPTY");
return;
}
while (zNode != null) {
System.out.println(zNode);
zNode = zNode.next;
}
}
public int sizeOfList() {
Node zNode = firstNode;
sizeOfList = 0;
while( zNode != null) {
zNode = firstNode.next;
sizeOfList++;
}
return sizeOfList;
}
public int ValueOfNode( int column ) {
int counter = 0;
Node zNode = firstNode;
while (zNode != null) {
if (column == counter){
return zNode.numInMatrix();
}
else
zNode = firstNode.next;
counter++;
}
return -1;
}

When you are doing
size2 = listToBuild.sizeOfList();
sizeOfList() will always return the same value for each call.
I guess, you are not changing value of firstNode. Moreover, there are some changes I have made in your function.
public int sizeOfList() {
Node zNode = firstNode;
sizeOfList = 0;
while( zNode != null) {
zNode = zNode.next;
sizeOfList++;
}
return sizeOfList;
}

Related

Linked list, count even and uneven positions, unsing recursion

I want to create two methods, "private int sumEven (Node node){}" for suming up even positions in a linked list and "sumOdd (Node node) {}" for suming up odd positions. I want to use recursion.
This is how far i've come, but i dont know what should I do next.
Does any one have a tipp or a hint for me, what should i do next?
public class RecursiveListTest {
static Node head;
static boolean found = false;
static int counter = 0;
public static void main(String[] args) {
RecursiveListTest list = new RecursiveListTest();
list.addNumber(3);
list.addNumber(5);
list.addNumber(2);
list.addNumber(7);
list.addNumber(5);
list.addNumber(1);
list.addNumber(4);
list.printList();
int sumEven = list.sumEven(head);
int sumOdd = list.sumOdd(head);
System.out.println();
System.out.println("Sum of even Positions: " + sumEven);
System.out.println();
System.out.println("Sum of odd Positions: " + sumOdd);
System.out.println();
}
// Node
private class Node {
Node next;
int value;
Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
private int sumEven(Node n) {
int sumEven = 0;
int sumOdd = 0;
counter = counter + 1;
if (counter % 2 == 0) {
sumEven = sumEven + n.value;
if (n.next.next != null) {
sumEven = sumEven + sumEven(n.next.next);
}
}
else if (counter % 2 == 1) {
if (n.next != null) {
sumEven = sumEven + sumEven(n.next);
}
}
return sumEven;
}
private int sumOdd(Node n) {
return 0;
}
private void addNumber(int number) {
Node curr = head;
Node prev = null;
if (head == null) {
head = new Node(number, null);
} else {
while (curr != null) {
prev = curr;
curr = curr.next;
}
Node newNode = new Node(number, null);
prev.next = newNode;
}
}
private void printList() {
Node curr = head;
Node prev = null;
while (curr != null) {
System.out.print(curr.value + " ");
prev = curr;
curr = curr.next;
}
}
}
You should consider using variables private static int evenSum, oddSum and your methods could be:
private int sumEven() {
evenSum = 0;
sumEvenHelper(head);
return evenSum;
}
private int sumOdd() {
oddSum = 0;
sumEvenHelper(head);
return oddSum;
}
private void sumEvenHelper(Node n) {
if(n != null) {
evenSum += n.value;
sumOddHelper(n.next);
}
}
private void sumOddHelper(Node n) {
if(n != null) {
oddSum += n.value;
sumEvenHelper(n.next);
}
}
My code assumes head is list element 0. Otherwise you will call sumOddHelper(head) inside the sumEven and sumOdd methods.

Huffman tree and order of nodes in terms of occurrence

I'm trying to implement an algorithm for Huffman coding, I have a very simple code at the moment that works fine. In my code, the weight of the character is based on the frequency of occurrence of that character, however I would like to improve it so that it meets the following criteria:
I would like my code to consider the order in which a node is encountered. For example if ’e’ and ’ ’ have the same frequency, but ’e’ occurs first, its weight would be considered greater. I have been trying to implement this for my code but it seems to give me mixed results.
Here is what I have. Any input on how to go about this would be greatly appreciated. I apologize in advance if this is too simple, but I'm a student and still learning.
import java.util.ArrayList;
public class Huffman {
static Node node;
static Node newRoot;
static String codedString = "";
public static void main(String[] args) {
String message = "'twas brillig, and the slithy toves did gyre and gimble in the wabe: all mimsy were the borogoves, and the mome raths outgrabe. "
+ "\"beware the jabberwock, my son! the jaws that bite, the claws that catch! beware the jubjub bird, and shun the frumious bandersnatch!\" "
+ "he took his vorpal sword in hand: long time the manxome foe he sought -- so rested he by the tumtum tree, and stood awhile in thought. "
+ "and, as in uffish thought he stood, the jabberwock, with eyes of flame, came whiffling through the tulgey wood, and burbled as it came! "
+ "one, two! one, two! and through and through the vorpal blade went snicker-snack! he left it dead, and with its head he went galumphing back. "
+ "\"and, has thou slain the jabberwock? come to my arms, my beamish boy! o frabjous day! callooh! callay!\" "
+ " he chortled in his joy. 'twas brillig, and the slithy toves did gyre and gimble in the wabe; "
+ " all mimsy were the borogoves, and the mome raths outgrabe.";
// Convert the string to char array
char[] msgChar = message.toCharArray();
ArrayList<Character> characters = new ArrayList<Character>();
/*
* Get a List of all the chars which are present in the string No
* repeating the characters!
*/
for (int i = 0; i < msgChar.length; i++) {
if (!(characters.contains(msgChar[i]))) {
characters.add(msgChar[i]);
}
}
/* Print out the available characters */
// System.out.println(characters);
/* Count the number of occurrences of Characters */
int[] countOfChar = new int[characters.size()];
/* Fill The Array Of Counts with one as base value */
for (int x = 0; x < countOfChar.length; x++) {
countOfChar[x] = 0;
}
/* Do Actual Counting! */
for (int i = 0; i < characters.size(); i++) {
char checker = characters.get(i);
for (int x = 0; x < msgChar.length; x++) {
if (checker == msgChar[x]) {
countOfChar[i]++;
}
}
}
/* Sort the arrays is descending order */
for (int i = 0; i < countOfChar.length - 1; i++) {
for (int j = 0; j < countOfChar.length - 1; j++) {
if (countOfChar[j] < countOfChar[j + 1]) {
int temp = countOfChar[j];
countOfChar[j] = countOfChar[j + 1];
countOfChar[j + 1] = temp;
char tempChar = characters.get(j);
characters.set(j, characters.get(j + 1));
characters.set(j + 1, tempChar);
}
}
}
/* Print Out The Frequencies of the Characters */
for (int x = 0; x < countOfChar.length; x++) {
System.out.println(characters.get(x) + " - " + countOfChar[x]);
}
/* Form the Tree! */
/* Form Leaf Nodes and Arrange them in a linked list */
Node root = null;
Node current = null;
Node end = null;
for (int i = 0; i < countOfChar.length; i++) {
Node node = new Node(characters.get(i).toString(), countOfChar[i]);
if (root == null) {
root = node;
end = node;
} else {
current = root;
while (current.linker != null) {
current = current.linker;
}
current.linker = node;
current.linker.linkerBack = current;
end = node;
}
}
// Recursively add and make nodes!
TreeMaker(root, end);
// inOrder(root);
System.out.println();
inOrder(node);
// preOrder(root);
System.out.println();
preOrder(node);
// Calculate the ends and the meets!
char[] messageArray = message.toCharArray();
char checker;
for (int i = 0; i < messageArray.length; i++) {
current = node;
checker = messageArray[i];
String code = "";
while (true) {
if (current.left.value.toCharArray()[0] == checker) {
code += "0";
break;
} else {
code += "1";
if (current.right != null) {
if (current.right.value.toCharArray()[0] == characters
.get(countOfChar.length - 1)) {
break;
}
current = current.right;
} else {
break;
}
}
}
codedString += code;
}
System.out.println();
System.out.println("The coded string is " + codedString);
}
public static void preOrder(Node root) {
if (root != null) {
System.out.print(root.value + "->");
preOrder(root.left);
preOrder(root.right);
}
}
public static void inOrder(Node root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.value + "->");
inOrder(root.right);
}
}
public static void TreeMaker(Node root, Node end) {
node = new Node(end.linkerBack.value + end.value, end.linkerBack.count
+ end.count);
node.left = end.linkerBack;
node.right = end;
end.linkerBack.linkerBack.linker = node;
node.linkerBack = end.linkerBack.linkerBack;
end = node;
end.linker = null;
Node current = root;
while (current.linker != null) {
System.out.print(current.value + "->");
current = current.linker;
}
System.out.println(current.value);
if (root.linker == end) {
node = new Node(root.value + end.value, root.count + end.count);
node.left = root;
node.right = end;
node.linker = null;
node.linkerBack = null;
System.out.println(node.value);
newRoot = node;
} else {
TreeMaker(root, end);
}
}
}
class Node {
String value;
int count;
Node left;
Node right;
Node linker;
Node linkerBack;
Node(String value, int count) {
this.value = value;
this.count = count;
this.left = null;
this.right = null;
this.linker = null;
this.linkerBack = null;
}
}

Adding Number Represented by Linked List

I'm stuck on this problem:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
The problem is that my result is 8 8 while the result should be 8 0 8.
I printed out the sum and it is 8 10 8 so it should work.
Any ideas?
Here is my code:
public Node addNumbers(Node number1, Node number2) {
if(number1 == null && number2 == null)
return null;
Node sumOf = null;
int sum = 0;
int carry = 0;
while(number1 != null && number2 != null) {
sum = number1.data + number2.data + carry;
System.out.println(sum);
// update carry for next operation
if(sum > 9)
carry = 1;
else
carry = 0;
if(sum > 9) {
if(sumOf == null) {
sumOf = new Node(sum % 10);
} else {
sumOf.next = new Node(sum % 10);
}
} else {
if(sumOf == null) {
sumOf = new Node(sum);
} else {
sumOf.next = new Node(sum);
}
}
number1 = number1.next;
number2 = number2.next;
}
return sumOf;
}
public void toString(Node node) {
System.out.println();
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
AddTwoNumbers add = new AddTwoNumbers();
number1 = new Node(3);
number1.next = new Node(1);
number1.next.next = new Node(5);
number2 = new Node(5);
number2.next = new Node(9);
number2.next.next = new Node(2);
System.out.println("numbers: ");
add.toString(number1);
add.toString(number2);
System.out.println();
System.out.println("after adding: ");
add.toString(add.addNumbers(number1, number2));
}
}
You only ever set sumOf (if it is null) and sumOf.next (if sumOf is not null). Your resulting list therefore never has more than two elements. You need to track the current tail of your list and append there, instead of always appending to sumOf.
Additionally, you need to handle the cases where one input number has more digits than the other, and where you have non-zero carry after exhausting all the input digits. You do not presently handle either.
Here is the solution, do note that i carry forward when the sum of two integers is greater than 9 else i continue with the sum of next integers from both the list.
class Node {
private Object data;
private Node next;
public Object getData() { return data; }
public void setData(Object data) { this.data = data; }
public Node getNext() { return next; }
public void setNext(Node next) { this.next = next; }
public Node(final Object data, final Node next) {
this.data = data;
this.next = next;
}
#Override
public String toString() { return "Node:[Data=" + data + "]"; }
}
class SinglyLinkedList {
Node start;
public SinglyLinkedList() { start = null; }
public void addFront(final Object data) {
// create a reference to the start node with new data
Node node = new Node(data, start);
// assign our start to a new node
start = node;
}
public void addRear(final Object data) {
Node node = new Node(data, null);
Node current = start;
if (current != null) {
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(node);
} else {
addFront(data);
}
}
public void deleteNode(final Object data) {
Node previous = start;
if (previous == null) {
return;
}
Node current = previous.getNext();
if (previous != null && previous.getData().equals(data)) {
start = previous.getNext();
previous = current;
current = previous.getNext();
return;
}
while (current != null) {
if (current.getData().equals(data)) {
previous.setNext(current.getNext());
current = previous.getNext();
} else {
previous = previous.getNext();
current = previous.getNext();
}
}
}
public Object getFront() {
if (start != null) {
return start.getData();
} else {
return null;
}
}
public void print() {
Node current = start;
if (current == null) {
System.out.println("SingleLinkedList is Empty");
}
while (current != null) {
System.out.print(current);
current = current.getNext();
if (current != null) {
System.out.print(", ");
}
}
}
public int size() {
int size = 0;
Node current = start;
while (current != null) {
current = current.getNext();
size++;
}
return size;
}
public Node getStart() {
return this.start;
}
public Node getRear() {
Node current = start;
Node previous = current;
while (current != null) {
previous = current;
current = current.getNext();
}
return previous;
}
}
public class AddNumbersInSinglyLinkedList {
public static void main(String[] args) {
SinglyLinkedList listOne = new SinglyLinkedList();
SinglyLinkedList listTwo = new SinglyLinkedList();
listOne.addFront(5);
listOne.addFront(1);
listOne.addFront(3);
listOne.print();
System.out.println();
listTwo.addFront(2);
listTwo.addFront(9);
listTwo.addFront(5);
listTwo.print();
SinglyLinkedList listThree = add(listOne, listTwo);
System.out.println();
listThree.print();
}
private static SinglyLinkedList add(SinglyLinkedList listOne, SinglyLinkedList listTwo) {
SinglyLinkedList result = new SinglyLinkedList();
Node startOne = listOne.getStart();
Node startTwo = listTwo.getStart();
int carry = 0;
while (startOne != null || startTwo != null) {
int one = 0;
int two = 0;
if (startOne != null) {
one = (Integer) startOne.getData();
startOne = startOne.getNext();
}
if (startTwo != null) {
two = (Integer) startTwo.getData();
startTwo = startTwo.getNext();
}
int sum = carry + one + two;
carry = 0;
if (sum > 9) {
carry = sum / 10;
result.addRear(sum % 10);
} else {
result.addRear(sum);
}
}
return result;
}
}
Sample Run
Node:[Data=3], Node:[Data=1], Node:[Data=5]
Node:[Data=5], Node:[Data=9], Node:[Data=2]
Node:[Data=8], Node:[Data=0], Node:[Data=8]
**#In Python:-**
class Node():
def __init__(self,value):
self.value=value
self.nextnode=None
class LinkedList():
def __init__(self):
self.head=None
def add_element(self,value):
node=Node(value)
if self.head is None:
self.head =node
return
crnt_node=self.head
while crnt_node.nextnode is not None:
crnt_node=crnt_node.nextnode
crnt_node.nextnode=node
def reverse_llist(self):
crnt_node=self.head
if crnt_node == None:
print('Empty Linkned List')
return
old_node = None
while crnt_node:
temp_node = crnt_node.nextnode
crnt_node.nextnode = old_node
old_node = crnt_node
crnt_node = temp_node
self.head = old_node
def converted_llist(self):
crnt_node=self.head
carry_value=0
while True:
#print(crnt_node.value)
if (crnt_node.value+1)%10==0:
carry_value=1
crnt_node.value=0
print(crnt_node.value,end='->')
else:
print(crnt_node.value+carry_value,end='->')
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
def print_llist(self):
crnt_node=self.head
while True:
print(crnt_node.value,end='->')
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
list_convert=LinkedList()
list_convert.add_element(1)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.add_element(9)
list_convert.print_llist()
list_convert.reverse_llist()
list_convert.print_llist()
list_convert.converted_llist()

LinkedList NullPointerException?

Hey I can't seem to get my code to work, there is something wrong with the constructor and I just can't figure out what it is.
I had it working for the constructor and tried it for some of the methods but even then it still gave me NullPointerException
import java.util.NoSuchElementException;
public class LinkedString
{
//Required Nodes/counters to track positions in LinkedList
private Node start;
private Node end;
private int counter;
private int i = 0;
//Inner class Node provides the node object required to create links
private class Node
{
public char data;
public Node next;
}
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}
//This accessor returns a value at the specified index
//The 1st character has an index of 0 and will throw
//a no such element exception if there is no char # given index
public char charAt(int index)
{
Node current = start;
boolean found = false;
char temp = 0;
int i = 0;
while (current.next != null && i <= index)
{
current = current.next;
if(i == index)
{
found = true;
//Return done, and Data is wrong Edit.
}
i++;
temp = current.data;
}
if(found == false) {
throw new NoSuchElementException();
}
return temp;
}
//concat connects two linkedString objects together and updates the
//counter for how many chars are in the combined list
public LinkedString concat(LinkedString value)
{
end.next = value.start;
end = value.end;
counter = counter + value.length();
return value;
}
//isEmpty checks to see if the list has a initial value
//if it doesnt its empty and returns true
public boolean isEmpty()
{
if(start == null)
{
return true;
}
else
{
return false;
}
}
//length() returns the counter variable which counts the number of
// characters in the linked string
public int length()
{
return counter;
}
//substring returns a copy of the linked string from a specified point
//to another, if the user attempts to copy a value from a not existing
//index point it throws NoSuchElementException
public Node substring(int startIndex, int endIndex)
{
Node current = start;
Node sIndex;
Node eIndex;
Node copy = null;
int i = 0;
while(current.next != null && i <= startIndex)
{
current = current.next;
if(i == startIndex)
{
sIndex = current;
sIndex.next = copy;
while(current.next != null && i <= endIndex)
{
current = current.next;
copy.next = current;
copy = current;
if(i == endIndex)
{
eIndex = current;
eIndex.next = null;
copy.next = eIndex;
}
i++;
}
if(i < endIndex)
throw new NoSuchElementException();
}
i++;
}
return copy;
}
}
public class LinkedStringMain {
public static void main(String[] args) {
LinkedString linked = new LinkedString("stack");
System.out.println(" " + linked.charAt(0));
System.out.println(" " + linked.isEmpty());
}
}
The error is that start is not being initialized in your either of your constructors after you check if it is null. To fix this, initialize start using start = new Node();. The changes are implemented below:
//This constructor allows the user to input a array of characters
//and have them created into a LinkedString object
public LinkedString(char[] value)
{
start.data = value[0];
counter = 0;
for(int i = 0 ; i < value.length ; i++)
{
if ( start == null)
{
start = new Node(); //initialize start
start.data = value[i];
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data = value[i];
end.next = newNode;
newNode.next = null;
end = newNode;
counter++;
}
}
}
//This constructor allows the user to input a String
//getting each character and creating it into a LinkedString object
public LinkedString(String value)
{
counter=0;
for(int i = 0; i < value.length(); i++)
{
if(start == null)
{
start = new Node(); //initialize start
start.data = value.charAt(i);
start.next = end;
counter++;
}
else
{
Node newNode = new Node();
newNode.data=value.charAt(i);
end.next = newNode;
newNode.next = null;
end = newNode;
}
}
}

Arrival time cannot be sorted correctly in Java

Greeting to everyone. I currently work on a program that sorting the emergency number of patients(the number that assigned by nurse when they enter the emergency room and this number determines the seriousness of their sickness too). However, if there are more than 1 patient who hold the same emergency numbers(eg: 2 patients hold emergency number 1), the one who came earlier should receive the treatment first. For this reason, I have 2 sortings, one is to sort the emergency number in ascending order and the other is to sort the time in ascending order too. But unfortunately the second sorting cannot work correctly.The following are the explanations for the type of emergency numbers:
Emergency number : 1 – Immediately life threatening
Emergency number : 2 – Urgent, but not immediately life threatening
Emergency number : 3 – Less urgent
So,now comes the coding part(Please note that this is a linkedlist)
Interface:
public interface ListInterface<T> {
public boolean add(T newEntry);
public boolean add(int newPosition, T newEntry);
public T remove(int givenPosition);
public void clear();
public boolean replace(int givenPosition, T newEntry);
public T getEntry(int givenPosition);
public boolean contains(T anEntry);
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
LList class:
/**
* LList.java
* A class that implements the ADT list by using a chain of nodes,
* with the node implemented as an inner class.
*/
public class LList<T> implements ListInterface<T> {
private Node firstNode; // reference to first node
private int length; // number of entries in list
public LList() {
clear();
}
public final void clear() {
firstNode = null;
length = 0;
}
public boolean add(T newEntry) {
Node newNode = new Node(newEntry); // create the new node
if (isEmpty()) // if empty list
firstNode = newNode;
else { // add to end of nonempty list
Node currentNode = firstNode; // traverse linked list with p pointing to the current node
while (currentNode.next != null) { // while have not reached the last node
currentNode = currentNode.next;
}
currentNode.next = newNode; // make last node reference new node
}
length++;
return true;
}
public boolean add(int newPosition, T newEntry) { // OutOfMemoryError possible
boolean isSuccessful = true;
if ((newPosition >= 1) && (newPosition <= length+1)) {
Node newNode = new Node(newEntry);
if (isEmpty() || (newPosition == 1)) { // case 1: add to beginning of list
newNode.next = firstNode;
firstNode = newNode;
}
else { // case 2: list is not empty and newPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < newPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
newNode.next = nodeBefore.next; // make new node point to current node at newPosition
nodeBefore.next = newNode; // make the node before point to the new node
}
length++;
}
else
isSuccessful = false;
return isSuccessful;
}
public T remove(int givenPosition) {
T result = null; // return value
if ((givenPosition >= 1) && (givenPosition <= length)) {
if (givenPosition == 1) { // case 1: remove first entry
result = firstNode.data; // save entry to be removed
firstNode = firstNode.next;
}
else { // case 2: givenPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < givenPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
result = nodeBefore.next.data; // save entry to be removed
nodeBefore.next = nodeBefore.next.next; // make node before point to node after the
} // one to be deleted (to disconnect node from chain)
length--;
}
return result; // return removed entry, or
// null if operation fails
}
public boolean replace(int givenPosition, T newEntry) {
boolean isSuccessful = true;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
// System.out.println("Trace| currentNode.data = " + currentNode.data + "\t, i = " + i);
currentNode = currentNode.next; // advance currentNode to next node
}
currentNode.data = newEntry; // currentNode is pointing to the node at givenPosition
}
else
isSuccessful = false;
return isSuccessful;
}
public T getEntry(int givenPosition) {
T result = null;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
currentNode = currentNode.next; // advance currentNode to next node
}
result = currentNode.data; // currentNode is pointing to the node at givenPosition
}
return result;
}
public boolean contains(T anEntry) {
boolean found = false;
Node currentNode = firstNode;
while (!found && (currentNode != null)) {
if (anEntry.equals(currentNode.data))
found = true;
else
currentNode = currentNode.next;
}
return found;
}
public int getLength() {
return length;
}
public boolean isEmpty() {
boolean result;
if (length == 0)
result = true;
else
result = false;
return result;
}
public boolean isFull() {
return false;
}
public String toString() {
String outputStr = "";
Node currentNode = firstNode;
while (currentNode != null) {
outputStr += currentNode.data + "\n";
currentNode = currentNode.next;
}
return outputStr;
}
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
this.next = null;
}
private Node(T data, Node next) {
this.data = data;
this.next = next;
}
} // end Node
} // end LList
Patient class:
public class Patient {
private int emergencyNo;
private int queueTime;
private String patientName;
private String patientIC;
private String patientGender;
private String patientTelNo;
private String patientAdd;
private String visitDate;
public Patient() {
}
public Patient(int emergencyNo, int queueTime, String patientName, String patientIC, String patientGender, String patientTelNo, String patientAdd, String visitDate)
{
this.emergencyNo = emergencyNo;
this.queueTime = queueTime;
this.patientName = patientName;
this.patientIC = patientIC;
this.patientGender = patientGender;
this.patientTelNo = patientTelNo;
this.patientAdd = patientAdd;
this.visitDate = visitDate;
}
//set methods
public void setQueueTime(int queueTime)
{
this.queueTime = queueTime;
}
public boolean setEmergencyNo(int emergencyNo)
{
boolean varEmergencyNo = true;
if (emergencyNo != 1 && emergencyNo != 2 && emergencyNo != 3)
{
varEmergencyNo = false;
System.out.println("Emergency number is in invalid format!");
System.out.println("Emergency number is either 1, 2 or 3 only!");
System.out.println("\n");
}
else
{
this.emergencyNo = emergencyNo;
}
return varEmergencyNo;
}
public boolean setPatientName(String patientName)
{
boolean varPatientName = true;
if (patientName.equals("") || patientName.equals(null))
{
varPatientName = false;
System.out.println("The patient name cannot be empty!\n");
}
else
{
this.patientName = patientName;
}
return varPatientName;
}
public boolean setPatientIC(String patientIC)
{
boolean varPatientIC = true;
if(!patientIC.matches("^[0-9]{12}$"))
{
varPatientIC = false;
System.out.println("IC is in invalid format!");
System.out.println("It must consist of 12 numbers only!\n");
}
else
{
this.patientIC = patientIC;
}
return varPatientIC;
}
public boolean setPatientGender(String patientGender)
{
boolean varPatientGender = true;
if(!patientGender.equals("F") && !patientGender.equals("f") && !patientGender.equals("M") && !patientGender.equals("m"))
{
varPatientGender = false;
System.out.println("Gender is in invalid format!");
System.out.println("It must be either 'M' or 'F' only!\n");
}
else
{
this.patientGender = patientGender;
}
return varPatientGender;
}
public boolean setPatientTelNo(String patientTelNo)
{
boolean varPatientTelNo = true;
if((!patientTelNo.matches("^01[02346789]\\d{7}$")) && (!patientTelNo.matches("^03\\d{8}$")))
{
varPatientTelNo = false;
System.out.println("Invalid phone number!");
System.out.println("It must be in the following format : 0167890990 / 0342346789!\n");
System.out.print("\n");
}
else
{
this.patientTelNo = patientTelNo;
}
return varPatientTelNo;
}
public boolean setPatientAdd(String patientAdd)
{
boolean varPatientAdd = true;
if (patientAdd.equals("") || patientAdd.equals(null))
{
varPatientAdd = false;
System.out.println("The patient address cannot be empty!\n");
}
else
{
this.patientAdd = patientAdd;
}
return varPatientAdd;
}
public void setVisitDate(String visitDate)
{
this.visitDate = visitDate;
}
//get methods
public int getQueueTime()
{
return this.queueTime;
}
public int getEmergencyNo()
{
return this.emergencyNo;
}
public String getPatientName()
{
return this.patientName;
}
public String getPatientIC()
{
return this.patientIC;
}
public String getPatientGender()
{
return this.patientGender;
}
public String getPatientTelNo()
{
return this.patientTelNo;
}
public String getPatientAdd()
{
return this.patientAdd;
}
public String getVisitDate()
{
return this.visitDate;
}
#Override
public String toString()
{
return (this.emergencyNo + "\t\t" + this.patientName + "\t\t" + this.patientIC +
"\t\t" + this.patientGender + "\t\t" + this.patientTelNo + "\t\t" + this.patientAdd + "\t\t" + this.visitDate);
}
public String anotherToString()
{
return (this.emergencyNo + "\t\t\t\t\t\t" + this.patientName + "\t\t\t " + this.visitDate);
}
}
EmergencyCmp(Comparator)--->use for sorting the emergency numbers of the patients
import java.util.Comparator;
public class EmergencyCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
return 1;
}
else
{
return -1;
}
}
}
QueueCmp(Comparator)--->use for sorting the arrival time of the patients
import java.util.Comparator;
public class QueueCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
}
Main function:
import java.util.Calendar;
import java.util.Scanner;
import java.util.Arrays;
import java.util.*;
public class DSA {
public DSA() {
}
public static void main(String[] args) {
//patient's attributes
int emergencyNo;
int queueTime;
String patientName;
String patientIC;
String patientGender;
String patientTelNo;
String patientAdd;
String visitDate;
//counter
int j = 0;
int x = 0;
int y = 0;
int z = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int countEnteredPatient = 1;
int totalCount = 0;
//calendar
int nowYr, nowMn, nowDy, nowHr, nowMt, nowSc;
//others
boolean enterNewPatient = true;
String continueInput;
boolean enterNewPatient1 = true;
String continueInput1;
boolean continueEmergencyNo;
Scanner scan = new Scanner(System.in);
ListInterface<Patient> patientList = new LList<Patient>();
ListInterface<Patient> newPatientList = new LList<Patient>();
Patient[] patientArr1 = new Patient[10000];
Patient[] patientArr2 = new Patient[10000];
Patient[] patientArr3 = new Patient[10000];
Patient tempoPatient;
do{
//do-while loop for entering new patient details after viewing patient list
System.out.println("Welcome to Hospital Ten Stars!\n");
do{
//do-while loop for entering new patient details
System.out.println("Entering details of patient " + countEnteredPatient);
System.out.println("===================================\n");
Calendar calendar = Calendar.getInstance();
nowYr = calendar.get(Calendar.YEAR);
nowMn = calendar.get(Calendar.MONTH);
nowDy = calendar.get(Calendar.DAY_OF_MONTH);
nowHr = calendar.get(Calendar.HOUR);
nowMt = calendar.get(Calendar.MINUTE);
nowSc = calendar.get(Calendar.SECOND);
queueTime = calendar.get(Calendar.MILLISECOND);
visitDate = nowDy + "/" + nowMn + "/" + nowYr + ", " + nowHr + ":" + nowMt + ":" + nowSc;
//input emergency number
do{
tempoPatient = new Patient();
continueEmergencyNo = false;
int EmergencyNoOption;
try
{
do{
System.out.print("Please select 1 – Immediately life threatening, 2 – Urgent, but not immediately life threatening or 3 – Less urgent(Eg: 1) : ");
EmergencyNoOption = scan.nextInt();
scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setEmergencyNo(EmergencyNoOption) == false);
}
catch(InputMismatchException ex)
{
System.out.print("\n");
System.out.println("Invalid input detected.");
scan.nextLine();
System.out.print("\n");
continueEmergencyNo = true;
}
}while(continueEmergencyNo);
//input patient name
do{
System.out.print("Patient name(Eg: Christine Redfield) : ");
patientName = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientName(patientName) == false);
//input patient ic no
do{
System.out.print("Patient IC number(Eg: 931231124567) : ");
patientIC = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientIC(patientIC) == false);
//input patient gender
do{
System.out.print("Patient gender(Eg: M) : ");
patientGender = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientGender(patientGender) == false);
//input patient tel. no
do{
System.out.print("Patient tel.No(without'-')(Eg: 0162345678/0342980123) : ");
patientTelNo = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientTelNo(patientTelNo) == false);
//input patient address
do{
System.out.print("Patient address(Eg: 4-C9 Jln Besar 123, Taman Besar, 56000 Kuala Lumpur) : ");
patientAdd = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientAdd(patientAdd) == false);
tempoPatient.setQueueTime(queueTime);
tempoPatient.setVisitDate(visitDate);
patientList.add(tempoPatient);
//decide whether want to enter a new patient or not
do{
System.out.print("Do you want to enter another new patient?(Eg: Y/N) : ");
continueInput = scan.nextLine();
if(continueInput.equals("Y") || continueInput.equals("y"))
{
enterNewPatient = true;
System.out.print("\n");
}
else if(continueInput.equals("N") || continueInput.equals("n"))
{
enterNewPatient = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput.equals("Y") && !continueInput.equals("y") && !continueInput.equals("N") && !continueInput.equals("n"));
countEnteredPatient++;
}while(enterNewPatient); //end do-while loop for entering new patient details
System.out.println("\nWaiting list of patient will be displayed soon.\n");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
System.out.println("Waiting list of patients");
System.out.println("========================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= patientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + patientList.getEntry(i).anotherToString());
}
do{
System.out.print("\nSo, now do you want to enter another new patient?(Eg: Y/N) : ");
continueInput1 = scan.nextLine();
if(continueInput1.equals("Y") || continueInput1.equals("y"))
{
enterNewPatient1 = true;
System.out.print("\n");
}
else if(continueInput1.equals("N") || continueInput1.equals("n"))
{
enterNewPatient1 = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput1.equals("Y") && !continueInput1.equals("y") && !continueInput1.equals("N") && !continueInput1.equals("n"));
}while(enterNewPatient1);//end do-while loop for entering new patient details after viewing patient list
System.out.println("\nNow rearranging the list based on the seriouness and their arrival time.");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
//create an unsorted array
Patient[] tempoPatientArr = new Patient[patientList.getLength()];
//copy the contents of patientList into tempoPatientArr
for(int i = 1; i <= patientList.getLength(); i++ )
{
tempoPatientArr[i-1] = patientList.getEntry(i);
}
//sort tempoPatientArr
Arrays.sort(tempoPatientArr, new EmergencyCmp());
//the above part until this comment line does not have problem
//check the emergency no and then categorise accordingly
for(int i = 0; i < tempoPatientArr.length; i++)
{
if(tempoPatientArr[i].getEmergencyNo() == 1)
{
patientArr1[x] = tempoPatientArr[i];
x++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 2)
{
patientArr2[y] = tempoPatientArr[i];
y++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 3)
{
patientArr3[z] = tempoPatientArr[i];
z++;
}
}
//to check how many !null elements by using count for 3 sub-arrays
for(int i = 0; i < patientArr1.length; i++)
{
if(patientArr1[i] != null)
{
count1++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr2.length; i++)
{
if(patientArr2[i] != null)
{
count2++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr3.length; i++)
{
if(patientArr3[i] != null)
{
count3++;
}
else
{
break;
}
}
//new array with elimination of null values
Patient[] newPatientArr1 = new Patient[count1];
Patient[] newPatientArr2 = new Patient[count2];
Patient[] newPatientArr3 = new Patient[count3];
//copy the contents of old sub arrays(the arrays with null values) into the new sub arrays(without null values)
for(int i = 0; i < newPatientArr1.length; i++)
{
newPatientArr1[i] = patientArr1[i];
}
for(int i = 0; i < newPatientArr2.length; i++)
{
newPatientArr2[i] = patientArr2[i];
}
for(int i = 0; i < newPatientArr3.length; i++)
{
newPatientArr3[i] = patientArr3[i];
}
totalCount = count1 + count2 + count3;
//array that used to combine all the sub-arrays
Patient[] newPatientArr = new Patient[totalCount];
//sort all sub new arrays
Arrays.sort(newPatientArr1, new QueueCmp());
Arrays.sort(newPatientArr2, new QueueCmp());
Arrays.sort(newPatientArr3, new QueueCmp());
//combine the contents of sub new arrays into the newPatientArr array
do{
for (int i = 0; i < count1; i++)
{
newPatientArr[j] = newPatientArr1[i];
j++;
}
for (int b = 0; b < count2; b++)
{
newPatientArr[j] = newPatientArr2[b];
j++;
}
for (int c = 0; c < count3; c++)
{
newPatientArr[j] = newPatientArr3[c];
j++;
}
}while(j < totalCount);
//relink the nodes
for(int i = 0; i < newPatientArr.length; i++)
{
newPatientList.add(newPatientArr[i]);
}
System.out.println("\nSorted waiting list of patients");
System.out.println("===============================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= newPatientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + newPatientList.getEntry(i).anotherToString());
}
}
}
Interface and LList class definitely do not have problems. So everyone can skip the 2 parts.
For the main function, I have a comment like this:
//the above part until this comment line does not have problem
When you all see the comment, that means the previous code does not have problem and you all may skip it and below is an attachment of the result that I got earlier:
So, from the picture you all can see that the sorting of arrival time is not correct. I hope that I can know why does this problem occurs since I cannot figure it out by myself. Thanks to all of you first.
So, after taking the advice of #Scott Hunter, I have made the following modification to the EmergencyCmp:
#Override
public int compare(Patient p1, Patient p2)
{
int value = 0;
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
value = 1;
}
else if(p1.getEmergencyNo() < p2.getEmergencyNo())
{
value = -1;
}
else if(p1.getEmergencyNo() == p2.getEmergencyNo())
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
return value;
}
However, the time sorting still produce a wrong result.
As I understand it (which I may not; you provided a LOT of extraneous stuff), it looks like you are trying to perform 2 distinct sorts, one after the other, such that the second is undoing the work of the first. Instead, you should define a single Comparator which compares emergency numbers and, only if they are the same, compares arrival times.

Categories