Getting WA(Wrong asnwer) for http://www.spoj.com/problems/IITWPC4I/ - java

I have used disjoint set concept to solve this problem. Starting with all milkmen as visited, whenever a new person can be reached with new branch, he is marked as visited. I have already tested following edge cases:
There is no milkmen in the city
Everyone is milkman
Some milkman is not connected to anyone
Some person is not connected to anyone
Multiple paths between 2 people
Milkmen and people are forming disjoint set
Still i am getting WA. Any idea about missing case?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by VIVEK VERMA on 9/25/2016.
*/
public class SpojIITWPC4I {
public static void main(String[] arge) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
for (int t = 0; t < T; t++) {
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
int totalIncludedNodes = 0;
ManNode[] people = new ManNode[n];
Queue<ManLink> links = new PriorityQueue<>();
tokenizer = new StringTokenizer(reader.readLine());
for(int i=0;i<n;i++){
int val=Integer.parseInt(tokenizer.nextToken());
people[i] = new ManNode(i);
if(val==1){
people[i].isIncluded = true;
totalIncludedNodes++;
}
}
for(int i = 0; i<m;i++){
tokenizer = new StringTokenizer(reader.readLine());
int start = Integer.parseInt(tokenizer.nextToken()) -1;
int destination = Integer.parseInt(tokenizer.nextToken()) -1;
int value = Integer.parseInt(tokenizer.nextToken());
ManLink link = new ManLink(people[start], people[destination], value);
people[start].AddChild(link);
people[destination].AddChild(link);
if(people[start].isIncluded ^ people[destination].isIncluded){
links.add(link);
}
}
int minCost = 0;
while(!links.isEmpty() && totalIncludedNodes <n){
ManLink link = links.poll();
ManNode nextAddedNode = (link.source.isIncluded==true?link.destinationNode:link.source);
if(nextAddedNode.isIncluded){
continue;
}
minCost += link.value;
nextAddedNode.isIncluded = true;
totalIncludedNodes++;
for(int i=0;i<nextAddedNode.children.size();i++){
if((nextAddedNode.isIncluded ^ nextAddedNode.children.get(i).source.isIncluded)
|| (nextAddedNode.isIncluded ^ nextAddedNode.children.get(i).destinationNode.isIncluded)){
links.add(nextAddedNode.children.get(i));
}
}
}
if(totalIncludedNodes == n){
System.out.println(minCost);
}else{
System.out.println("impossible");
}
}
}
}
class ManNode{
boolean isIncluded = false;
List<ManLink> children = new ArrayList<>();
int index;
ManNode(int index){
this.index = index;
}
void AddChild(ManLink link){
children.add(link);
}
}
class ManLink implements Comparable{
ManNode destinationNode, source;
int value;
ManLink(ManNode source, ManNode node, int value){
this.source = source;
this.destinationNode = node;
this.value = value;
}
#Override
public int compareTo(Object o) {
return this.value - ((ManLink)o).value;
}
}

Related

How do I check for duplicates from my 2d Array? Java

What I want is if [1][0] is already in the list then if inputting [0][1] is considered as duplicate thus not adding it to the loop. That's the only thing that I wanted to accomplish and yet it seems impossible; at least for me.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MatrixGraph{
List<List<Integer>> graph;
Scanner input = new Scanner(System.in);
ArrayList<Connection> Links = new ArrayList<Connection>();
boolean visited[];
int nodes;
int vertices;
int matrix[][];
class Node {
String name;
boolean visited;
ArrayList<Node> neighbors = new ArrayList<Node>();
Node(String name) {
this.name = name;
visited = false;
}
}
class Connection {
double fare;
Node source, destination;
Connection(Node source, Node destination) {
this.source = source;
this.destination = destination;
}
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int V = s.nextInt();
MatrixGraph amg = new MatrixGraph(V);
int n1 = V-1; int n2 = V*n1; int maxSize = n2/2;
while (true){
System.out.println("Enter the number of edges");
int E = s.nextInt();
if (E > maxSize){
System.out.println("Too Much Edges!");
continue;
}else{
System.out.print("\n");
for(int i=0;i<E;i++){
System.out.print("Source: ");
int mark = s.nextInt();
System.out.print("Destination: ");
int mac = s.nextInt();
if (mark == mac) {
System.out.println("\nERROR TRAPPED!!\nNo Loops Allowed Here!\nAdd New Edge!");
i--;
continue;
} else if(mark > (V-1)||mac > (V-1)) {
i--;
System.out.println("\nLOL No\n");
}
amg.addEdge(mark,mac);
amg.addEdge1(mark,mac);
}
}
}
}
MatrixGraph(int vertices){
graph = new ArrayList<>();
visited = new boolean[vertices];
this.vertices=vertices;
matrix=new int[vertices][vertices];
for (int i = 0; i < vertices; i++){
graph.add(i, new ArrayList<>());
}
}
public void addEdge(int source,int destination){
matrix[source][destination]= 1;
matrix[destination][source]= 1;
}
public void addEdge1(int a, int b) {
graph.get(a).add(b);
graph.get(b).add(a);
}
}

