SLL sort by int - java

I have this singly linked list where each node holds a name and a weight. I'm trying to write a method that will spit out the list by weight(least to greatest).
Here is the method of the SLL class:
public void printWeights() {
int weightCache;
String nameCache;
index=this.head;
for (int j = 0; j < count; j++) {
for (int i =0; i<count-j;i++) {
indexCheck = index.next;
if (index.next==null||indexCheck==null){
index=index.next;
indexCheck = index.next;
break;
}
if (index.weight>indexCheck.weight) {
weightCache = index.weight; nameCache = index.name;
index.weight=indexCheck.weight; index.name=indexCheck.name;
indexCheck.weight= index.weight; indexCheck.name= index.name;
indexCheck.weight = weightCache;indexCheck.name = nameCache;
indexCheck=indexCheck.next;
}
}
}
if (head == null) {
System.out.println("List is Empty!");
}
for (int i = 1; i <= count; i++) {
if (i < count) {
System.out.print(this.head.name + " - " + this.head.weight + ", ");
head = head.next;
} else {
System.out.print(this.head.name + " - " + this.head.weight + ". \nDone.");
}
}
}

Related

How to add elements into array from a queue?

Im trying to create a waiting list which will hold names of customers in a static array when the main array is full.and When the main array gets an EMPTY slot the first customer in the waiting list array will fill up the EMPTY slot of main array and the added element will be removed Im trying to create this in a circular queue implementation. but I cannot get it to add the other queue elements when main array gets empty
import java.util.Scanner;
public class CQueue {
int SIZE = 4;
int front, rear;
int items[] = new int[4];
void initialize (String[]task) {
for (int i = 0; i < task.length; i++) {
task[i] = "FULL";
}
}
CQueue() {
front = -1;
rear = -1;
}
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
if (front == rear + 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (front == -1)
front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
return (element);
}
}
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
System.out.println("Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE)
System.out.print(items[i] + " ");
System.out.println(items[i]);
System.out.println("Rear -> " + rear);
}
}
void deleteArr(String task[]) {
CQueue q = new CQueue();
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
int element = items[front];
task[NUM]=Integer.toString(element);
q.deQueue();
q.display();
}
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue();
q.initialize(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
while (true) {
q.deleteArr(task);
for (int j = 0; j < task.length; j++) {
System.out.println(task[j]);
}
}
}

Deque with circular array implementation

