Java constructor and modify the object properties at runtime - java

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.

Related

How to correctly implement maximum weight independent set of positive tree using BFS

can someone help me implement the maximum weight independent set for a TREE (not a graph)?
The tree is represented by an adjacency matrix, and we have an array for the weights of the vertices.
BFS output: // 0: distances from start vertex
// 1: BFS-order
// 2: parent-IDs
I tried this code, it doesn't work on all test cases and it says most of the time that the weight is too small.
Can someone help me find the errors?
import java.io.*;
import java.util.*;
public class Lab5
{
/**
* Problem: Find a maximum weight independent set using dynammic programming.
*/
private static int[] problem(Tree t, int[] weights)
{
// Implement me!
//base cases
if (t.noOfVertices==0) {
return new int[] {};
}
if (t.noOfVertices==1) {
return new int[] {weights[0]};
}
//we will implement this using bfs, we will use 0 as the root
int[][] bfs = t.bfs(0);
//finding leaves
int leaf[] = new int [t.noOfVertices];
//now we can implement our algorithm
//M is the maximum weight of the tree if it contains i, and M1 is the maximum weight of the tree if it doesn't contain i
int M[]=new int[t.noOfVertices];
int M1[]=new int[t.noOfVertices];
//treating elements that aren't leaves
int nodeDiscovered[] = new int[t.noOfVertices];
for (int i = 0; i<t.noOfVertices; i++) {
if (t.edges[i].length==1) {
leaf[i]=1;
M[i]=weights[i];
nodeDiscovered[i]=1;
M1[i]=0;
}
else {
leaf[i]=0;
nodeDiscovered[i]=0;
}
}
for (int i = 1; i<t.noOfVertices; i++) {
if (leaf[i]==1) {
int node = bfs[2][i];
if (nodeDiscovered[node]!=0) {
continue;
}
while (node>-1) {
int parent = bfs[2][node];
ArrayList<Integer> sibs = new ArrayList<Integer>();
if (parent!=-1) {
for (int j = 0; j<t.edges[parent].length; j++) {
if (t.edges[parent][j]!=bfs[2][parent]) {
sibs.add(t.edges[parent][j]);
}
}
}
else {
sibs.add(node);
}
for (int sib : sibs) {
if (nodeDiscovered[sib]!=0) {
continue;
}
M[sib]=weights[sib];
for (int k : t.edges[sib]) {
if(bfs[0][sib]==bfs[0][k]-1) {
M[sib]=M[sib]+M1[k];
M1[sib]+=(M[k]>M1[k])?M[k]:M1[k];
}
}
nodeDiscovered[sib]=1;
}
node = bfs[2][node];
}
}
}
//putting the answers in an arraylist
ArrayList<Integer> set = new ArrayList<Integer>();
if (M[0]>M1[0]) {
set.add(0);
}
for (int i = 1; i<t.noOfVertices; i++) {
if (!set.contains(bfs[2][i]) && M[i]>=M1[i] ) {
set.add(i);
}
}
System.out.println(set);
//putting the elements of the arraylist into an array of int
int[] set1 = new int[set.size()];
for (int i = 0; i<set.size(); i++) {
set1[i]=set.get(i);
}
return set1;
}
// ---------------------------------------------------------------------
// Do not change any of the code below!
// Do not change any of the code below!
/**
* Determines if a given set of vertices is an independent set for the given tree.
*/
private static boolean isIndSet(Tree t, int[] set)
{
if (set == null) return false;
boolean[] covered = new boolean[t.noOfVertices];
for (int i = 0; i < set.length; i++)
{
int vId = set[i];
int[] neighs = t.edges[vId];
if (covered[vId]) return false;
covered[vId] = true;
for (int j = 0; j < neighs.length; j++)
{
int nId = neighs[j];
covered[nId] = true;
}
}
return true;
}
private static final int LabNo = 5;
private static final String course = "CS 427";
private static final String quarter = "Fall 2021";
private static final Random rng = new Random(190817);
private static boolean testProblem(int[][] testCase)
{
int[] parents = testCase[0];
int[] weights = testCase[1];
Tree t = Tree.fromParents(parents);
int[] solution = maxIsWeight(t, weights);
int isWeight = solution[0];
int isSize = solution[1];
int[] answer = problem(t, weights.clone());
if (!isIndSet(t, answer))
{
System.out.println("Not an independent set.");
return false;
}
int ansWeight = 0;
for (int i = 0; i < answer.length; i++)
{
ansWeight += weights[answer[i]];
}
if (ansWeight < isWeight)
{
System.out.println("Weight too small.");
return false;
}
if (answer.length < isSize)
{
System.out.println("Set too small.");
return false;
}
return true;
}
private static int[] maxIsWeight(Tree t, int[] weigh)
{
int n = t.noOfVertices;
int[][] dfs = t.dfs(0);
int[] post = dfs[2];
int[] w = new int[n];
for (int i = 0; i < n; i++)
{
w[i] = weigh[i] * n + 1;
}
boolean[] isCandidate = new boolean[n];
for (int i = 0; i < n; i++)
{
int vId = post[i];
if (w[vId] <= 0) continue;
isCandidate[vId] = true;
int[] neighs = t.edges[vId];
for (int j = 0; j < neighs.length; j++)
{
int uId = neighs[j];
w[uId] = Math.max(w[uId] - w[vId], 0);
}
}
int isWeight = 0;
int isSize = 0;
for (int i = n - 1; i >= 0; i--)
{
int vId = post[i];
if (!isCandidate[vId]) continue;
isWeight += weigh[vId];
isSize++;
int[] neighs = t.edges[vId];
for (int j = 0; j < neighs.length; j++)
{
int uId = neighs[j];
isCandidate[uId] = false;
}
}
return new int[] { isWeight, isSize };
}
public static void main(String args[])
{
System.out.println(course + " -- " + quarter + " -- Lab " + LabNo);
int noOfTests = 300;
boolean passedAll = true;
System.out.println("-- -- -- -- --");
System.out.println(noOfTests + " random test cases.");
for (int i = 1; i <= noOfTests; i++)
{
boolean passed = false;
boolean exce = false;
try
{
int[][] testCase = createProblem(i);
passed = testProblem(testCase);
}
catch (Exception ex)
{
passed = false;
exce = true;
ex.printStackTrace();
}
if (!passed)
{
System.out.println("Test " + i + " failed!" + (exce ? " (Exception)" : ""));
passedAll = false;
//break;
}
}
if (passedAll)
{
System.out.println("All test passed.");
}
}
private static int[][] createProblem(int testNo)
{
int size = rng.nextInt(Math.min(testNo, 5000)) + 5;
// -- Generate tree. ---
int[] parents = new int[size];
parents[0] = -1;
for (int i = 1; i < parents.length; i++)
{
parents[i] = rng.nextInt(i);
}
// -- Generate weights. ---
int[] weights = new int[size];
for (int i = 0; i < weights.length; i++)
{
weights[i] = rng.nextInt(256);
}
return new int[][] { parents, weights };
}
}
I attached an image that contains the algorithm that I used.

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

