Queue Scenario Help Getting Started - java

Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void print() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Node Class
public class Node<E>{
private E element;
private Node<E> next;
public Node(E element, Node next) {
this.element = element;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node<E> getNextNode() {
return next;
}
public E getElement() {
return element;
}
public String toString() {
return element.toString();
}
}
Simulation Class
import java.util.Random;
public class Simulation {
private int arrivalRate;
//you'll need other instance variables
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
}
public void runSimulation() {
//this is an example for using getRandomNumPeople
//you are going to remove this whole loop.
for (int i = 0; i < 10; i++) {
int numPeople = getRandomNumPeople(arrivalRate);
System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
}
}
//Don't change this method.
private static int getRandomNumPeople(double avg) {
Random r = new Random();
double L = Math.exp(-avg);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
//Don't change the main method.
public static void main(String[] args) {
Simulation s = new Simulation(18, 10);
s.runSimulation();
}
}

It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
// missing the handling of maxNumQueues
}
So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {
private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}

Related

Strange infinite loop in java

//Nevermind, it seems some of the testing code of my university seemed to create an infinite loop when I didnt have all methods that were part of the task implemented...
Hi guys I know this might seem a bit lazy, but the java compiler of my university claims that I have an infinite loop in my Code and I cant find it! Here's the code:
public class List {
private class Node {
private int value;
private Node next;
private Node(int element) {
this.value = element;
next = null;
}
private boolean hasNext(){
return next != null;
}
private void setNext(Node n){
next = n;
}
private Node getNext(){
return next;
}
private int getElement(){
return value;
}
}
private static void flip(Node first, Node second) {
int tmp = first.value;
first.value = second.value;
second.value = tmp;
}
private Node head;
public List() {
head = null;
}
public void add(int e){
if(head == null){
head = new Node(e);
}else{
Node n = head;
while(n.hasNext()){
n = n.getNext();
}
n.setNext(new Node(e));
}
}
#Override
public String toString() {
Node n = head;
String s = "";
while(n != null){
s += n.getElement() + " ";
n = n.getNext();
}
return s;
}
}
I basically need to program a list of integers, which seems easy to me, but already at the part of adding elements I get this error...

How to create some methods(ex: insertAtIndex()) for custom linked list?

I am new to the concept of Linked list, and I am having a lot of trouble building this custom linked list for the first time.
I have two classes: CellPhone and CellList.
In CellPhone, I have 4 attributes: serialNum(long), brand(String), year(int), and price(double).
In CellList, I have:
an inner class called CellNode, which has two attributes: phone(CellPhone), and next(CellNode)
and two attributes head(CellNode) and size(int)
This is from my CellList class:
private CellNode head; // point first node in this list object
private int size; // current size of the list(how many nodes in the list)
public CellList() {
head = null;
size = 0;
}
public CellList(CellList c) { // is this a correct deep copying?
head = new CellNode(c.head);
size = c.getSize();
}
public int getSize() {
return size;
}
public void addToStart(CellPhone c) {
head = new CellNode(c, null); //head.getPhone() = c, head.getNextNode() = null.
size++;
}
I am not even sure if that addToStart method is correctly done, and now I need to add methods like insertAt(/deleteFrom)Index(CellPhone c, int index). I've done till here:
public void insertAtIndex(CellPhone c, int index) { //index is invalid when it's not 0<index<size-1
if(index<0 || index>size-1) {
throw new NoSuchElementException("index is invalid! System terminated.");
}
but I can't fully understand how this Node thing works, so I am stuck.
Here is the full code:
import java.util.NoSuchElementException;
public class CellList {
class CellNode {
private CellPhone phone;
private CellNode next;
public CellNode() {
phone = null;
next = null;
}
public CellNode(CellPhone c, CellNode n) {
phone = c;
next = n;
}
public CellNode(CellNode c) {
this(c.getPhone(), c.getNextNode());
}
public CellNode clone() {
CellNode c = new CellNode(phone, next);
return c;
}
public CellPhone getPhone() {
return phone;
}
public CellNode getNextNode() {
return next;
}
public void setPhone(CellPhone c) {
phone = c;
}
public void setNextNode(CellNode n) {
next = n;
}
}
private CellNode head; // point first node in this list object
private int size; // current size of the list(how many nodes in list)
public CellList() {
head = null;
size = 0;
}
public CellList(CellList c) {
head = new CellNode(c.head);
size = c.getSize();
}
public int getSize() {
return size;
}
public void addToStart(CellPhone c) {
head = new CellNode(c, null); //head.getPhone() = c, head.getNextNode() = null.
size++;
}
public void insertAtIndex(CellPhone c, int index) { //index is invalid when it's not 0<index<size-1
if(index<0 || index>size-1) {
throw new NoSuchElementException("index is invalid! System terminated.");
}
}
public void showContents() {
while(head.getNextNode() != null) {
System.out.println(head.getPhone()+"---->");
head = head.getNextNode();
}
}
}
If you want to insert a node at an index x you have to,
go to the node at index x-1, store the next value of node x-1 in a temp variable, put the node you want to insert in next property of x-1 node, and put the value in the temp variable in the next property of the node you want to insert.

Java linked list how to make a private method to handle searching

I trying and need help on how to create a private method to search a singly linked list.
My private search method is all the way at the bottom, how can I create a private method so i can then use it in an add/delete method?
I have been trying to do this for hours and I can't seem to get it right, i want to make a private search method to avoid loops later on in my other methods such as find add delete
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}
You can create a search method in a single linked list which returns the position of the item or e.g. -1 in case the item was not found.
This search method will need to loop from the first node through its tailing nodes sequentially, extracts the item associated to each node and uses the equals method to try to find a match with the search item.
Here is a possible implementation in Java:
public int search(T item) {
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
Below is a full example of how you can do it in a simple linked list with minimal generics support. Included is also a main method with a minimal unit test to prove the concept:
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}