This is programming exercise from Lafore's Data Structures & Algorithms book:
So far I have this:
public class DequeLong {
private int maxSize;
private long[] dequeArray;
private int front;
private int rear;
private int nItems;
public DequeLong(int size){
maxSize = size;
dequeArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insertLeft(long j){
if(rear == maxSize - 1)
rear = -1;
dequeArray[++rear] = j;
nItems++;
getDequeArray();
}
public void insertRight(long j){
if(front == maxSize)
front = 0;
dequeArray[front] = j;
front++;
nItems++;
getDequeArray();
}
public long removeLeft(){
long temp = dequeArray[rear];
if(rear == 0)
rear = maxSize - 1;
else{
rear--;
}
nItems--;
getDequeArray();
return temp;
}
public long removeRight(){
long temp = dequeArray[front++];
if(front == maxSize)
front = 0;
nItems--;
getDequeArray();
return temp;
}
public long peekFront(){
return dequeArray[front];
}
public long peekRear(){
return dequeArray[rear];
}
public boolean isFull(){
return nItems == maxSize;
}
public boolean isEmpty(){
return nItems == 0;
}
public int size(){
return nItems;
}
public long get(int i){
return dequeArray[i];
}
public void getDequeArray(){
System.out.print("[");
for(int i = 0; i < nItems; i++){
System.out.print(dequeArray[i] + " ");
}
System.out.print("]");
System.out.println();
}
}
And main class:
public class DequeApp {
public static void main(String[] args) {
DequeLong dl = new DequeLong(5);
//check stack - insertLeft() & removeLeft()
dl.insertLeft(100);
dl.insertLeft(200);
dl.insertLeft(300);
dl.insertLeft(400);
dl.insertLeft(500);
dl.removeLeft();
dl.removeLeft();
dl.insertLeft(600);
dl.insertLeft(700);
System.out.println("");
for(int i = 0; i < dl.size(); i++){
System.out.print(dl.get(i) + " ");
}
System.out.println("");
while(!dl.isEmpty())
System.out.println("removed: " + dl.removeLeft());
System.out.println("*************************");
//check queue - insertLeft() & removeRight()
dl.insertLeft(1_000);
dl.insertLeft(2_000);
dl.insertLeft(3_000);
dl.insertLeft(4_000);
dl.insertLeft(5_000);
dl.removeRight();
dl.removeRight();
dl.insertLeft(6_000);
dl.insertLeft(7_000);
System.out.println("");
for(int i = 0; i < dl.size(); i++){
System.out.print(dl.get(i) + " ");
}
System.out.println("");
while(!dl.isEmpty())
System.out.println("removed: " + dl.removeRight());
System.out.println("*************************");
//insertRight() & removeLeft()
dl.insertRight(10_000);
dl.insertRight(20_000);
dl.insertRight(30_000);
dl.insertRight(40_000);
dl.insertRight(50_000);
dl.removeLeft();
dl.removeLeft();
dl.insertRight(60_000);
dl.insertRight(70_000);
System.out.println("");
for(int i = 0; i < dl.size(); i++){
System.out.print(dl.get(i) + " ");
}
System.out.println("");
while(!dl.isEmpty())
System.out.println("removed: " + dl.removeLeft());
System.out.println("*************************");
//insertRight() & removeRight()
dl.insertRight(100_000);
dl.insertRight(200_000);
dl.insertRight(300_000);
dl.insertRight(400_000);
dl.insertRight(500_000);
dl.removeRight();
dl.removeRight();
dl.insertRight(600_000);
dl.insertRight(700_000);
System.out.println("");
for(int i = 0; i < dl.size(); i++){
System.out.print(dl.get(i) + " ");
}
System.out.println("");
while(!dl.isEmpty())
System.out.println("removed: " + dl.removeRight());
System.out.println("*************************");
}
}
Questions:
1) Right now I am applying all operations on the same object, am I doing it right? or I have to create new object(or add reset method to existing one) in order to apply insertLeft(), insertRight(), removeLeft(), removeRight() combos sequentially?
2) If it's possible to use methods sequentially, does my code returns correct results?

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;
}
}

Queue Simulation JAVA