Compare Lists in ArrayList

I have a text file containing the following strings (which are versions of a software):
1_10_2_0_154
3_10_5_2_10
2_10_4_1
3_10_5_1_37
I'm trying to find the most recent version, in this case 3_10_5_2_10 is the version that I'm trying to display using java.
For the moment, here is my code:
BufferedReader br;
String version;
ArrayList<List<Integer>> array = new ArrayList<List<Integer>>();
List<Integer> liste = new ArrayList<Integer>();
try{
br = new BufferedReader(new FileReader(new File(FILEPATH)));
while((version= br.readLine()) != null)
{
liste = Arrays.asList(version.split("_")).stream().
map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
array.add(liste);
}
for(int i = 0; i < array.size(); i++)
{
for (List l: array)
{
Object z = l.get(i);
List<Object> listes = new ArrayList<Object>();
listes.add(z);
System.out.println(listes);
}
}
br.close();
System.out.println(array);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
I made a loop to save strings to ArrayList> like:
[[1,10,2,0,154] , [3,10,5,2,10], [2,10,4,1], [3,10,5,1,37]]
I want to get the elements of each list and compare them to find the most biggest one (most recent one) but I don't know to do that..
I sugguest you a object approach, define a class named Version with compareTo method, then using method sort on Collections class you can simply sort your versions.
Advantages
Clean and Clear code
Data validation
Main:
public class Main {
public static void main(String[] args){
List<Version> versions = Arrays.asList(
Version.create("1_10_2_0_154"),
Version.create("3_10_5_2_10"),
Version.create("2_10_4_1_49"),
Version.create("3_10_5_1_37"));
versions.sort(Version::compareTo);
System.out.println(versions.get(0).toString());
}
}
Version:
public class Version implements Comparable<Version> {
private final int major;
private final int minor;
private final int bug;
private final int release;
private final int build;
public Version(int major, int minor, int bug, int release, int build) {
this.major = major;
this.minor = minor;
this.bug = bug;
this.release = release;
this.build = build;
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getBug() {
return bug;
}
public int getRelease() {
return release;
}
public int getBuild() {
return build;
}
#Override
public String toString() {
return "Version{" +
"major=" + major +
", minor=" + minor +
", bug=" + bug +
", release=" + release +
", build=" + build +
'}';
}
public static Version create(String value){
String[] splitRes = value.split("_");
List<Integer> intValues = new ArrayList<>();
for(String v : splitRes){
intValues.add(Integer.parseInt(v));
}
return create(intValues);
}
public static Version create(List<Integer> values){
if(Objects.requireNonNull(values).size() < 5)
throw new IllegalArgumentException();
return new Version(
values.get(0),
values.get(1),
values.get(2),
values.get(3),
values.get(4)
);
}
#Override
public int compareTo(Version that) {
if (this.major > that.major) {
return -1;
} else if (this.major < that.major) {
return 1;
}
if (this.minor > that.minor) {
return -1;
} else if (this.minor < that.minor) {
return 1;
}
if (this.bug > that.bug) {
return -1;
} else if (this.bug < that.bug) {
return 1;
}
if (this.release > that.release) {
return -1;
} else if (this.release < that.release) {
return 1;
}
if (this.build > that.build) {
return -1;
} else if (this.build < that.build) {
return 1;
}
return 0;
}
}
UPDATE 1
As suggested by #Henrik i updated the list sorting with a Java 8 approach.
UPDATE 2
I reversed the compareTo method so now you can simply do plain sort calling sort method on list and passing method reference Version::compareTo
UPDATE 3
A more dynamic solution for Version class:
public class Version implements Comparable<Version> {
private final List<Integer> values;
public Version(List<Integer> values) {
this.values = values;
}
public List<Integer> getValues() {
return values;
}
#Override
public String toString() {
return String.join("_", values
.stream()
.map(Object::toString)
.collect(Collectors.toList()));
}
#Override
public int compareTo(Version that) {
List<Integer> thatValues = that.getValues();
for(int index = 0; index < values.size(); index++){
Integer value = values.get(index);
Integer thatValue = thatValues.get(index);
if (value > thatValue) {
return -1;
} else if (value < thatValue) {
return 1;
}
}
return 0;
}
public static Version create(String value){
String[] splitRes = value.split("_");
List<Integer> intValues = new ArrayList<>();
for(String v : splitRes){
intValues.add(Integer.parseInt(v));
}
return new Version(intValues);
}
}
You can write a Comparator to compare two Lists
Comparator<List<Integer>> comparator = (list1, list2) -> {
Iterator<Integer> iteratorA = list1.iterator();
Iterator<Integer> iteratorB = list2.iterator();
//It iterates through each list looking for an int that is not equal to determine which one precedes the other
while (iteratorA.hasNext() && iteratorB.hasNext()) {
int elementA = iteratorA.next();
int elementB = iteratorB.next();
if (elementA > elementB) {
return 1;
} else if (elementA < elementB) {
return -1;
}
}
//All elements seen so far are equal. Use the list size to decide
return iteratorA.hasNext() ? 1 : iteratorB.hasNext() ? -1 : 0;
};
You can sort it as
Collections.sort(list, comparator);
EDIT: You can refer to David Geirola's answer to convert the version string as a POJO and move the comparator logic inside that. But that is highly tied/coupled to the input string format. My solution works for any List<List<Integer>>.
A simple object oriented approach would be to create object, representing version number, let's call it VersionNumber, which would have a constructor of a factory method that does the parsing of the string. This VersionNumber class should implement interface Comparable and implement method compareTo.
Here is a hint for using Comparable Why should a Java class implement comparable?
Then you can easily write an algorithm to find the max version or google some library that would do it for you.
It is not optimized but should work. You can use both of comparators.
static List<String> versions = Arrays.asList(
"1_10_2_0_154",
"3_10_5_2_10",
"2_10_4_1_49",
"3_10_5_1_37");
static Comparator<List<Integer>> c = (o1,o2) -> {
int length = o1.size()>o2.size()?o2.size():o1.size();
for (int i = 0; i < length; i++) {
int i1 = o1.get(i);
int i2 = o2.get(i);
if (i1 != i2)
return i1 - i2;
}
return 0;
};
static Comparator<List<Integer>> c2 = (o1,o2) -> {
Iterator<Integer> i1=o1.iterator();
Iterator<Integer> i2=o2.iterator();
while (i1.hasNext() && i2.hasNext()){
int i = i1.next()-i2.next();
if (i!=0) return i;
}
return 0;
};
static Optional<List<Integer>> getTheMostRecentVersion(List<String> versions) {
return versions.stream().
map(s -> Arrays.stream(s.split("_")).
map(Integer::parseInt).
collect(Collectors.toList())).max(c2);
}
I think that this text file could be very big and it is better to compare each line on the fly (instead of store all line into collection to sort it after):
public static String getMostRecentVersion(BufferedReader in) throws IOException {
final Comparator<String[]> version = (s1, s2) -> {
int res = 0;
for (int i = 0; i < 5 && res == 0; i++)
res = Integer.compare(Integer.parseInt(s1[i]), Integer.parseInt(s2[i]));
return res;
};
String str;
String resStr = null;
String[] resPparts = null;
while ((str = in.readLine()) != null) {
String[] parts = str.split("_");
if (resStr == null || version.compare(parts, resPparts) > 0) {
resStr = str;
resPparts = parts;
}
}
return resStr;
}
A general ListComparator should help.
static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
#Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.max(o1.size(), o2.size()); i++) {
int diff =
// Off the end of both - same.
i >= o1.size() && i >= o2.size() ? 0
// Off the end of 1 - the other is greater.
: i >= o1.size() ? -1
: i >= o2.size() ? 1
// Normal diff.
: o1.get(i).compareTo(o2.get(i));
if (diff != 0) {
return diff;
}
}
return 0;
}
}
private static final Comparator<List<Integer>> BY_VERSION = new ListComparator<Integer>().reversed();
public void test(String[] args) {
String[] tests = {
"1_10_2_0_154",
"3_10_5_2_10",
"2_10_4_1_49",
"3_10_5_1_37",
"3_10_5_1_37_0"
};
System.out.println("Before: " + Arrays.toString(tests));
System.out.println("After: " + Arrays.stream(tests)
// Split into parts.
.map(s -> s.split("_"))
// Map String[] to List<Integer>
.map(a -> Arrays.stream(a).map(s -> Integer.valueOf(s)).collect(Collectors.toList()))
// Sort it.
.sorted(BY_VERSION)
// Back to a new list.
.collect(Collectors.toList()));
}
slap your arrays together into a number then just do number comparison.
class Scratch
{
public static void main(String[] args)
{
List<List<Integer>> arr = new ArrayList<>();
arr.add(fromArray(new Integer[]{1,10,2,0,154}));
arr.add(fromArray(new Integer[]{3,10,5,2,10}));
arr.add(fromArray(new Integer[]{2,10,4,1,49}));
arr.add(fromArray(new Integer[]{3,10,5,1,37}));
Integer[] maxLengths = {0,0,0,0,0};
for (List<Integer> v : arr)
{
for(int idx = 0; idx < v.size(); idx++)
{
Integer n = v.get(idx);
int curMaxLen = maxLengths[idx];
maxLengths[idx] = Math.max(n.toString().length(), curMaxLen);
}
}
Long largest = arr.stream().map(v -> {
StringBuilder result = new StringBuilder();
for(int idx = 0; idx < v.size(); idx++)
{
Integer n = v.get(idx);
int maxLen = maxLengths[idx];
result.append(String.format("%-" + maxLen + 's', n).replace(' ', '0'));
}
return result.toString();
}).map(Long::valueOf).max(Comparator.naturalOrder()).get();
System.out.println(largest);
}
public static List<Integer> fromArray(Integer[] array)
{
List<Integer> list = new ArrayList<>();
Collections.addAll(list, array);
return list;
}
}

