Dynamic programming for a complete binary tree - java

I'm trying to apply dynamic programming on a complete binary tree with 15 nodes, where each node is of type Employee and has a value(Evalution_Score) of type double and an ID.
I created an array of type double to store the max values. The method find returns the node with ID = j or I
public class BT<T> {
BTNode<T> root, current;
public BT() {
root = current = null;
}
public void max(){
BTNode<Employee> tmproot = (BTNode<Employee>)root;
BTNode<Employee> tmp=null;
double x[] = new double[33];
Employee p[] = new Employee[33];
for(int i=14;i>=0;i--) {
tmp = search(i+1, tmproot);
x[i] = Math.max(x[i+1], (tmp.data.Evaluation_Score + x[i+2+2]));
}
for(int j=14;j>=0;j--) {
tmp = search(j+1, tmproot);
if(x[j+1]<x[j])
p[j] = tmp.data;
}
for(Employee e: p)
System.out.println(e);
}
public BTNode<Employee> search(int id, BTNode<Employee> node){
if(node != null){
if(node.data.ID ==id){
return node;
} else {
BTNode<Employee> foundNode = search(id, node.left);
if(foundNode == null) {
foundNode = search(id, node.right);
}
return foundNode;
}
} else {
return null;
}
}
}
class BTNode <T> {
public T data;
public BTNode<T> left, right;
/** Creates a new instance of BTNode */
public BTNode(T val) {
data = val;
left = right = null;
}
public BTNode(T val, BTNode<T> l, BTNode<T> r){
data = val;
left = l;
right = r;
}
}
class Employee {
int ID_of_parent;
String Name;
int ID;
double Evaluation_Score;
public Employee(int ID_of_parent , String Name , int ID , double Evaluation_Score) {
this.ID_of_parent = ID_of_parent;
this.Name = Name;
this.ID = ID;
this.Evaluation_Score = Evaluation_Score;
}
public String toString() {
return ID_of_parent + ":" + Name + ":" + ID + ":" + Evaluation_Score + "\n";
}
}
But for some reason it's not printing the required output exactly.

Related

Linked List program only adding one object when reading line from text file