So I had to write this to simulate queues on two servers running the same operation, to compare if a shop needs to hire a second cashier depending on how efficient the simulation runs. Single queue with single server vs single queue with two servers. I write all my code in main rather than creating additional classes and calling/extending since JAVA is not my strong suite, it takes me a ton of time to come up with this stuff and I write very simple code so it gets really long as you can see. Are there any pointers that you folks can give me based on what you see, to help me streamline this? Within the methods, constructors or classes, groups of lines or code that can be reduced, be more efficient? This works with the desired results though. My apologies if this is not the right way to ask or not the right thing to ask, I will delete it. Thanks in advance.
public class SimulationProject1 {
private static int poissonDistr(double mean) {
Random x = new Random();
double J = Math.exp(-mean);
int i = 0;
double pD = 1.0;
do {
pD = pD * x.nextDouble();
i++;
} while (pD > J);
return i - 1;
}
public class listNode {
int data;
listNode next;
public listNode(int data) {
this.data = data;
this.next = null;
}
}
private final listNode head;
public SimulationProject1() {
this.head = null;
}
public boolean isEmpty() {
return (this.head == null);
}
public int getFirst() {
return head.data;
}
public static class LinkedQueue extends SimulationProject1 {
int size;
int totalTime;
private class Node {
int items;
int waitTime;
int dead;
Node next;
public Node(int items) {
this.items = items;
waitTime = 0;
dead = 0;
size++;
this.next = null;
}
}
private Node head;
public void enqueue(int items) {
if (head == null) {
head = new Node(items);
} else {
Node tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = new Node(items);
}
this.size++;
}
public void dequeue() {
if (this.head == null) {
System.out.println("No customers in line");
} else {
this.head = head.next;
}
this.size--;
}
public void setWaitTime() {
Node temp = head;
while (temp != null) {
temp.waitTime++;
temp = temp.next;
}
}
public void getWaitTime() {
Node temp = head;
if(temp != null){
while (temp != null) {
totalTime = temp.waitTime + totalTime;
System.out.println("Total wait time: " + totalTime);
temp = temp.next;
}
}else{
System.out.println("Noone's waiting..");
}
}
public void setTimeout() {
Node temp = head;
while (temp != null) {
if (temp.waitTime >= 8) {
temp.dead = 1;
this.size--;
} else if (temp.waitTime <= 8) {
temp.waitTime++;
}
temp = temp.next;
}
}
}
public static void oneServer(LinkedQueue line, LinkedQueue cashier) {
int cost = 0;
int profit = 0;
int timedOut = 0;
int inLine = 0;
double mean = 0.2;
int [] customersServiced = new int[50];
int [] customerWaitTime = new int[50];
int [] customersInLine = new int[50];
int [] profitData = new int[50];
int [] costData = new int[50];
for (int i = 0; i < 50; i++) {
cost = cost - 3;
for (int j = 0; j < poissonDistr(mean); j++) {
System.out.println("Customers Arriving");
int items = (int) (Math.random() * 6 + 2);
line.enqueue(items);
}
if (line.head != null && line.head.dead == 1) {
timedOut++;
line.dequeue();
cost = cost - 10;
}
if (cashier.head == null && line.head != null && line.head.dead == 0) {
System.out.println("Line Moving");
cashier.head = line.head;
line.head = line.head.next;
}
if (cashier.head != null && cashier.head.items > 0) {
cashier.head.items--;
} else if (cashier.head != null && cashier.head.items <= 0) {
System.out.println("Available");
profit++;
cashier.head = null;
}
line.setWaitTime();
line.setTimeout();
System.out.println("Number currently in line: " + line.size);
customersInLine[i] = line.size;
line.getWaitTime();
customerWaitTime[i] = line.totalTime;
System.out.println("Customers serviced: " + profit);
customersServiced[i] = profit;
profitData[i] = profit;
costData[i] = cost;
}
while (line.head != null) {
line.head = line.head.next;
inLine++;
}
System.out.println("\n" + "-------------------------Stats-----------------------------" + "\n" + "Cost: " +
cost + "\nPer iteration: " + Arrays.toString(costData) + "\n");
System.out.println("Profit: " + profit + "\nPer iteration: " + Arrays.toString(profitData) + "\n");
System.out.println("In the line: " + inLine + "\nAccrued per iteration: " + Arrays.toString(customersInLine) + "\n");
System.out.println("Timed out: " + timedOut + "\n");
System.out.println("Total wait time: " + line.totalTime + "\nPer iteration: " + Arrays.toString(customerWaitTime) + "\n");
}
public static void twoServer(LinkedQueue line, LinkedQueue cashier, LinkedQueue cashier2) {
int cost = 0;
int profit = 0;
int timedOut = 0;
int inLine = 0;
double mean = 0.2;
int[] customersServiced = new int[50];
int[] customerWaitTime = new int[50];
int[] customersInLine = new int[50];
int[] profitData = new int[50];
int[] costData = new int[50];
for (int i = 0; i < 50; i++) {
cost = cost - 6;
for (int j = 0; j < poissonDistr(mean); j++) {
System.out.println("Customers Arriving");
int items = (int) (Math.random() * 6 + 2);
line.enqueue(items);
}
if (line.head != null && line.head.dead == 1) {
timedOut++;
line.dequeue();
cost = cost - 10;
}
if (cashier.head == null && line.head != null && line.head.dead == 0) {
System.out.println("Line Moving");
cashier.head = line.head;
line.head = line.head.next;
}
if (cashier2.head == null && line.head != null && line.head.dead == 0) {
System.out.println("Line Moving");
cashier2.head = line.head;
line.head = line.head.next;
}
if (cashier.head != null && cashier.head.items > 0) {
cashier.head.items--;
} else if (cashier.head != null && cashier.head.items <= 0) {
System.out.println("Available");
profit++;
cashier.head = null;
}
if (cashier2.head != null && cashier2.head.items > 0) {
cashier2.head.items--;
} else if (cashier2.head != null && cashier2.head.items <= 0) {
System.out.println("Available");
profit++;
cashier2.head = null;
}
line.setWaitTime();
line.setTimeout();
System.out.println("Number currently in line: " + line.size);
customersInLine[i] = line.size;
line.getWaitTime();
customerWaitTime[i] = line.totalTime;
System.out.println("Customers serviced: " + profit);
customersServiced[i] = profit;
profitData[i] = profit;
costData[i] = cost;
}
while (line.head != null) {
line.head = line.head.next;
inLine++;
}
System.out.println("\n" + "-------------------------Stats-----------------------------" + "\n" +
"Cost: " + cost + "\nPer iteration: " + Arrays.toString(costData) + "\n");
System.out.println("Profit: " + profit + "\nPer iteration: " + Arrays.toString(profitData) + "\n");
System.out.println("In the line: " + inLine + "\nAccrued per iteration: " + Arrays.toString(customersInLine) + "\n");
System.out.println("Timed out: " + timedOut + "\n");
System.out.println("Total wait time: " + line.totalTime + "\nPer iteration: " + Arrays.toString(customerWaitTime) + "\n");
}
public static void main(String[] args) {
LinkedQueue line = new LinkedQueue();
LinkedQueue line2 = new LinkedQueue();
LinkedQueue cashier = new LinkedQueue();
LinkedQueue cashier2 = new LinkedQueue();
oneServer(line, cashier);
System.out.println("-------------------------Double Server------------------------------------");
twoServer(line2, cashier, cashier2);
}
}
The output it too large to post, it has stuff like
Numbers in line
Currently Waiting
Currently serviced
Cost
Loss
Profit
etc