All my objects change in my arraylist

I'm adding a new object(class) to an ArrayList, but when I try to get variables from the objects in my ArrayList, the variables are the same in all my classes. I've added a NEW object, so I expect it to add a new object, right?
This is my code in my for loop. The print says that every variable in the object[i] has the same number.
ArrayList treeDots;
ArrayList branchList;
boolean clicked;
void setup ()
{
size(1024, 768, P3D);
clicked = false;
treeDots = new ArrayList();
branchList = new ArrayList();
treeDots.add(new TreeDot(width/2, height/2));
}
void draw ()
{
if (clicked)
AddTreeDot();
if (treeDots.size() > 1)
{
for (int i = 0; i < treeDots.size() -1 ; i++)
{
int temp_loc = 0;
TreeDot index1 = (TreeDot)treeDots.get(i);
TreeDot index2 = (TreeDot)treeDots.get(i + 1);
print(index1.xLoc(temp_loc) + " ");
print(i + " ");
print(index2.xLoc(temp_loc) + " ");
print(i + " ");
strokeWeight(2);
stroke(#09FF00);
line(index1.xLoc(temp_loc),index1.yLoc(temp_loc), index2.xLoc(temp_loc), index2.yLoc(temp_loc));
}
}
}
void AddTreeDot ()
{
int randomX = 0;
int randomY = 0;
treeDots.add(new TreeDot(randomDotX(randomX), randomDotY(randomY)));
clicked = false;
}
int randomDotX (int _randomX)
{
TreeDot temp = (TreeDot) treeDots.get(treeDots.size() -1);
int temp_x_loc = 0;
int lastDotX = temp.xLoc(temp_x_loc);
_randomX = lastDotX + int(random(-10, 10));
return _randomX;
}
int randomDotY (int _randomY)
{
TreeDot temp = (TreeDot) treeDots.get(treeDots.size() -1);
int temp_y_loc = 0;
int lastDotY = temp.yLoc(temp_y_loc);
_randomY = lastDotY + int(random(0, 10));
return _randomY;
}
void mouseClicked ()
{
clicked = true;
}
and here is my class code
int randomSpread;
boolean canIGrow;
boolean endDot;
int x_loc;
int y_loc;
int lineThickness;
class TreeDot
{
TreeDot (int x_loc_par, int y_loc_par)
{
x_loc = x_loc_par;
y_loc = y_loc_par;
//ellipse(x_loc_par, y_loc_par, 10, 10);
endDot = false;
}
int xLoc (int _x_loc)
{
_x_loc = x_loc;
return _x_loc;
}
int yLoc(int _y_loc)
{
_y_loc = y_loc;
return _y_loc;
}
}
The problem that you have to declare variable inside the class & this code will be prblematic.
int xLoc(int _x_loc)
{
_x_loc = x_loc;
return _x_loc;
}
int yLoc(int _y_loc)
{
_y_loc = y_loc;
return _y_loc;
}
Then in call it
int temp_loc = 0;
TreeDot index1 = (TreeDot)treeDots.get(i);
TreeDot index2 = (TreeDot)treeDots.get(i + 1);
print(index1.xLoc(temp_loc) + " ");
print(i + " ");
print(index2.xLoc(temp_loc) + " ");
print(i + " ");
This line index1.xLoc(temp_loc) reset the value for you to 0.
Your TreeDot getters/setters are messed up. In xLoc() you are passing in _x_loc, making it equal to x_loc and return it. Same for yLoc()
Class variables should be declared inside the class.
What you're doing is you're setting the same (global) variables each time you add a new TreeDot.
P.S. your getters are not the problem as some of the answers are mentioning.

I am getting null values in my Array

I am playing around with an ArrayList and trying to get it to grow twice it's size every time it exceeds it's size. Here is my add method:
public class ArrayExpander
{
private int size;
private int noOfItems;
private Object[] store;
private final int INITIALSIZE = 2;
public ArrayExpander()
{
store = new Object[INITIALSIZE];
noOfItems = 0;
size = INITIALSIZE;
}
public void add(Object obj)
{
growBufferIfNecessary();
store[size++] = obj;
/*for (int i = size - 1; i < store.length; i++)
{
store[i] = store[i - 1];
store[i] = obj;
}*/
}
public String toString()
{
String temp = "[" + store[0];
for (int i = 1; i < size; i++)
{
temp = temp + "," + store[i];
}
temp = temp + "]";
return temp;
}
private void growBufferIfNecessary()
{
if (size == store.length)
{
Object[] newStore = new Object[2 * store.length];
for (int i = 0; i < store.length; i++)
{
newStore[i] = store[i];
}
store = newStore;
}
}
public static void main(String[] args)
{
ArrayExpander ae = new ArrayExpander();
//System.out.println(ae);
ae.add("a");
ae.add("b");
System.out.println(ae);
ae.add("c");
ae.add("d");
ae.add("e");
ae.add("f");
ae.add("g");
ae.add("h");
System.out.println(ae);
ae.add("i");
System.out.println(ae);
}
}
Here is my output:
[null,null]
[null,null,a,b]
[null,null,a,b,c,d,e,f,g,h]
[null,null,a,b,c,d,e,f,g,h,i]
I can't figure out why I am getting the null statements. The first line should be a,b and then the arraylist should double in size and be a,b,c,d. I have it set for final int INITIALSIZE = 2.
The output I am looking for is
[a,b]
[a,b,c,d]
[a,b,c,d,e,f,g,h]
[a,b,c,d,e,f,g,h,i,null,null,null,null,null,null,null]
This code will work for you. size should be referring to the size of your array while noOfItems refers to the number of items in your array. You were kind of mixing the 2 up. I only changed a couple things in your add() and growBufferIfNecessary().
public class ArrayExpander
{
private int size;
private int noOfItems;
private Object[] store;
private final int INITIALSIZE = 2;
public ArrayExpander()
{
store = new Object[INITIALSIZE];
noOfItems = 0;
size = INITIALSIZE;
}
public void add(Object obj)
{
growBufferIfNecessary();
store[noOfItems++] = obj;
}
public String toString()
{
String temp = "[" + store[0];
for (int i = 1; i < size; i++)
{
temp = temp + "," + store[i];
}
temp = temp + "]";
return temp;
}
private void growBufferIfNecessary()
{
if (noOfItems == size)
{
size = 2 * size;
Object[] newStore = new Object[size];
for (int i = 0; i < store.length; i++)
{
newStore[i] = store[i];
}
store = newStore;
}
}
public static void main(String[] args)
{
ArrayExpander ae = new ArrayExpander();
//System.out.println(ae);
ae.add("a");
ae.add("b");
System.out.println(ae);
ae.add("c");
ae.add("d");
ae.add("e");
ae.add("f");
ae.add("g");
ae.add("h");
System.out.println(ae);
ae.add("i");
System.out.println(ae);
}
}
Try this. If you notice I replaced size in a couple spots with noOfItems. You were really close you just needed to change a couple things.
Manually copying arrays with loops is such a pain, use System.arraycopy(Object,int,Object,int,int) like
private int size = 0;
private Object[] store = new Object[INITIALSIZE];
private void growBufferIfNecessary() {
if (size >= store.length) {
Object[] newStore = new Object[2 * store.length];
System.arraycopy(store, 0, newStore, 0, store.length);
store = newStore;
}
}
I eliminated noOfItems. You don't need it, your add method is just
public void add(Object obj) {
growBufferIfNecessary();
store[size++] = obj;
}
Finally, your toString() could use Arrays.copyOf(T[], int) like
#Override
public String toString() {
return Arrays.toString(Arrays.copyOf(store, size));
}
And then I got your expected output
[a, b]
[a, b, c, d, e, f, g, h]
[a, b, c, d, e, f, g, h, i]

Categories

Resources