I am having a problem here. I am trying to add more than one line when reading from text file and adding item to linked list, but for some reason it stops after the first line. This program reads a file line by line splits each word into an array and adds that object to a linked list. When I print it only prints the first line of the text file.
package com.foodlist;
public class Food {
private String name;
private String group;
private int calories;
private double percentage;
public Food(String name, String group, int calories, double percentage){
this.name = name;
this.group = group;
this.calories = calories;
this.percentage = percentage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public String toString(){
String result = "";
result = name + " " + group + " " + calories + " " + percentage + "\n";
return result;
}
}public class FoodList {
private FoodListNode head;
private class FoodListNode{
public Food f;
public FoodListNode next;
public FoodListNode(Food f){
this.f = f;
this.next = null;
}
}
public FoodList(){
head = null;
}
public FoodList getFoodList(){
final String FILE_NAME = "foods.txt";
String[] item = null;
Scanner inFile = null;
try {
inFile = new Scanner(new File(FILE_NAME));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FoodList list = new FoodList();
while (inFile.hasNextLine()){
String line = inFile.nextLine().trim();
item = line.split("\\s+");
if(item.length==4){
list.add(new Food(item[0], item[1], Integer.parseInt(item[2]), Double.parseDouble(item[3])));
}
}
inFile.close();
return list;
}
public void add(Food f){
FoodListNode node = new FoodListNode(f);
if (head == null){
head = node;
}
else{
FoodListNode tmp = head;
while (tmp.next != null){
tmp = tmp.next;
tmp.next = node;
}
}
}
public String toString(){
String result = "";
FoodListNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next){
result += tmp.f;
}
return result;
}
}
public class FoodMenu {
public static void main(String[] args) {
FoodList items = new FoodList();
FoodList list = items.getFoodList();
System.out.println(list);
}
}
The problem was the braces I put in the while loop here:
if (head == null){
head = node;
} else {
FoodListNode tmp = head;
while (tmp.next != null)->{
tmp = tmp.next;
tmp.next = node;
}<-
}
I removed them and now it is working perfectly. Have not looked into why this change fixed it, but will look into it more.

Sorting a linkedList by the value of the object

For an assignment, I've been tasked to create a priority based support ticket system which contains the user's Name, ID, Handler and Priority however ticket's with higher priority are placed first in the list to be dealt with.
I have three classes.
Main: where I add/delete and change ticket priority.
TicketSystem: Contains the constructor for the ticket alongside getters and setter methods
LinkedList: Has insert, delete printList and should have sortList
So far I've determined the algorithm needs to be bubblesort as Priority is an int value but I'm not too sure how to receive the value for priority and then sort it.
public class TicketSystem {
private String handler;
private int priority;
private String iD;
private String creator;
public TicketSystem() {
}
public String getHandler ( ) {
return handler;
}
public int getPriority () {
return priority;
}
public String getID () {
return iD;
}
public String creator () {
return creator;
}
public void setID (String i) {
this.iD = i;
}
public void setHandler (String h) {
this.handler = h;
}
public void setPriority (int p ) {
this.priority = p;
}
public String setCreator (String c) {
return this.creator = c;
}
public void addTicket( String h, int p, String c, String iD) {
this.handler = h;
this.priority = p;
this.iD = iD;
this.creator = c;
}
#Override
public String toString() {
String output = "";
output += "Handler: " + handler +", ";
output += "Priority: " + priority + ", ";
output += "Creator: " + creator + ", ";
output += "ID: " + iD + " ";
return output;
}
}
public class LinkedList {
private Node head;
public LinkedList(TicketSystem ticket) {
head = new Node();
head.ticket = ticket;
head.link = null;
}
public boolean insertItem(TicketSystem ticket) {
Node n = new Node();
Node new_node;
new_node = head;
while (new_node.link != null) {
new_node = new_node.link;
}
n.ticket = ticket;
n.link = null;
new_node.link = n;
return true;
}
public void printList() {
Node z = head;
while (z!= null) {
System.out.println(z.ticket.toString());
z = z.link;
}
}
public boolean deleteItem(TicketSystem ticket) {
if(ticket.equals(head.ticket)) {
head = head.link;
return true;
} else {
Node prevNode = head;
Node curNode = head.link;
while(curNode != null && !(curNode.ticket == ticket)) {
prevNode = curNode;
curNode = curNode.link;
}
if(curNode != null) {
prevNode.link = curNode.link;
return true;
} else {
return false;
}
}
}
/* sort list */
public void sortList() {
TicketSystem ts = new TicketSystem();
}
class Node {
private TicketSystem ticket;
private Node link;
}
}

How to sort a custom Linked List in Java?

I am working on a custom Linked List based on Crunchify's implementation to display list of Employee. As of now I can add new Employee or remove existing Employee from the list. However, my project requires adding a sorting method that would not be based on Collections.sort(). My teacher wants this sorting method to be custom, so this is quite difficult for me. Is there anyway to sort this list by first name that is easy to code (I'm completely new to object oriented programming)?
Here is my custom Linked List:
import java.util.Scanner;
import java.io.IOException;
public class MyLinkedListTest2 {
public static MyLinkedList linkededList;
public static void main(String[] args) {
linkededList = new MyLinkedList();
linkededList.add(new Employee("Agness", "Bed", 2000.0, 32));
linkededList.add(new Employee("Adriano", "Phuks", 4000.0, 16));
linkededList.add(new Employee("Panda", "Mocs", 6000.0, 35));
System.out.println(linkededList);
//OPTIONS
Scanner scanner = new Scanner(System.in);
int selection;
do {
System.out.println("OPTIONS:\n[1] ADD EMPLOYEE\n[2] REMOVE EMPLOYEE\n[3] SORT \n[4] EXIT\n");
selection = scanner.nextInt();
switch (selection) {
case 1:
System.out.println("Name:");
scanner.nextLine();
String name = scanner.nextLine();
System.out.println("Surname:");
String surname = scanner.nextLine();
System.out.println("Salary:");
double salary = scanner.nextDouble();
System.out.println("Experience:");
int experience = scanner.nextInt();
linkededList.add(new Employee(name, surname, salary, experience));
System.out.println(linkededList);
break;
case 2:
System.out.println("Which row do you want to remove?");
int choice = scanner.nextInt();
if (choice == 0)
System.out.println("No such row exists");
else if (choice > linkededList.size())
System.out.println("No such row exists");
else
linkededList.remove(choice - 1);
System.out.println(linkededList);
break;
case 3:
System.out.println("SORT BY: 1.NAME\t2.SURNAME\t3.SALARY\t4.EXPERIENCE\n");
//In this section sorting algorithm should be added
break;
case 4:
break;
default:
System.out.println("Wrong choice");
}
} while (selection != 4);
}
}
class MyLinkedList<Employee> {
private static int counter;
private Node head;
public MyLinkedList() {
}
public void add(Object data) {
if (head == null) {
head = new Node(data);
}
Node myTemp = new Node(data);
Node myCurrent = head;
if (myCurrent != null) {
while (myCurrent.getNext() != null) {
myCurrent = myCurrent.getNext();
}
myCurrent.setNext(myTemp);
}
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
public void add(Object data, int index) {
Node myTemp = new Node(data);
Node myCurrent = head;
if (myCurrent != null) {
for (int i = 0; i < index && myCurrent.getNext() != null; i++) {
myCurrent = myCurrent.getNext();
}
}
myTemp.setNext(myCurrent.getNext());
myCurrent.setNext(myTemp);
incrementCounter();
}
public Object get(int index){
if (index < 0)
return null;
Node myCurrent = null;
if (head != null) {
myCurrent = head.getNext();
for (int i = 0; i < index; i++) {
if (myCurrent.getNext() == null)
return null;
myCurrent = myCurrent.getNext();
}
return myCurrent.getData();
}
return myCurrent;
}
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node myCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (myCurrent.getNext() == null)
return false;
myCurrent = myCurrent.getNext();
}
myCurrent.setNext(myCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node myCurrent = head.getNext();
while (myCurrent != null) {
output += myCurrent.getData().toString();
myCurrent = myCurrent.getNext();
}
}
return output;
}
public void compare(int index){
Node myCurrent = head.getNext();
if(myCurrent != myCurrent.getNext())
myCurrent = head;
else
myCurrent = myCurrent.getNext();
}
private class Node {
Node next;
Object data;
public Node(Object dataValue) {
next = null;
data = dataValue;
}
#SuppressWarnings("unused")
public Node(Object dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
Also, here is my Employee class that the list is based on:
public class Employee
{
private String firstName;
private String lastName;
private double salary;
private int experience;
public Employee(String firstName, String lastName, double salary, int experience)
{
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
this.experience = experience;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public double getSalary()
{
return salary;
}
public int getExperience()
{
return experience;
}
#Override
public String toString()
{
String ret = "\n" +"Name: "+firstName +" | Surname: "+lastName +" | Salary: "+salary + " | Experience: "+experience +"\n";
return ret;
}
}
The code is compiling now, but maybe you have some recommendation regarding this implementation of Linked List? I would be grateful if someone comes up with a solution for sorting, since with this my project will be completed. Only Comparable can be used, while Collections.sort() method cannot be implemented due to project's requirements.
You can define your own EmployeeComparator that implements Comparator<Employee> (see comparator) and use it like following :
SortedSet<Employee> set = new TreeSet<Employee>(new EmployeeComparator());
set.addAll(employees);
Since you need to implement the sorting yourself, one of the easiest way could be so compare each list node with the next one and swap them if they are not in sorted order. You need to do this until there is any such out of order nodes left in the list.
You can see bubble sort implementation for an idea on how this works.

NPE when deleting a node at a given position in linked list

Node
private Object data;
private Node link;
private Node next;
private Node prev;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
public Node(Object data) {
this.data = data;
this.link = null;
}
public Node getNextNode() {
return next;
}
public Node getPrevNode() {
return prev;
}
public void setNextNode(Node n) {
next = n;
}
public void setPrevNode(Node n) {
prev = n;
}
Item
private int id;
private String name;
private String type;
private double price;
public Item(int id, String name, String type, double price) {
this.id = id;
this.name = name;
this.type = type;
this.price = price;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public double getPrice() {
return price;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Item: " + "ID: " + id + ", Name: " + name + ", Type: " + type + ", Price: " + price;
}
LinkedList
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
newNode.setLink(head);
head = newNode;
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getLink();
count--;
}
}
public void AddItemToFront(Item p) {
Node newNode = new Node(p);
newNode.setLink(head);
head = newNode;
count++;
}
public void DisplayItems() {
Node temp = head;
while(temp != null) {
System.out.println(temp.getData());
temp = temp.getLink();
}
}
public void RemoveItemAtPosition(int n) {
if(n == 1) {
Node x = head;
head = x.getLink();
count--;
}
else if (n > count || n < 0) {
System.out.println("The index you entered is out of bound.");
}
else {
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Node temp = x;
x = temp.getPrevNode();
x.setNextNode(temp.getNextNode());
temp = null;
count--;
}
}
I'm trying to remove a Node at a position given integer n.
I tried researching on SO before posting here and the above is the code that i came out with. However, the code returned me an error saying >java.lang.NullPointerException at LinkedList.java:74 at main:35
The Node is actually an object that is being added to the LinkedList
I checked your code I see that you have some bugs.
your mistakes are:
1 -you use linked object.
2- try to access previous and next without initialization.
3- you only care on the next node.
I removed link form Node class and I do some changes into LinkedList:
public class LinkedList {
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
if (head == null) {
head = newNode;
} else {
Node node = head;
head = newNode;
head.setNextNode(node);
node.setPrevNode(head);
}
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getNextNode();
head.setPrevNode(null);
count--;
}
}
public void AddItemToFront(Item p) {
Node newNode = new Node(p);
if (head == null) {
head = newNode;
} else {
Node node = head;
head = newNode;
head.setNextNode(node);
node.setPrevNode(head);
}
count++;
}
public void DisplayItems() {
Node temp = head;
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNextNode();
}
}
public void RemoveItemAtPosition(int n) {
if (n == 1) {
deleteFront();
} else if (n > count || n < 0) {
System.out.println("The index you entered is out of bound.");
} else {
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Node temp = x;
temp.getPrevNode().setNextNode(temp.getNextNode());
temp.getNextNode().setPrevNode(temp.getPrevNode());
temp = null;
count--;
}
}
}
When checking the provided source code, in the function AddItemToFront(Item p) only the linked-list is managed with newNode.setLink(head);. Both Node next; and Node prev; are never initialized and never used before in the function removeItemAtPosition(int n).
Warning: your Linked-List is managed on reverse (due to the function void AddItemToFront(Item p)).
A simple way to solve your problem should to use only Node link; also in the function removeItemAtPosition(int n).
Step 1 - in RemoveItemAtPosition(int n), modify the search of the nth Node in the for-loop
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getLink(); // Use Node link
}
Instead of
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Step 2 - in RemoveItemAtPosition(int n), connect the next node link to the node before
Node temp = x.getLink();
x.setLink(temp.getLink());
count--;
Instead of
Node temp = x;
x = temp.getPrevNode();
x.setNextNode(temp.getNextNode());
temp = null;
count--;

