How do I fill an array with user-defined objects? - java

I am writing a program that creates an object (Line) that contains a name and two nodes (x,y,z coordinates) which are then stored in a separate object (class LineModel). Within the class LineModel a method, getNodes(), is created that should return an array containing all the nodes.
My problem lies within the method getNodes(), as I am struggling to populate the array. My code is below.
public class LineModel {
// Object attributes
private String name;
private Line[] lines;
private int numLines;
// Constructor
public LineModel(String name, int maxLines) {
this.name = name;
lines = new Line[maxLines];
numLines = 0;
}
public void addLine(Line line) {
if (contains(line)) {
System.out.println("Line " + line.getName() + " already in model");
return;
}
if (numLines < lines.length) {
lines[numLines] = line;
numLines++;
} else {
System.out.println("Increase lines array size.");
System.exit(1);
}
}
public boolean contains(Line line) {
for (int i = 0; i < numLines; i++) {
if (line == lines[i])
return true;
}
return false;
}
public Line getLine(String name) {
for (int i = 0; i < numLines; i++) {
if (lines[i].getName().equals(name))
return lines[i];
}
System.out.println("Line " + name + " not found");
return null;
}
public void printModel() {
System.out.println('\n' + "Line model: " + name);
for (int i = 0; i < numLines; i++) {
System.out.println(lines[i]);
}
}
public Node getNode(String name) {
// Loop through lines
for (int i = 0; i <= numLines; i++) {
// Check if node 1 is contained in the line and returns if true
if (lines[i].getN1().getName().equals(name)) {
return lines[i].getN1();
}
// Check if node 2 is contained in the line and returns if true
else if (lines[i].getN2().getName().equals(name)) {
return lines[i].getN2();
}
}
return null;
}
public Node[] getNodes() {
Node[] nodes = new Node[2 * numLines];
for (int i = 0; i < numLines; i++) {
Node start = lines[i].getN1();
Node end = lines[i].getN2();
for (int j = 0; j < nodes.length - 1; j++) {
nodes[j] = start;
for (int k = 1; k <= nodes.length - 1; k++) {
nodes[k] = end;
}
}
}
return nodes;
}
}
Classes Node and Line are below
public class Node {
// Object attributes
private String name;
private double[] coordinates;
// Constructor(s)
public Node(String name, double x) {
this.name = name;
coordinates = new double[1];
coordinates[0] = x;
}
public Node(String name, double x, double y) {
this.name = name;
coordinates = new double[2];
coordinates[0] = x; coordinates[1] = y;
}
public Node(String name, double x, double y, double z) {
this.name = name;
coordinates = new double[3];
coordinates[0] = x; coordinates[1] = y; coordinates[2] = z;
}
// Object methods
public String getName(){
return name;
}
public double[] getCoordinates(){
return coordinates;
}
public double getX() {
if (coordinates.length > 0){
return coordinates[0];
} else {
return Double.NaN;
}
}
public double getY() {
if (coordinates.length > 1){
return coordinates[1];
} else {
return Double.NaN;
}
}
public double getZ() {
if (coordinates.length > 2){
return coordinates[2];
} else {
return Double.NaN;
}
}
public String toString() {
return "Node "+name+" "+Arrays.toString(coordinates);
}
}
public class Line {
// Object attributes
private String name;
private Node n1, n2;
// Constructor(s)
public Line(String name, Node n1, Node n2){
this.name = name;
this.n1 = n1;
this.n2 = n2;
}
public String getName(){ return name; }
// Object methods
public double length(){
double[] n1C = n1.getCoordinates();
double[] n2C = n2.getCoordinates();
if(n1C.length == n2C.length){
double pythagoras = 0;
for (int i = 0; i < n1C.length; i++) {
double dv = n2C[i] - n1C[i];
pythagoras += dv*dv;
}
return Math.sqrt(pythagoras);
}
return Double.NaN;
}
#Override
public String toString(){
return "Line "+name+" "+n1.getName()+"-->"+n2.getName()+" Length = "+length();
}
My current output is this:
[L_22751459.Node;#7530d0a

You just need to replace your getNodes() method with below code.
Need to introduce extra variable count and for every added node simply increment it. So automatically for two lines it will add four nodes like node[0],node[1],node[2],node[3]
public Node[] getNodes() {
int count=0;
Node[] nodes = new Node[2 * numLines];
for (int i = 0; i < numLines; i++) {
nodes[count]=lines[i].getN1();
nodes[count+1]=lines[i].getN2();
count=count+2;
}
return nodes;
}
public static void main(String[] args) {
LineModel obj2=new LineModel("l2",2);
obj2.addLine(new Line("name1",new Node("x",1.0),new Node("y",2.0)));
obj2.addLine(new Line("name2",new Node("x",2.0),new Node("y",3.0)));
Node[] arr=obj2.getNodes();
Arrays.stream(arr).forEach(node -> System.out.println(node.toString()));
}
Above code printing below Output which is perfectly fine.
Node x [1.0]
Node y [2.0]
Node x [2.0]
Node y [3.0]

Related

How do I return a user-defined object in java?

I am writing a program that creates an object (Line) that contains a name and two nodes (x,y,z coordinates) which are then stored in a separate object (class LineModel). Within the class LineModel a method, getNode(), is created that should return the node. The nodes are constructed in a separate object (class Node).
My problem lies within the method getNode(), as I can't seem to return the node that I'm looking for.
public class LineModel {
// Object attributes
private String name;
private Line[] lines;
private int numLines;
// Constructor
public LineModel(String name, int maxLines) {
this.name = name;
lines = new Line[maxLines];
numLines = 0;
}
// Add lines
public void addLine(Line line) {
if (contains(line)) {
System.out.println("Line " + line.getName() + " already in model");
return;
}
if (numLines < lines.length) {
lines[numLines] = line;
numLines++;
} else {
System.out.println("Increase lines array size.");
System.exit(1);
}
}
public Node getNode(String name) {
for (int i = 0; i < numLines; i++) {
if (lines[i].getN1().getName().equals(name) || lines[i].getN2().getName().equals(name)) {
return lines[i].getN1();
} else {
return null;
}
}
}
Below are the classes Line and Node
public class Line {
// Object attributes
private String name;
private Node n1, n2;
// Constructor(s)
public Line(String name, Node n1, Node n2){
this.name = name;
this.n1 = n1;
this.n2 = n2;
}
public String getName(){ return name; }
// Object methods
public double length(){
double[] n1C = n1.getCoordinates();
double[] n2C = n2.getCoordinates();
if(n1C.length == n2C.length){
double pythagoras = 0;
for (int i = 0; i < n1C.length; i++) {
double dv = n2C[i] - n1C[i];
pythagoras += dv*dv;
}
return Math.sqrt(pythagoras);
}
return Double.NaN;
}
#Override
public String toString(){
return "Line "+name+" "+n1.getName()+"-->"+n2.getName()+" Length = "+length();
}
public Node getN1() { return n1;}
public Node getN2() { return n2;}
public class Node {
// Object attributes
private String name;
private double[] coordinates;
// Constructor(s)
public Node(String name, double x) {
this.name = name;
coordinates = new double[1];
coordinates[0] = x;
}
public Node(String name, double x, double y) {
this.name = name;
coordinates = new double[2];
coordinates[0] = x; coordinates[1] = y;
}
public Node(String name, double x, double y, double z) {
this.name = name;
coordinates = new double[3];
coordinates[0] = x; coordinates[1] = y; coordinates[2] = z;
}
// Object methods
public String getName(){
return name;
}
public double[] getCoordinates(){
return coordinates;
}
public double getX() {
if (coordinates.length > 0){
return coordinates[0];
} else {
return Double.NaN;
}
}
public double getY() {
if (coordinates.length > 1){
return coordinates[1];
} else {
return Double.NaN;
}
}
public double getZ() {
if (coordinates.length > 2){
return coordinates[2];
} else {
return Double.NaN;
}
}
public String toString() {
return "Node "+name+" "+Arrays.toString(coordinates);
}
}
The current error is that it has to return type Node, but I can't seem to figure out why it says that. Sorry for the large amount of code. I'm quite new to coding so I don't know if everthing is relevant.
The for-loop inside "getNode" always gets terminated after one iteration.
If the first node has the matching name it returns the node, otherwise it returns null which always terminates the for-loop after the first iteration without checking any further nodes inside the array.
IMHO you should change the code to something like this:
public Node getNode(String name) {
for (int i = 0; i <= numLines; i++) {
if (lines[i].getN1().getName().equals(name) || lines[i].getN2().getName().equals(name)) {
return lines[i].getN1();
}
}
return null;
}
In this case the for-loop iterates over each element of the array until it finds the correct node or until there are no more elements left. If the requested node gets found it returns the node, otherwise it returns null.
You should also do
for (int i = 0; i <= numLines; i++)
instead of
for (int i = 0; i < numLines; i++)
because, in your implementation the last element of the array will always be ignored as if the array has one element "numLines" will be "1" and "1 < 1 == false". This means, that the loop even doesn't do any iteration and if "numLines" is "2" it will only perform one iteration as "2 < 2 == false".

Trying to find smallest weight of widest path of a graph using modified Dijkstra's Algorithm in Java

I need to give the widest path from one chosen node to another in a self-generated graph. After this, I need to state the "bottleneck" or smallest weight on the computed path. As it is, I don't know where to start to find the bottleneck and I'm having trouble showing the path. Under the Graph class, in the printPath method, I am currently getting a StackOverflow Error from presumably infinite recursion, though I don't understand how its recurring infinitely in the first place. I've used some code from here: https://www.geeksforgeeks.org/printing-paths-dijkstras-shortest-path-algorithm/ with slight modification to find the largest path rather than the shortest as well renaming variables. I feel an error in said modification is most likely one source of the problem. Following is the output of my most recent test:
Enter a positive integer.
5
Node list: {1,2,3,4,5}
Edge list: {(2,3,17),(2,4,8),(3,5,3)}
Enter a source node.
1
Enter a destination node
5
Vertex: 1 --> 5
Distance: 20
Path: Exception in thread "main" java.lang.StackOverflowError
at Graph.printPath(Graph.java:104)
at Graph.printPath(Graph.java:104)
at Graph.printPath(Graph.java:104)
Here's my code so far. I've had my code in separate classes, so I apologize for any errors I may have made combining them to one file. I also apologize for the massive and messy block of code but I don't think there's anything here I can weed out before posting.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class Graph{
private ArrayList<Node> nodes = new ArrayList<Node>();
private ArrayList<Edge> edges = new ArrayList<Edge>();
private int[][] adjMatrix;
Graph(int numNodes, int weightBound, double probability){
ArrayList<Node> tempNodeList = new ArrayList<Node>(numNodes);
for(int i = 0; i < numNodes; i++) {
Node tempNode = new Node(i+1);
tempNodeList.add(tempNode);
}
this.nodes = tempNodeList;
Random rand = new Random();
for(int i = 0; i < numNodes; i++) {
for(int j = i+1; j < numNodes; j++) {
if(rand.nextInt((int)Math.round(1/probability)) == 0) {
Edge tempEdge = new Edge(rand.nextInt(5*numNodes-1)+1, nodes.get(i), nodes.get(j));
edges.add(tempEdge);
}
}
}
adjMatrix = new int[numNodes][numNodes];
for(int i = 0; i < edges.size(); i++) {
adjMatrix[edges.get(i).getNode(0).getID()-1][edges.get(i).getNode(1).getID()-1] = edges.get(i).getWeight();
adjMatrix[edges.get(i).getNode(1).getID()-1][edges.get(i).getNode(0).getID()-1] = edges.get(i).getWeight();
}
}
public void printGraph() {
System.out.print("Node list: {");
for(int i = 0; i < nodes.size(); i++) {
nodes.get(i).printNode();
if(i != nodes.size()-1) {
System.out.print(",");
}
}
System.out.println("}");
System.out.print("Edge list: {");
for(int i = 0; i < edges.size(); i++) {
edges.get(i).printEdge();
if(i != edges.size()-1) {
System.out.print(",");
}
}
System.out.println("}");
}
public void widestPath(int source, int dest){
int numVertices = adjMatrix[0].length;
int[] longestDists = new int[numVertices];
boolean[] inPath = new boolean[numVertices];
for(int i = 0; i < numVertices; i++) {
inPath[i] = false;
}
longestDists[source] = 0;
Node tempNode = nodes.get(source);
tempNode.setParent(-1);
nodes.set(source, tempNode);
for(int i = 1; i < numVertices; i++) {
int furthestNode = -1;
int longestDist = Integer.MIN_VALUE;
for(int index = 0; index < numVertices; index++) {
if(!inPath[index] && longestDists[index] > longestDist) {
furthestNode = index;
longestDist = longestDists[index];
}
}
inPath[furthestNode] = true;
for(int index = 0; index < numVertices; index++) {
int edgeWeight = adjMatrix[furthestNode][index];
if(edgeWeight > 0 && ((longestDist + edgeWeight) > (longestDists[index]))){
tempNode = nodes.get(index);
tempNode.setParent(furthestNode);
nodes.set(index, tempNode);
longestDists[index] = longestDist + edgeWeight;
}
}
}
printResult(source, longestDists, dest);
}
public void printResult(int source, int[] dists, int dest) {
System.out.println("Vertex: " + (source+1) + " --> " + (dest+1));
System.out.println("Distance: " + dists[dest]);
System.out.print("Path: ");
printPath(dest);
}
public void printPath(int dest) {
if(nodes.get(dest).getParent() == -1) {
return;
}
printPath(nodes.get(dest).getParent()); // StackOverflow here
System.out.print((dest+1) + " ");
}
}
public class Node {
private int ID;
private int distance = Integer.MIN_VALUE;
private int parent;
Node(int id){
this.ID = id;
}
public int getID() {
return this.ID;
}
public void printNode() {
System.out.print(this.ID);
}
public void setDist(int dist) {
this.distance = dist;
}
public int getDist() {
return this.distance;
}
public void setParent(int p) {
this.parent = p;
}
public int getParent() {
return this.parent;
}
}
public class Edge {
private int weight;
private ArrayList<Node> vertices = new ArrayList<Node>(2);
Edge(int weight){
this.weight = weight;
}
Edge(int weight, Node n1, Node n2){
this.weight = weight;
this.vertices.add(n1);
this.vertices.add(n2);
}
public int getWeight() {
return weight;
}
public void setNodes(Node n1, Node n2) {
this.vertices.set(0, n1);
this.vertices.set(1, n2);
}
public ArrayList<Node> getNodes(){
return vertices;
}
public void printEdge() {
System.out.print("(" + vertices.get(0).getID() + "," + vertices.get(1).getID() + "," + this.weight + ")");
}
public int otherNodeIndex(int ID) {
if(vertices.get(0).getID() == ID) {
return 1;
}else if(vertices.get(1).getID() == ID) {
return 0;
} else {
return -1;
}
}
public Node getNode(int index) {
return vertices.get(index);
}
}
public class Driver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = -1;
while(input <= 0) {
System.out.println("Enter a positive integer.");
input = sc.nextInt();
}
double probability = 0.25;
Graph gr = new Graph(input, input*5, probability);
gr.printGraph();
int source = -1;
int dest = -1;
while(source < 0 || source > input) {
System.out.println("Enter a source node.");
source = sc.nextInt()-1;
}
while(dest < 0 || dest > input) {
System.out.println("Enter a destination node");
dest = sc.nextInt()-1;
}
gr.widestPath(source, dest);
}
}

Binary Search Same items & Store and Display them

This is my main search algorithm for multiple items using binary and separate function. I need someone to refactor my approach.
private int Multisearch(TYPE key){
int ind = binarySearchComparator(key);
// If element is not present
if (ind == -1)
return -1;
// Count elements on left side.
int count = 1;
int left = ind - 1;
int i = 1;
while (left >= 0 && (comparator.compare(list[left], key)) == 0)
{
lol[i] = list[left]; // store left found elements in array here
i++;
count++;
left--;
}
// Count elements
// on right side.
int right = ind + 1;
try{
while (right < list.length && (comparator.compare(list[right], key)) == 0)
{
lol[i] = list[right]; // store right found elements in array here
i++;
count++;
right++;
}
}catch(Exception e){
}
return count;
}
private int binarySearchComparator(TYPE key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) / 2 ;
TYPE midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -1; // key not found.
}
Above code is my approach and my backup. I want you guys to use a binary search to look for multiple items and store them somewhere for it to display to the user as the user is filtering items by gender and the binarysearch function will search items that is " Male " and display them all for the user.
I need it to search multiple items and display/store them somewhere else to display it to the user.
This is like a filtering function by the way if any kind soul is able to help me out. I will greatly appreciate it!
Well if you can actually count the occurrence of same item/object as well as store them to display later. I will even greatly appreciate that approach! Please show me how! Thanks!
Sorted List Interface
public interface SortedListInterface <TYPE extends Comparable<TYPE>> {
public boolean add(TYPE element);
public TYPE get(int index);
public int search(TYPE element);
public TYPE remove(int index);
public void clear();
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
SearchComparator Class
public class MobileSearch implements Comparator<Student>{
private String type;
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
#Override
public int compare(Student student1, Student student2) {
int result = 0;
if(this.type.equals("mobile")){
result = student1.getMobileNo().compareTo(student2.getMobileNo());
System.out.print(result+"mobile");
}
else if(this.type.equals("name")){
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
System.out.println(result+"name");
}
else if(this.type.equals("group")){
result = student1.getGroup().compareTo(student2.getGroup());
System.out.print(result+"group");
}
return result;
}
}
SortedArrayList Implementation
public class SortedArrayList<TYPE extends Comparable<TYPE>> implements SortedListInterface<TYPE>{
//Data Types
private TYPE[] list;
private int length;
private static final int SIZE = 10;
private Comparator<? super TYPE> comparator;
private int count;
#SuppressWarnings("unchecked")
public SortedArrayList(Comparator<? super TYPE> c) {
comparator = c;
list = (TYPE[]) new Comparable[SIZE]; // No way to verify that 'list' only contains instances of 'T'.
/* NOTE: Following is not allowed.
list = new T[SIZE]; // Cannot create a generic array of T
*/
}
// Constructors
public SortedArrayList() {
this(SIZE);
}
public SortedArrayList(int size) {
length = 0;
list = (TYPE[]) new Comparable[SIZE]; // an array of instances of a class implementing Comparable interface and able to use compareto method but its overidden instead
}
// Setter & Getters
#Override
public int getLength() {
return length;
}
#Override
public boolean isEmpty() {
return length == 0;
}
#Override
public boolean isFull() {
return false;
}
#Override
public void clear() {
length = 0;
}
// Array Expansion
private boolean isArrayFull() {
return length == list.length;
}
private void expandArray() {
TYPE[] oldList = list;
int oldSize = oldList.length;
list = (TYPE[]) new Object[2 * oldSize];
for (int i = 0; i < oldSize; i++) // copy old array elements into new array elements
list[i] = oldList[i];
}
// ADT METHODs
// Add New Elements Function
#Override
// public boolean add(TYPE element) {
// int i = 0;
//
// while (i < length && element.compareTo(list[i]) > 0) // return 0 with equal , return more than 1 if element larger than list[i] , return -1 if less
// {
// i++;
// }
//
// makeRoom(i + 1);
// list[i] = element;
// length++;
// return true;
// }
public boolean add(TYPE element) {
boolean result = false;
if (count == 0) {
list[0] = element;
count = 1;
result = true;
}
else {
if (!isFull()) {
int i = 0;
while (list[i] != null) {
if (element.compareTo(list[i]) < 0) {
break;
}
i++;
}
if (list[i] != null) {
for (int j = count - 1; j >= i; j--) {
list[j + 1] = list[j];
}
}
list[i] = element;
count++;
result = true;
}
}
return result;
}
private void makeRoom(int index) { // accepts given index
int newIndex = index - 1;
int lastIndex = length - 1;
for (int i = lastIndex; i >= newIndex; i--)
list[i + 1] = list[i];
}
//Remove Elements Function
#Override
public TYPE remove(int index) { // accepts given index
TYPE result = null;
if ( index >= 1 && index <= length ) {
result = list[index - 1];
if (index < length)
removeGap(index);
length--;
}
return result;
}
private void removeGap(int index) { // accepts given index and remove the gap where the element its removed
int removedIndex = index - 1;
int lastIndex = length - 1;
for (int i = removedIndex; i < lastIndex; i++)
list[i] = list[i + 1]; // shifts elements back to remove the gap
}
// Get Element
#Override
public TYPE get(int index) { // accepts given index and return the object
TYPE object = null;
if ( index >= 1 && index <= length)
object = list[index - 1];
return object;
}
// Search Algorithms
#Override
// public boolean search(TYPE element) {
// boolean found = false;
//
// int lo = 0;
// int hi = count - 1;
//
// while (lo <= hi) {
// int mid = (lo + hi) / 2;
// if (list[mid].compareTo(element) < 0) {
// lo = mid + 1;
// }
// else if (list[mid].compareTo(element) > 0) {
// hi = mid - 1;
// }
// else if (list[mid].compareTo(element) == 0) {
// found = true;
// break;
// }
// return found
// }
public int search(TYPE element) {
return exponentialSearch(element);
}
private boolean binarySearchComparable(TYPE element) {
boolean found = false;
int lo = 0;
int hi = count - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list[mid].compareTo(element) < 0) {
lo = mid + 1;
}
else if (list[mid].compareTo(element) > 0) {
hi = mid - 1;
}
else if (list[mid].compareTo(element) == 0) {
found = true;
break;
}
}
System.out.print("Single");
return found;
}
private int exponentialSearch(TYPE key){
int ind = binarySearchComparator(key);
// If element is not present
if (ind == -1)
return -1;
// Count elements on left side.
int count = 1;
int left = ind - 1;
int i = 1;
while (left >= 0 && (comparator.compare(list[left], key)) == 0)
{
// lol[i] = list[left];
System.out.println(left+"lefttest");
i++;
count++;
left--;
}
// Count elements
// on right side.
int right = ind + 1;
try{
while (right < list.length && (comparator.compare(list[right], key)) == 0)
{
System.out.println(right+"righttest");
// lol[i] = arr[right];
i++;
count++;
right++;
}
}catch(Exception e){
}
return count;
}
private int binarySearchComparator(TYPE key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) / 2 ;
TYPE midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -1; // key not found.
}
//To String Method
#Override
public String toString() {
String result = "";
for (int i = 0; i < count; i++)
result += list[i] + "\n";
return result;
}
}
Name Class
public class Name {
// Data Types
private String firstName;
private String lastName;
// Constructors
public Name() {
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// setter
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// getter
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName(){
return firstName + " " + lastName;
}
#Override
public String toString() {
return "Name{" + "firstName=" + firstName + ", lastName=" + lastName + '}';
}
}
Student Class
public class Student implements Comparable<Student>{
// Data Types
private String studID;
private Name name;
private String gender;
private String icNo;
private String mobileNo;
private Course course;
private String group;
private String dOB;
// Constructors
public Student() {
}
public Student(String studID, Name name, String gender, String icNo, String mobileNo, Course course, String group, String dOB) {
this.studID = studID;
this.name = name;
this.gender = gender;
this.icNo = icNo;
this.mobileNo = mobileNo;
this.course = course;
this.group = group;
this.dOB = dOB;
}
public Student(Name name) {
this.name = name;
}
// setter
public void setStudID(String studID) {
this.studID = studID;
}
public void setName(Name name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setIcNo(String icNo) {
this.icNo = icNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public void setCourse(Course course) {
this.course = course;
}
public void setGroup(String group) {
this.group = group;
}
public void setdOB(String dOB) {
this.dOB = dOB;
}
// getter
public String getStudID() {
return studID;
}
public Name getName() {
return name;
}
public String getGender() {
return gender;
}
public String getIcNo() {
return icNo;
}
public String getMobileNo() {
return mobileNo;
}
public Course getCourse() {
return course;
}
public String getGroup() {
return group;
}
public String getdOB() {
return dOB;
}
#Override
public String toString() {
return "Student{" + "name=" + name + ", gender=" + gender + ", icNo=" + icNo + ", mobileNo=" + mobileNo + ", course=" + course + ", group=" + group + ", dOB=" + dOB + '}';
}
#Override
public int compareTo(Student object) { // Sort according to name if name same then sort according to gender and so on.
int c = this.name.getFullName().compareTo(object.getName().getFullName());
if(c == 0)
c = this.gender.compareTo(object.getGender());
if(c == 0)
c = this.icNo.compareTo(object.getIcNo());
if(c == 0)
c = this.mobileNo.compareTo(object.getMobileNo());
if(c == 0)
c = this.group.compareTo(object.getGroup());
if(c == 0)
c = this.dOB.compareTo(object.getdOB());
return c;
}
public static Student[] sort(Student[] object,String category){
Student[] array;
if(category.equals("ID")){
for (int i=1; i < object.length; i++) {
for(int j = 0 ; j < object.length - i ; j++)
if( (object[j].getGender().compareTo(object[j+1].getGender())) > 0 ){
Student lol = object[j];
object[j] = object[j+1];
object[j+1] = lol;
}
}
}
array = object;
return array;
}
}
Course Class
public class Course {
// Data Types
private String courseCode;
private String courseName;
private double courseFee;
// Constructors
public Course() {
}
public Course(String courseCode, String courseName, double courseFee) {
this.courseCode = courseCode;
this.courseName = courseName;
this.courseFee = courseFee;
}
// setter
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setCourseFee(double courseFee) {
this.courseFee = courseFee;
}
// getter
public String getCourseCode() {
return courseCode;
}
public String getCourseName() {
return courseName;
}
public double getCourseFee() {
return courseFee;
}
#Override
public String toString() {
return "CourseCode = " + courseCode + "Course Name = " + courseName + "Course Fee = " + courseFee;
}
}
If your data are already sorted, you won't get faster than binary search O(log n). If there are more than one match, find one match and than iterate forward (until no more matches found) and backward (until no more matches found) from it to get all matches.(or if you only need the index of first and last match, you can replace the iterating part by again binary search for the first / last matching one. That would reduce complexity to O(n) no matter how many matches there are)
This takes O(log n) + O(#matches)
If that is not fast enough for you, try profiling your implementation to find the bottleneck where further optimization attempts make most sense.

Sort Single Linked List in descending order

How would I display this linked list in desending order by Score? I need it when it when I display it in my GUI to sort by the highest score at the top, and then desending to the lowest score in the bottom? Also, I was wondering if there is a way to limit the entries to only 10. Any help would be appreciated! Thanks.
public class ScoreList {
private Player head; //reference to the head of the list
private Player tail; //reference to the tail of the list
int count;
public ScoreList() {
count = 0;
head = null;
tail = null;
}
public int getCount() {
return count;
}
public int size() {
int count = 0;
Player p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
//method to add an item to the list - append to the tail of the list
public void add(String name, String score) {
// Create Player object
Player newPlayer = new Player(name, score);
if (head == null) {
head = newPlayer;
tail = head;
count++;
}
else {
//append to the end of the list
tail.setNext(newPlayer);
tail = newPlayer;
count++;
}
if(size() > 10) {
Player currentPlayer = head;
for (int i = 0; i < 9; i++) {
currentPlayer = currentPlayer.next;
}
currentPlayer.next = null;
}
}
// end add method
//method to let the user get the data from a node in the list
public String getItem(int index) {
String result = "";
String name = "";
String score = "";
Player curName;
if (count > 0 && index == 0) {
//return the Player info at the head of the list
name = head.getName();
score = head.getScore();
}
else if (index > 0 && index < count) {
curName = head;
for (int i = 1; i <= index; i++) {
curName = curName.getNext();
}
name = curName.getName();
score = curName.getScore();
}
result = "Player: " + name + " Score: " + score;
return result;
}
//nested inner class
public class Player {
private String player;
private String score;
private Player next;
public Player() {
player = "";
score = "";
next = null;
}
public Player(String artist, String title) {
this.player = artist;
this.score = title;
next = null;
}
public String getName() {
return player;
}
public String getScore() {
return score;
}
public Player getNext() {
return next;
}
public void setArtist(String player) {
this.player = player;
}
public void setTitle(String score) {
this.score = score;
}
public void setNext(Player next) {
this.next = next;
}
}
}
Why are you taking Score as a String?
I am assuming score as Integer
below is the sort method that you can include in ScoreList class, which will sort your LinkList in descending order of player score.
Time Complexity : O(nlogn)
Space COmplexity: O(n)
Hope this helps
public void sort() {
Player runner = head;
Player[] arr = new Player[size()];
int i = 0;
while (runner != null) {
arr[i++] = runner;
runner = runner.next;
}
Arrays.sort(arr, new Comparator<Player>() {
public int compare(Player o1, Player o2) {
if (Integer.parseInt(o1.getScore()) > Integer.parseInt(o2.getScore())) {
return -1;
} else if (Integer.parseInt(o1.getScore()) < Integer.parseInt(o2.getScore())) {
return 1;
} else {
return 0;
}
}
});
for (int j = 0; j < arr.length - 1; j++) {
arr[j].setNext(arr[j + 1]);
}
if (arr.length > 0) {
arr[arr.length - 1].setNext(null);
head = arr[0];
tail = arr[arr.length - 1];
}
}

I have ONE pre-compile error

Here is the assignment:
Modify the maze problem in Chapter 4 so that it can start from a user defined starting position (other than 0, 0) and search for a user defined ending point.
The whole program seems to look fine, and I still have to mess with the user-inputted part, but there is one line that has an error and I don't know how to get rid of it. Any help would be appreciated.
The line that has the error is:
StackADT stack = new LinkedStackADT ();
And it is telling me that LinkedStackADT cannot be resolved to a type.
Also, how do I get the maze to take in user-defined starting positions and ending points? Thanks for any possible help!
public class Maze
{
public interface StackADT<T> {
public void push (T element);
public T pop();
public T peek();
public boolean isEmpty();
public int size();
public String toString();
}
public static void main(String[] args){
abstract class LinkedStack<T> implements StackADT<T>
{
private int count;
private LinearNode<T> top;
public LinkedStack()
{
count = 0;
top = null;
}
class LinearNode<T>
{
private LinearNode<T> next;
private T element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode(T elem)
{
next = null;
element = elem;
}
public LinearNode<T> getNext()
{
return next;
}
public void setNext(LinearNode<T> node)
{
next = node;
}
public T getElement()
{
return element;
}
public void setElement(T elem)
{
element = elem;
}
}
class Position
{
private int x;
private int y;
Position ()
{
x = 0;
y = 0;
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
public void setx1(int a)
{
x = a;
}
public void sety(int a)
{
y = a;
}
public void setx(int x2) {
}
}
private final int TRIED = 3;
private final int PATH = 7;
private int [][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,0,1,1,0,1,1,1,1,0,0,1},
{1,1,1,1,1,0,1,0,1,0,1,0,0},
{0,0,0,0,1,1,1,0,1,0,1,1,1},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1}};
public StackADT<Position> push_new_pos(int x, int y,
StackADT<Position> stack)
{
Position npos = new Position();
npos.setx1(x);
npos.sety(y);
if (valid(npos.getx(),npos.gety()))
stack.push(npos);
return stack;
}
public boolean traverse ()
{
boolean done = false;
Position pos = new Position();
Object dispose;
StackADT<Position> stack = new LinkedStackADT<Position> ();
stack.push(pos);
while (!(done))
{
pos = stack.pop();
grid[pos.getx()][pos.gety()] = TRIED; // this cell has been tried
if (pos.getx() == grid.length-1 && pos.gety() == grid[0].length-1)
done = true; // the maze is solved
else
{
stack = push_new_pos(pos.getx(),pos.gety() - 1, stack);
stack = push_new_pos(pos.getx(),pos.gety() + 1, stack);
stack = push_new_pos(pos.getx() - 1,pos.gety(), stack);
stack = push_new_pos(pos.getx() + 1,pos.gety(), stack);
}
}
return done;
}
private boolean valid (int row, int column)
{
boolean result = false;
if (row >= 0 && row < grid.length &&
column >= 0 && column < grid[row].length)
if (grid[row][column] == 1)
result = true;
return result;
}
public String toString ()
{
String result = "\n";
for (int row=0; row < grid.length; row++)
{
for (int column=0; column < grid[row].length; column++)
result += grid[row][column] + "";
result += "\n";
}
return result;
}
}
}
}
You don't have a type (or a class) defined as LinkedStackADT. You do have a type LinkedStack, but it's abstract so the new will fail. If you remove the abstract keyword from LinkedStack, it should be instantiatable. (note: instantiatable is not a real word)

Categories