toString() With Recursion Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have this really weird issue with my program and the test class provided. The goal is to return a string in the exact format provided. However, when I run the test class, it tells me my string is wrong, even though it is exactly the same as the string in the test class. I am not sure why it is coming up as an incorrect string, even though the string is correct. Thanks!
This is the class:
public class RecursionLinkedList
{
private Node firstNode;
private int numberOfEntries;
public RecursionLinkedList()
{
firstNode = null;
numberOfEntries = 0;
}
public void add(int aData)
{
if(numberOfEntries == 0)
{
firstNode = new Node(aData);
}
else
{
firstNode = new Node(aData, firstNode);
}
numberOfEntries++;
}
/**
* boolean contains(int aData)
*
* See whether this RecursionLinkedList contains aData
* #param aData a data to be located
* #return true if this RecursionLinkedList contains aData,
* or false otherwise.
*/
public boolean contains(int aData)
{
Node currentNode = firstNode;
if(currentNode == null) {
return false;
}
if(currentNode.data == aData) {
return true;
}
else {
return contains1(aData, currentNode);
}
}
/**
* int getFrequencyOf(int aData)
*
* Counts the number of times a given data appears in this
* RecursionLinkedList.
*
* #param aData the data to be counted
* #return the number of times aData appears in this RecursionLinkedList
*/
public int getFrequencyOf(int aData)
{
Node currentNode = firstNode;
int frequency = 0;
if(currentNode == null) {
return frequency;
}
else {
frequency = getFrequencyOf1(aData, currentNode);
return frequency;
}
}
/**
* String toString()
*
* Return a string representation of this RecursionLinkedList. For example,
* if this RecursionLinkedList contains 1, 2, 3, 5, 2 and 3 from the first
* index to the last index, the returned string should be
* "[1,2,3,5,2,3]"
* #return the string representation of this RecursionLinkedList.
*/
public String toString()
{
Node currentNode = firstNode;
String str1 = "[";
String str = toString1(currentNode);
String str2 = "]";
return str1 + str + str2;
}
/**
* int getIndexOf(int aData)
*
* Return the index of the first aData where the first index of
* the first item in this RecursionLinkedList is 0.
*
* #param aData the data to be located
* #return the index of the first aData.
*/
public int getIndexOf(int aData)
{
Node currentNode = firstNode;
int index = 0;
if(currentNode == null) {
return 0;
}
else {
index = getIndexOf1(aData, currentNode);
return index;
}
}
public boolean contains1(int aData, Node node)
{
Node currentNode = node;
if(currentNode == null) {
return false;
}
if(currentNode.data == aData) {
return true;
}
else {
return contains1(aData, currentNode.next);
}
}
public int getFrequencyOf1(int aData, Node node)
{
Node currentNode = node;
int frequency = 0;
if(currentNode == null) {
return frequency;
}
if(currentNode.data == aData) {
frequency = 1 + getFrequencyOf1(aData, currentNode.next);
}
else {
frequency = getFrequencyOf1(aData, currentNode.next);
}
return frequency;
}
public String toString1(Node node)
{
Node currentNode = node;
if(currentNode == null) {
return "\b";
}
else {
int i = currentNode.data;
String str = Integer.toString(i);
String str1 = str + ","+toString1(currentNode.next);
return str1;
}
}
public int getIndexOf1(int aData, Node node)
{
Node currentNode = node;
int index = 0;
if(currentNode == null) {
return 0;
}
if(currentNode.data == aData) {
return index;
}
else {
index = 1 + getIndexOf1(aData, currentNode.next);
return index;
}
}
private class Node
{
private int data;
private Node next;
private Node(int aData, Node nextNode)
{
data = aData;
next = nextNode;
}
private Node(int aData)
{
this(aData, null);
}
}
}
And this is the test class:
import java.util.Random;
public class RecursionLLTester
{
public static void main(String[] args)
{
RecursionLinkedList rll = new RecursionLinkedList();
int point = 0;
boolean isError = false;
System.out.println("Create an empty RecursionLinkedList named rll.");
System.out.print("Test the method contains() on an empty RecursionLinkedList: ");
if(rll.contains(5) != false)
{
System.out.println("FAIL");
System.out.println("Nothing is added into RecursionLinkedList rll.");
System.out.println("rll.contains(5) should return 0.");
System.out.println("But your rll.contains(5) returns " + rll.contains(5) + ".");
}
else
{
System.out.println("PASS");
point++;
}
System.out.print("Test the method getFrequencyOf() on an empty RecursionLinkedList: ");
if(rll.getFrequencyOf(5) != 0)
{
System.out.println("FAIL");
System.out.println("Nothing is added into RecursionLinkedList rll.");
System.out.println("rll.getFrequencyOf(5) should return 0.");
System.out.println("But your rll.getFrequencyOf(5) returns " + rll.getFrequencyOf(5) + ".");
}
else
{
System.out.println("PASS");
point++;
}
Random rand = new Random();
int num = 20;
int[] array = new int[5];
for(int i = 0; i < 5; i++)
{
array[i] = 0;
}
System.out.println("Add the following integer into rll:");
String s = "]";
for(int i = 0; i < num - 1; i++)
{
int temp = rand.nextInt(5);
System.out.print(temp + " ");
s = "," + temp + s;
array[temp]++;
rll.add(temp);
}
int temp = rand.nextInt(5);
System.out.println(temp);
s = "[" + temp + s;
array[temp]++;
rll.add(temp);
System.out.println("\nTest the method contains() on a non-empty RecursionLinkedList");
System.out.print(" - Test rll.contains(-1): ");
if(rll.contains(-1) != false)
{
System.out.println("FAIL");
System.out.println("No -1 has been added into the RecursionLinkedList rll.");
System.out.println("rll.contains(-1) should return 0.");
System.out.println("But your rll.contains(-1) returns " + rll.contains(-1));
}
else
{
System.out.println("PASS");
point++;
}
for(int i = 0; i < 5; i++)
{
System.out.print(" - Test rll.contains(" + i + "): ");
if(rll.contains(i) != (array[i] != 0))
{
System.out.println("FAIL");
System.out.println("There are " + array[i] + " in RecursiveLinkedList rll.");
System.out.println("rll.contains(" + i + ") should return " + (array[i] != 0));
System.out.println("But your rll.contains(" + i + ") returns " + rll.contains(i));
isError = true;
}
else
{
System.out.println("PASS");
}
}
if(!isError)
{
point++;
isError = false;
}
System.out.print(" - Test rll.contains(5): ");
if(rll.contains(5) != false)
{
System.out.println("FAIL");
System.out.println("No 5 has been added into the RecursionLinkedList rll.");
System.out.println("rll.contains(5) should return 0.");
System.out.println("But your rll.contains(5) returns " + rll.contains(5));
}
else
{
System.out.println("PASS");
point++;
}
System.out.println("Test the method getFrequencyOf() on a non-empty RecursionLinkedList");
System.out.print(" - Test rll.getFrequencyOf(-1): ");
if(rll.getFrequencyOf(-1) != 0)
{
System.out.println("FAIL");
System.out.println("No -1 has been added into the RecursionLinkedList rll.");
System.out.println("rll.getFrequencyOf(-1) should return 0.");
System.out.println("But your rll.getFrequencyOf(-1) returns " + rll.getFrequencyOf(-1));
}
else
{
System.out.println("PASS");
point++;
}
for(int i = 0; i < 5; i++)
{
System.out.print(" - Test rll.getFrequencyOf(" + i + "): ");
if(rll.getFrequencyOf(i) != array[i])
{
System.out.println("FAIL");
System.out.println(i + " has been added to the RecursionLinkedList " + array[i] + " times.");
System.out.println("rll.getFrequencyOf(" + i + ") should return " + array[i] + ".");
System.out.println("But your rll.getFrequencyOf(" + i + ") returns " + rll.getFrequencyOf(i));
isError = true;
}
else
{
System.out.println("PASS");
}
}
if(!isError)
{
point++;
isError = false;
}
System.out.print(" - Test rll.getFrequencyOf(5): ");
if(rll.getFrequencyOf(5) != 0)
{
System.out.println("FAIL");
System.out.println("No 5 has been added into the RecursionLinkedList rll.");
System.out.println("rll.getFrequencyOf(5) should return 0.");
System.out.println("But your rll.getFrequencyOf(5) returns " + rll.getFrequencyOf(5));
}
else
{
System.out.println("PASS");
point++;
}
System.out.print("Test the method toString(): ");
if(!s.equals(rll.toString()))
{
System.out.println("FAIL");
System.out.println("rll.toString() should return the string \"" + s + "\".");
System.out.println("But your rll.toString() returns the string \"" + rll.toString() + "\".");
}
else
{
System.out.println("PASS");
point++;
}
System.out.println("Test the method getIndexOf()");
System.out.println("Currently the rll is " + rll + ".");
String[] str = rll.toString().split(",");
str[0] = str[0].substring(1);
str[str.length - 1] = str[str.length - 1].substring(0, 1);
for(int i = -1; i <= 5; i++)
{
System.out.print("Test the method getIndexOf(" + i + "): ");
if(getIndex(str,i) != rll.getIndexOf(i))
{
System.out.println("FAIL");
System.out.println("The index of " + i + " should be " + getIndex(str,i) + ".");
System.out.println("But your rll.getIndexOf(" + i + ") returns " + rll.getIndexOf(i) + ".");
isError = true;
}
else
{
System.out.println("PASS");
}
}
if(!isError)
{
point++;
isError = false;
}
System.out.println("Your current point is " + point + ".");
}
public static int getIndex(String[] str, int s)
{
int result = -1;
for(int i = 0; i < str.length; i++)
{
if(s == Integer.parseInt(str[i]))
{
return i;
}
}
return result;
}
}
The problem is in your toString1(Node) method.
if (currentNode == null) {
return "\b";
}
The \b character is what you're seeing at the end in your test output.
rll.toString() should return the string "[1,1,1,3,4,2,2,1,0,1,2,1,0,4,4,4,2,1,1,2]".
But your rll.toString() returns the string "[1,1,1,3,4,2,2,1,0,1,2,1,0,4,4,4,2,1,1,2,?]".
With a slight adjustment to the method as follows, the test in question passes.
public String toString1(Node node)
{
Node currentNode = node;
if (currentNode == null) {
return "\b";
}
int i = currentNode.data;
String str = Integer.toString(i);
if (currentNode.next != null) {
str = str
+ "," + toString1(currentNode.next);
}
return str;
}
Though I would recommend you change a few things here:
Use a StringBuilder rather than all that thrashing on string concatenation.
Replace recursion with a loop. If your list gets too big you're going to run out of stack space with that recursive method.
I don't think you ever want to return that \b character, as it doesn't represent an integer and your indexOf() method seems to be choking on the concept as well.

Categories