How to generate and print a tree from string in Java

I would like to create and print a tree from string which read from file. I tried the following code but I could not print the tree in a correct way.
I have file file.txt which has for example the following string
com-bo-news-2012,12
com-bo-news-2015,3
net-php-www,20
net-phototrails,3
I would like to create a tree like
root
|
com(17) //calculated as (2+12+3)
|bo(17)
|news(17)
|2012 (12)
|2015(3)
|net(23)
|php(20)
|www(20)
|phototrails(3)
I tried the following code
public void ReadFile(String inputFile){
Map<String[],Integer> map = new HashMap<String[], Integer>();
BufferedReader br=null;
String file1 = "";
try {
br = new BufferedReader(new FileReader(inputFile));
while ((file1 = br.readLine()) != null) {
String path[]=file1.split(",");
String nodes[]=path[0].split("-");
map.put(nodes,Integer.parseInt(path[1].trim()));
}
buildTree(map);
br.close();
}catch(Exception e){
System.out.println(e);
}
}
public void buildTree(Map<String[],Integer> map)
{
Map<String, Node> wordMap = new HashMap<String, Node>();
Node root = new Node();
for (Map.Entry<String[], Integer> entry : map.entrySet()) {
String key[] = entry.getKey();
Integer value = entry.getValue();
Node current=root;
Node p;
for(String node:key)
{
if(wordMap.containsKey(node)){
p = wordMap.get(node);
p.addCost(value);
} else {
p=new Node(node,value);
wordMap.put(node, p);
System.out.println("AddNode: "+p.getName());
}
current.addChild(p);
current = p;
}
}
printTree(root);
}
public void printTree(Node doc) { ///print tree
if (doc == null) {
System.out.println("Nothing to print!!");
return;
}
try {
System.out.println(doc.getName() + " " + doc.getCount());
List<Node> cl = doc.getChildren();
for (int i = 0; i < cl.size(); i++) {
Node node = cl.get(i);
System.out.println(
"\t" + node.getName() + " ->" + node.getCount());
}
List<Node> nl = doc.getChildren();
for (int i = 0; i < nl.size(); i++) {
Node node = nl.get(i);
printTree(node);
}
} catch (Throwable e) {
System.out.println("Cannot print!! " + e.getMessage());
}
}
public class Node {
private String name;
private int count;
private List<Node> children;
public Node() {
this(null, 0);
}
public Node(String name, int count) {
this.name = name;
this.count = count;
this.children = new ArrayList<Node>();
}
public Node(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node n) {
for (Node nn : children) {
if (nn.name.equals(n.name)) {
return;
}
}
this.children.add(n);
}
public void addCost(int i) {
this.count += i;
}
}
But I could not print the tree in a correct way which mentioned. It sometimes make a infinite loop when it will get same node as a child. Could anyone please guide me for that? Thanks.
I have added the code to generate the Tree kind of structure, have used the composite pattern.
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
TestMain testMain = new TestMain();
List<String> testData = new ArrayList<String>();
testData.add("com-bo-news-2012,12");
testData.add("com-bo-news-2015,3");
testData.add("net-php-www,20");
testData.add("net-phototrails,3");
MyNode myNode = new MyNode("ROOT");
for (String string : testData) {
List<String> l = new ArrayList<String>();
l.addAll(Arrays.asList(string.split("-")));
testMain.buildTree(l, myNode);
}
printTree(myNode, 1);
}
private void buildTree(List<String> nodeNames, MyNode node) {
if (nodeNames.isEmpty()) {
return;
}
String nodeName = nodeNames.remove(0);
MyNode myNode = new MyNode(nodeName);
int index = node.getNodes().indexOf(myNode);
if (index == -1) {
node.getNodes().add(myNode);
} else {
myNode = node.getNodes().get(index);
}
buildTree(nodeNames, myNode);
}
private static void printTree(MyNode myNode, int tabCount) {
for (int i = 0; i < tabCount; i++) {
System.out.print("\t");
}
System.out.print(myNode.getNode() + "\n");
for (int i = 0; i < tabCount; i++) {
System.out.print("\t");
}
System.out.println("|");
for (MyNode node : myNode.getNodes()) {
printTree(node, ++tabCount);
}
}
}
package com.test;
import java.util.ArrayList;
import java.util.List;
public class MyNode {
private String node;
private List<MyNode> nodes;
public MyNode(String node) {
super();
this.node = node;
this.nodes = new ArrayList<MyNode>();
}
public MyNode(String node, List<MyNode> nodes) {
super();
this.node = node;
this.nodes = nodes;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public List<MyNode> getNodes() {
return nodes;
}
public void setNodes(List<MyNode> nodes) {
this.nodes = nodes;
}
#Override
public int hashCode() {
return node.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
return ((MyNode) obj).getNode().equals(node);
}
return false;
}
#Override
public String toString() {
return node + "[" + nodes.size()+"]";
}
}
Output needs to be formatted a bit, let me know if you have any questions

Categories