Java issues instantiating my LinkedList to my array. Data Structures course [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have scoured the internet and cannot find the answer to my question. I am currently in a data structures course, which is important to this question because I need to make EVERYTHING from scratch. I am currently working on homework and the question is this:
Using a USet, implement a Bag. A Bag is like a USet—it supports the add(x), remove(x), and find(x) methods—but it allows duplicate elements to be stored. The find(x) operation in a Bag returns some element (if any) that is equal to x. In addition, a Bag supports the findAll(x) operation that returns a list of all elements in the Bag that are equal to x.
I have done almost all of it and now when I am trying to test my code it throws a null pointer exception right off the bat. I went through the debugger and although I know where it is failing (when trying to create my array list and fill it with linked lists) I just dont know how to fix it. Here is what the error states:
Exception in thread "main" java.lang.NullPointerException
at Bag.<init>(Bag.java:10)
at Bag.main(Bag.java:198)
because I havent even gotten it to start I obviously dont know of any other errors it will encounter, but I will face those when this is fixed. I appreciate any help.
Reminder: I cannot use pre-built java dictionaries, everything needs to be done from the basics.
Here is my entire code:
public class Bag<T> {
final int ARR_SIZE = 128;
LinkedList[] theArray;
public Bag() {
for (int i = 0; i < ARR_SIZE; i++) {
theArray[i] = new LinkedList();
}
}
public boolean add(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
theArray[hashKey].addFirst(element, hashKey);
return true;
}
public T find(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
return theArray[hashKey].findNode(element).getData();
}
public T findAll(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
System.out.print(theArray[hashKey].findAllElements(element));
return element;
}
public T remove(T x) {
T element = x;
int hashKey = element.hashCode() % ARR_SIZE;
return theArray[hashKey].removeElement(element);
}
public int size() {
return ARR_SIZE;
}
public class Node {
T data;
int key;
Node next;
Node prev;
public Node(T t, int k, Node p, Node n) {
data = t;
key = k;
prev = p;
next = n;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPrev() {
return prev;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public void display() {
System.out.println(data);
}
}
public class LinkedList {
Node header;
Node trailer;
int size = 0;
public LinkedList() {
header = new Node(null, -1, trailer, null);
trailer = new Node(null, -1, null, null);
header.setNext(trailer);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public void addFirst(T t, int hashKey) {
Node currentLast = header.getNext();
Node newest = new Node(t, hashKey, header, currentLast);
header.setNext(newest);
currentLast.setPrev(newest);
size++;
}
public T add(T t) {
Node currentLast = header.getNext();
Node newest = new Node(t, -1, header, currentLast);
header.setNext(newest);
currentLast.setPrev(newest);
size++;
return newest.getData();
}
public T removeElement(T t) {
if (isEmpty()) {
return null;
}
T element = t;
return removeNode(findNode(element));
}
public T removeNode(Node node) {
if (isEmpty()) {
return null;
}
Node pred = node.getPrev();
Node succ = node.getNext();
pred.setNext(succ);
succ.setPrev(pred);
size--;
return node.getData();
}
public LinkedList findAllElements(T t) {
Node current = header.getNext();
T element = t;
if (isEmpty()) {
return null;
}
LinkedList all = new LinkedList();
while (current != null) {
if (current.getData() == element) {
all.addFirst(element, -1);
} else {
current = current.getNext();
}
}
return all;
}
public Node findNode(T t) {
Node current = header.getNext();
T element = t;
if (isEmpty()) {
return null;
}
while (current.getNext() != null && current.getData() != element) {
current = current.getNext();
}
if (current.getNext() == null && current.getData() != element) {
System.out.println("Does not exist");
}
return current;
}
}
public static void main(String[] args) {
Bag<Integer> bag = new Bag();
bag.add(1);
bag.add(1);
bag.add(2);
bag.add(2);
bag.add(8);
bag.add(5);
bag.add(90);
bag.add(43);
bag.add(43);
bag.add(77);
bag.add(100);
bag.add(88);
bag.add(555);
bag.add(345);
bag.add(555);
bag.add(999);
bag.find(1);
}
}
Initialize your theArray to avoid NullPointerExceptions.
LinkedList[] theArray = new LinkedList[ARR_SIZE];

java.lang.NullPointerException in my custom class

I wish to implement a Queue based in a simple linked list class, without using java.util.
When I call the addEnd method in List class through enqueue method, I receive a java.lang.NullPointerException, though I expect the second element.
Which solution can I take?
The node class
public class Node {
private int value;
private Node next;
public Node(int val) {
value = val;
}
public Node(int val, Node next) {
value = val;
this.next=next;
}
public Node(Node next) {
this.next=next;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void displayNode() {
System.out.print(" "+value+" ");
}
}
My interface
public interface MyQueue {
void enqueue(int oVal);
int dequeue();
}
The List
public class List {
private Node first;
private Node last;
private int counter;
public List() {
first = null;
last = null;
}
public boolean isEmpty() {
return first==null;
}
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first = n1;
} else {
last.setNext(n1);
last = n1;
}
}
public int deleteStart() {
int temp = first.getValue();
if(first.getNext() == null){
last = null;
first = first.getNext();
}
return temp;
}
public void displayList() {
Node current = first;
while(current != null) {
current.displayNode();
current = current.getNext();
}
System.out.println("");
}
public int size() {
return counter;
}
}
The Queue
public class Queue implements MyQueue {
private List listQ;
public Queue() {
listQ = new List();
}
public boolean isEmpty() {
return listQ.isEmpty();
}
public void enqueue(int oVal) {
listQ.addEnd(oVal);
}
public int dequeue() {
return listQ.deleteStart();
}
public void displayQueue() {
System.out.print("Queue ");
listQ.displayQueue();
}
}
public class App {
public static void main(String[] args) {
Queue q1 = new Queue();
System.out.println("Two insertions");
q1.enqueue(4);
q1.enqueue(64);
q1.displayQueue();
System.out.println("Insert at the end : ");
q1.enqueue(23);
q1.displayQueue();
System.out.println("Delete an element at the begining of the queue");
q1.dequeue();
q1.displayQueue();
}
}
What #pens-fan-69 said is true. I'd like to add on to that. In order to make your code work, all you have to do is make sure last is set to first during the first insert:
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first=last=n1;
} else {
last.setNext(n1);
last = n1;
}
}
I tried running the code in online compiler and it works: http://goo.gl/99FyfY
You need to set the last reference when inserting to the empty list. The NullPointerException is because you use last before ever setting it.

Categories

Resources