Difficulty reading .txt data when running Stable Marriage algorithm in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am new to Java and I am trying to execute the code below regarding Stable Marrage algorithm, but when executing the code below you get the following error:
Error: For input string: "3 " Exception in thread "main"
java.lang.NullPointerException at
br.com.entrada.GaleShapley.(GaleShapley.java:21) at
br.com.entrada.GaleShapley.main(GaleShapley.java:166)
Gale Shapley Marriage Algorithm
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args)
{
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = {"1", "2", "3"};
/** list of women **/
String[] w = {"1", "2", "3"};
/** men preference **/
String[][] mp = null ;
/** women preference **/
String[][] wp= null ;
// Input.txt is like
// 3 <--defines the size of array
// male preference array
// 1 3 2
// 1 2 3
// 2 3 1
//female preference array
//1 3 2
//2 1 3
//2 1 3
try{
FileInputStream fstream = new FileInputStream("input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line=0;
int k=0;
int n=0;
int i=0;
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
GaleShapley gs = new GaleShapley(m, w, mp, wp);
}
}
The program is not reading the input.txt input file completely. It is reading only the first line of this file. And I can't solve this. I think the problem should be in the code part below.
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
Below is the input file: input.txt
3
male preference array
1 3 2
1 2 3
2 3 1
female preference array
1 3 2
2 1 3
2 1 3
The error is thrown due this : 3 => it contains a whitespace
And when you call the Integer.parse(N), N cannot be parsed to Integer while there's this whitespaces,
To resolve this, i used strLine.trim();
women[i].equals(str) : you are comparing here a string to an Integer is always false and the result of your function womenIndexOf is -1, and this is going to throw an exception of IndexOutOfBounds Exception when using the -1 as index
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley {
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley() {
}
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp) {
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches() {
while (engagedCount < N) {
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++) {
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null) {
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
} else {
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index)) {
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
engagedCount++;
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index) {
for (int i = 0; i < N; i++) {
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str) {
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str) {
for (int i = 0; i < N; i++) {
if (women[i].equals(str))
return i;
}
return -1;
}
/** print couples **/
public void printCouples() {
System.out.println("Couples are : ");
for (int i = 0; i < N; i++) {
System.out.println(womenPartner[i] + " " + women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("C:\\Users\\Youssef\\Projects\\STS\\TEST\\src\\input");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
Follows the code running below:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
public GaleShapley() {}
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("src\\input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
The result is:
Gale Shapley Marriage Algorithm
Couples are :
1 1
2 2
3 3

Can't access variable from toString in

I'm back with another question about my Dijkstra algorithm. I fixed my previous question, but now I want to make a toString() method.
When I try to make it, the variables I use are unreachable from toString(), and I don't understand why.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Graph
{
ArrayList<Vertex> vertexObjects = new ArrayList<Vertex>();
ArrayList<Edge> edgeObjects = new ArrayList<Edge>();
ArrayList<Vertex> visitedObjects = new ArrayList<Vertex>();
ArrayList<Vertex> unvisitedObjects = new ArrayList<Vertex>();
ArrayList<Edge> tempEdge = new ArrayList<Edge>();
int numVertices = 0;
public void readFile(String textfile)
{
try {
Scanner s = new Scanner(new File(textfile));
String sameVertex = "";
while (s.hasNext()) {
String preVertex = s.next();
String postVertex = s.next();
String distance = s.next();
Edge temp = new Edge(preVertex, postVertex, distance);
edgeObjects.add(temp);
if (!(preVertex.equals(sameVertex)))
{
Vertex herp = new Vertex(preVertex, Double.POSITIVE_INFINITY, false, null);
vertexObjects.add(herp);
sameVertex = preVertex;
numVertices++;
}
}
} catch (FileNotFoundException e) {
System.out.println("I can't find that file!");
}
}
public void dijkstra(String startVertex, String endVertex)
{
// Change the distance of the startVertex to 0 and all others to infinity.
for (int i = (numVertices-1); i >= 0; i--)
{
if (vertexObjects.get(i).vertexName.equals(startVertex))
{
vertexObjects.get(i).distance = 0;
} else {
vertexObjects.get(i).distance = Double.POSITIVE_INFINITY;
}
}
//Set the node with lowest distance value to Current Status
unvisitedObjects = vertexObjects;
double smallDistance = Double.POSITIVE_INFINITY;
while(unvisitedObjects.size() != 0) {
//set current node to vertex with shortest distance
String currentNode = "";
for (int j = (unvisitedObjects.size()-1); j >= 0; j--) {
if (unvisitedObjects.get(j).distance <= smallDistance) {
smallDistance = unvisitedObjects.get(j).distance;
currentNode = unvisitedObjects.get(j).vertexName;
}
}
//remove the smallest distance having node from the unvisited array
//and place into visited array.
for (int g = (unvisitedObjects.size()-1); g >= 0; g--) {
if (unvisitedObjects.get(g).vertexName.equals(currentNode))
{
visitedObjects.add(unvisitedObjects.get(g));
unvisitedObjects.remove(g);
}
}
//for all the nodes that are adjacent to the current node, update their
//distance values if they are larger than the weight plus previous distances.
for (int w = (edgeObjects.size()-1); w >= 0; w--) {
if (edgeObjects.get(w).startVertex == currentNode) {
tempEdge.add(edgeObjects.get(w));
}
for (int t = (tempEdge.size()-1); t >=0; t--) {
for (int p = (vertexObjects.size()-1); p >= 0; p--) {
if (tempEdge.get(t).endVertex == vertexObjects.get(p).vertexName)
{
if ((Double.parseDouble(tempEdge.get(t).edgeWeight) + smallDistance) < vertexObjects.get(p).distance) {
vertexObjects.get(p).distance = (Double.parseDouble(tempEdge.get(t).edgeWeight) + smallDistance);
}
}
}
}
}
}
String smallDString = Double.toString(smallDistance);
}
public Graph(String textfile, String startingVertex, String endingVertex) {
String graphFile = textfile;
String startVertex = startingVertex;
String endVertex = endingVertex;
}
public String toString() {
return ("The shortest path from "+startVertex+" to "+endVertex+" is "+smallDistance+".");
}
}
You can't access them because they are initialized within a function. You need to declare them as global variables.
ArrayList<Vertex> vertexObjects = new ArrayList<Vertex>();
ArrayList<Edge> edgeObjects = new ArrayList<Edge>();
ArrayList<Vertex> visitedObjects = new ArrayList<Vertex>();
ArrayList<Vertex> unvisitedObjects = new ArrayList<Vertex>();
ArrayList<Edge> tempEdge = new ArrayList<Edge>();
int numVertices = 0;
String startVertex, smallDistance, endVertex = "";
that might be the problem.
You need to make them field in your class. Not just local variables. For example in your constructor you can do:
private String graphFile; // declare variable to store value
public Graph(String textfile, String startingVertex, String endingVertex) {
graphFile = textfile; // assign value in constructor
...
You've only declared the variables in the public Graph(...) constructor, not in the scope for the rest of the class.
You need to declare them in the class body (normally near the top) for the methods to have access to them.
This is because you declared and initialized the variables (graphFile,startVertex,endVertex,) inside of your constructor. This means that they are only visible/usable inside the constructor. You need to declare them as class variables, then you can initialize them in the constructor. For example
public class Graph {
String graphFile;
public Graph(String textfile) {
this.graphFile = textfile;
}
}
You can do the same for the others as well.

File I/O in Java

I have problems with the code for my own Vector class.
FIXED. Added reading and writing to file, but this try/catch things look too cumbersome for me. Maybe there's a better way of file I/O?
FIXED-2 Oh, I've just discovered "throws" and now my code looks really good. Thanks everyone for help! Here's the final version of Stack.java:
import java.util.Scanner;
import java.io.*;
class Vector {
private int[] vec;
private int length, pointer;
public Vector(int n) {
pointer = 0;
length = n;
vec = new int[length];
}
public int get(int i) {
return vec[i];
}
public void set(int i, int n) {
vec[i] = n;
}
public void push(int n) {
if (pointer == length) {
int[] nvec = new int[length*2];
for (int i = 0; i < length; i++)
nvec[i] = vec[i];
length *= 2;
vec = null;
vec = nvec;
}
vec[pointer++] = n;
}
public void delete() {
pointer--;
if (pointer == length / 4) {
int[] nvec = new int[length/2];
for (int i = 0; i <= pointer; i++)
nvec[i] = vec[i];
length /= 2;
vec = null;
vec = nvec;
}
}
public int size() {
return pointer;
}
public int actualSize() {
return length;
}
}
public class Stack {
public static void main(String[] args) throws IOException {
File ifile = new File("stack1.in");
BufferedReader reader = new BufferedReader(new FileReader(ifile));
File ofile = new File("stack1.out");
BufferedWriter writer = new BufferedWriter(new FileWriter(ofile));
int n = Integer.parseInt(reader.readLine());
Vector stack = new Vector(10);
for (int i = 0; i < n; i++) {
String s = reader.readLine();
if (s.charAt(0) == '-') {
writer.write(Integer.toString(stack.get(stack.size()-1)));
writer.write("\n");
stack.delete();
} else {
s = s.substring(2);
stack.push(Integer.parseInt(s));
}
}
writer.close();
reader.close();
}
}
Your syntax is wrong. Perhaps you meant something like this:
Vector stack = new Vector(10);
Also, are you sure you want your Vector class inside your Stack class? Also also, it's generally a bad idea to name your classes the same thing as existing Java classes.
Initialise the Vector class as below
Vector stack = new Vector(10);
Vector stack = new Vector(10);

Java constructor and modify the object properties at runtime

Note: This is an assignment
Hi,
I have the following class/constructor.
import java.io.*;
class Set {
public int numberOfElements = 0;
public String[] setElements = new String[5];
public int maxNumberOfElements = 5;
// constructor for our Set class
public Set(int numberOfE, int setE, int maxNumberOfE) {
int numberOfElements = numberOfE;
String[] setElements = new String[setE];
int maxNumberOfElements = maxNumberOfE;
}
// Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :(
static String[] removeAt(int k, String[] arr) {
final int L = arr.length;
String[] ret = new String[L - 1];
System.arraycopy(arr, 0, ret, 0, k);
System.arraycopy(arr, k + 1, ret, k, L - k - 1);
return ret;
}
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i] != null && setElements[i].equals(element) ) {
return retval = i;
}
retval = -1;
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem == -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
}
}
int getLength() {
if ( setElements != null ) {
return setElements.length;
}
else {
return 0;
}
}
String[] emptySet() {
setElements = new String[0];
return setElements;
}
Boolean isFull() {
Boolean True = new Boolean(true);
Boolean False = new Boolean(false);
if ( setElements.length == maxNumberOfElements ){
return True;
} else { return False; }
}
Boolean isEmpty() {
Boolean True = new Boolean(true);
Boolean False = new Boolean(false);
if ( setElements.length == 0 ) {
return True;
} else { return False; }
}
void remove(String newValue) {
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(newValue) ) {
setElements = removeAt(i,setElements);
}
}
}
int isAMember(String element) {
int retval = -1;
for ( int i = 0; i < setElements.length; i++ ) {
if (setElements[i] != null && setElements[i].equals(element)) {
return retval = i;
}
}
return retval;
}
void printSet() {
for ( int i = 0; i < setElements.length; i++) {
System.out.println("Member elements on index: "+ i +" " + setElements[i]);
}
}
String[] getMember() {
String[] tempArray = new String[setElements.length];
for ( int i = 0; i < setElements.length; i++) {
if(setElements[i] != null) {
tempArray[i] = setElements[i];
}
}
return tempArray;
}
Set union(Set x, Set y) {
String[] newXtemparray = new String[x.getLength()];
String[] newYtemparray = new String[y.getLength()];
Set temp = new Set(1,20,20);
newXtemparray = x.getMember();
newYtemparray = x.getMember();
for(int i = 0; i < newXtemparray.length; i++) {
temp.add(newYtemparray[i]);
}
for(int j = 0; j < newYtemparray.length; j++) {
temp.add(newYtemparray[j]);
}
return temp;
}
}
// This is the SetDemo class that will make use of our Set class
class SetDemo {
public static void main(String[] args) {
//get input from keyboard
BufferedReader keyboard;
InputStreamReader reader;
String temp = "";
reader = new InputStreamReader(System.in);
keyboard = new BufferedReader(reader);
try
{
System.out.println("Enter string element to be added" );
temp = keyboard.readLine( );
System.out.println("You entered " + temp );
}
catch (IOException IOerr)
{
System.out.println("There was an error during input");
}
/*
**************************************************************************
* Test cases for our new created Set class.
*
**************************************************************************
*/
Set setA = new Set(1,10,10);
setA.add(temp);
setA.add("b");
setA.add("b");
setA.add("hello");
setA.add("world");
setA.add("six");
setA.add("seven");
setA.add("b");
int size = setA.getLength();
System.out.println("Set size is: " + size );
Boolean isempty = setA.isEmpty();
System.out.println("Set is empty? " + isempty );
int ismember = setA.isAMember("sixb");
System.out.println("Element six is member of setA? " + ismember );
Boolean output = setA.isFull();
System.out.println("Set is full? " + output );
setA.printSet();
int index = setA.findElement("world");
System.out.println("Element b located on index: " + index );
setA.remove("b");
setA.emptySet();
int resize = setA.getLength();
System.out.println("Set size is: " + resize );
setA.printSet();
Set setB = new Set(0,10,10);
Set SetA = setA.union(setB,setA);
SetA.printSet();
}
}
I have two question here, why I when I change the class property declaration to:
class Set {
public int numberOfElements;
public String[] setElements;
public int maxNumberOfElements;
// constructor for our Set class
public Set(int numberOfE, int setE, int maxNumberOfE) {
int numberOfElements = numberOfE;
String[] setElements = new String[setE];
int maxNumberOfElements = maxNumberOfE;
}
I got this error:
\
javaprojects>java SetDemo
Enter string element to be added
a
You entered a
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:30)
at Set.add(Set.java:43)
at SetDemo.main(Set.java:169)
Second, on the union method, why the result of SetA.printSet still printing null, isn't it getting back the return value from union method?
Thanks in advance for any explaination.
lupin
You're shadowing your instance variables in the constructor:
When you write:
public Set(int numberOfE, int setE, int maxNumberOfE) {
int numberOfElements = numberOfE;
String[] setElements = new String[setE];
int maxNumberOfElements = maxNumberOfE;
}
That creates three new variables all of which only last the duration of the constructor. It should be:
public Set(int numberOfE, int setE, int maxNumberOfE) {
this.numberOfElements = numberOfE;
this.setElements = new String[setE];
this.maxNumberOfElements = maxNumberOfE;
}
You can drop the this. in this second version, but I find it clearer (it also lets you reuse variable names).
Also, you don't need to do:
String[] newXtemparray = new String[x.getLength()];
String[] newYtemparray = new String[y.getLength()];
Set temp = new Set(1,20,20);
newXtemparray = x.getMember();
newYtemparray = x.getMember();
Just:
Set temp = new Set(1,20,20);
String[] newXtemparray = x.getMember();
String[] newYtemparray = y.getMember();
is fine (note you also had a typo for newYtemparray; it was x.getMember)
These are reference variables. Currently, you're initialize them each to point to a new array. Then immediately, you assign them to point to a different array. So you're needlessly allocating and destructing memory.
Maybe because you forget about hiding? You don't assign any values to class vars in constructor, you just create new objects, which are garbage collected after constructor ends. Look for "scopes" or "visibility" for further info.

Categories

Resources