ADT LinkedList intersecting set error - java

I have a test code for an ADT of LinkedList, which implements interface NumList.java, and is implemented in a NumLinkedList.java, and am using it in a NumSet.java.
I am trying to make it so that my NumSet has methods where I can create a set from a double array input, and use intercept/union and print methods to use and print the data.
but my test code is showing that my test NumSet values are empty, namely testProof and testProof2.
So now my testProof is returning an empty variable, which means nothing is saving into it.
static public NumSet intersect(NumSet S1, NumSet S2) //check 2nd for and if//
{
NumSet intersectAnswer = new NumSet();
for (int i = 0; i < S1.set.size()-1; i++)
{
for(int j = 0; j < S2.set.size()-1; j++)
{
double FUZZ = 0.0001;
if (Math.abs(S1.set.lookup(i) - S2.set.lookup(j)) < FUZZ) // double values, this is more precise than ==.
{
intersectAnswer.set.insert(1, S1.set.lookup(i));
}
}
}
return intersectAnswer;
}
is the method for testProof, and the following is where testProof is defined.
public static void main(String[] args)
{
double[] a = {1.3,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.05};
NumArrayList test;
test = new NumArrayList();
test.printTest(); //runs test code in NumList
//ok below is running. what is wrong with intersect?
NumSet test2;
test2 = new NumSet(a);
NumSet test4;
test4 = new NumSet(b);
NumSet testProof;
NumSet testProof2;
test2.print(); //print out test 2
System.out.println();
test4.print();
System.out.println();
testProof = intersect(test2,test4);
I have initialized as
public class NumSet
{
private NumList set;
public NumSet(double[] sth)
{
//moves elements of sth into set.
set = new NumLinkedList();
for(int i = 0; i < sth.length; i++)
{
set.insert(0,sth[i]);
}
set.removeDuplicates();
}
public NumSet()
{
set = new NumLinkedList();
}
int numSet = 0;
and my intercept, union and print are below:
public NumSet intersect(NumSet S1, NumSet S2) //check 2nd for and if//
{
NumSet intersectAnswer = new NumSet();
for (int i = 0; i < S1.set.size()-1; i++)
{
for(int j = 0; j < S2.set.size()-1; j++)
{
if (S1.set.lookup(i) == S2.set.lookup(j))
{
intersectAnswer.set.insert(0, S1.set.lookup(i));
}
}
}
// intersectAnswer.set.removeDuplicates(); unnecessary, sets are already removed of duplicates
return intersectAnswer;
}
public NumSet union(NumSet S1, NumSet S2)
{ //check logic.
NumSet unionAnswer = new NumSet();
for (int i = 1; i < S1.set.size()+1; i++)
{
unionAnswer.set.insert(1, S1.set.lookup(i));
}
for (int i = 1; i < S2.set.size()+1; i++)
{
unionAnswer.set.insert(1, S2.set.lookup(i));
}
unionAnswer.set.removeDuplicates();
return unionAnswer;
}
public void print()
{
for (int i = 0; i < set.size()-1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()-1));
}
the lookup and size are referred to from my NumLinkedList.java and are as below
public int size() // measure size of list by counting counter++;
{
return nItem;
}
public double lookup(int i)
{
if( i <0 || i >= size()) //cannot lookup nonexistant object
{
System.out.println("out of bounds " + i + " < 0 or > " + size() );
//how do I break out of this loop?
System.out.println("just returning 0 for the sake of the program");
return 0;
}
if(i == 0)
{
return head.value;
}
double answer = 0;
Node currNode = head;
for(int j = 0; j < i+1; j++) //move to ith node and save value
{
answer = currNode.value;
currNode = currNode.next;
}
return answer;
}
and finally my test code is as below, where testProof and testProof2 are.
public static void main(String[] args)
{
double[] a = {1.3,2,3,4,101.9};
double[] b = {3,7,13,901,-29.1,0.05};
NumArrayList test;
test = new NumArrayList();
test.printTest(); //runs test code in NumList
//ok below is running. what is wrong with intersect?
NumSet test2;
test2 = new NumSet(a);
NumSet test4;
test4 = new NumSet(b);
NumSet testProof;
NumSet testProof2;
test2.print();
System.out.println();
testProof = test2.intersect(test2, test4);
System.out.println("tried intersect");
testProof.print();
System.out.println();
System.out.println("tried test.print()");
testProof2 = test2.union(test2,test4);
System.out.println("tried union");
testProof2.print();
System.out.println();
System.out.println("NumSet ran fully.");

I'd suggest you implement you NumSet Class with integer values rather than double values while you debug because comparing two double values tends to add some unneeded complexity to your code at this debug stage.
You might want to look at your removeDuplicates() method, I think that might hold the answer to your problem. Unfortunately I don't see it within the code you posted.
Actually, this part of code within the intersect() method is destined to fail from the start,
if (S1.set.lookup(i) == S2.set.lookup(j))
Because of your use of doubles, == is a very imprecise method of comparing two different values, a better way would be to allow for a certain amount of precision error, i.e.
double final FUZZ = 0.0001
if (Math.abs(S1.set.lookup(i) - S2.set.lookup(j)) < FUZZ )
//...

Related

Finite State Machine Program invalid output

I am working on a project and my code isn't working not sure why. Given the test program and general class I need a program that satisfies the following logical regular epxression:
L1: For alphabet {a,b}, all strings that contain an odd number of a's and exactly one b.
Test input: aabaaaa, aaabaaaa, aabaaaab, baaaaaa, aaaaabaa
What it should be:
aabaaaa False
aaabaaaa True
aabaaaab false
baaaaaa false
aaaaabaa True
Program output:
(ture, true, true, false, true)
My Test program:
import java.util.Scanner;
// Test Finite State Machine Class
public class TestFSML1
{
public static void main(String[] args){
String A = "ab";
int[][] ST = {{1,3,0},
{1,2,1},
{2,2,2},
{3,3,3}};
int[] AS = {0,0,1,0};
Scanner in = new Scanner(System.in);
String inString;
boolean accept1 = false;
FSM FSM1 = new FSM(A, ST, AS);
// Input string is command line parameter
System.out.println(" Input Accepted:");
for(int i=0;i<args.length;i++) {
inString = args[i];
accept1 = FSM1.validString(inString);
System.out.printf("%10s%13s\n",inString, accept1);
}
} // end main
} // end class
FSM Class
// Finite State Machine Class
public class FSM
{
// Instance variables
public String alphabet;
public int stateTrans[][];
public int acceptState[];
private int cstate;
// Constructor function
public FSM(String A, int[][] ST, int[] AS)
{
int NSYMBOLS = A.length();
int NSTATES = AS.length;
// Alphabet
alphabet = "" + A;
// State transition table
stateTrans = new int[NSTATES][NSYMBOLS];
for(int r = 0; r < NSTATES; r++)
for(int c = 0; c < NSYMBOLS; c++)
stateTrans[r][c] = ST[r][c];
// Accept states
acceptState = new int[NSTATES];
for(int r = 0; r < NSTATES; r++)
acceptState[r] = AS[r];
// Start state
cstate = 0;
}
// Methods
public int getState()
{
return cstate;
}
public void setState(int state)
{
cstate = state;
return;
}
public int nextState(char symbol)
{
int nstate = -1;
int col = alphabet.indexOf(symbol);
if(col >= 0)
nstate = stateTrans[cstate][col];
return nstate;
}
public boolean accept(int state)
{
if(state < 0)
return false;
return (acceptState[state] != 0);
}
public boolean validString(String word)
{
cstate = 0;
for(int k = 0; k < word.length(); k++){
cstate = nextState(word.charAt(k));
System.out.print(cstate);
System.out.println(" " + word.charAt(k));
if(cstate < 0)
return false;
}
return accept(cstate);
}
} // end class
Thanks!
Here's a simple method I typed up to perform the task you wanted.
public static boolean validWord(String s) {
int aCounter = 0;
int bCounter = 0;
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ((int) c == (int) 'a') {
aCounter++;
} else {
bCounter++;
}
}
return (aCounter % 2 == 1 && bCounter == 1);
}
I had trouble understanding how you were implementing your method, and I think it could be much simpler. I'm sure the instance variables you included in the FSM class serve some other use, but I you don't really need any of them to analyze the string. Just use something like this, it should be easy enough to integrate into your code as all it takes is the string. Hope this helps!

Cannot Print Void Method from Main

I made a main method, insertion sort and want it to print out properly in my tester class. I know that it cannot print because its a void method using arrays and I need it to be a string to print, I'm just not sure what to edit in my method or my print line to make it feasible.
METHOD
public static void insertionSort(String[] inputList)
{
OrderStrings c = new OrderStrings();
for (int i = 1; i < inputList.length; i++)
{
String index = inputList[i];
int j = i;
while ( j > 0 && c.compare((sort(inputList[j])), sort(inputList[j-1])) > 0)
{
inputList[j] = inputList[j-1];
j--;
}
inputList[j] = index;
}
}
TESTER
#Test
public void testInsertionSort()
{
AnagramUtil insertionTest = new AnagramUtil();
String[] test2 = { "ComputerScience" };
System.out.print("Testing Insertion Sort");
System.out.println();
System.out.println(insertionTest.insertionSort("sorted" + test2);
//the above is the line that will not print
//it says "- The method insertionSort(String[]) in the type AnagramUtil is not applicable for the arguments(String)"
}

Writing an equals method to compare two arrays

I have the following code, I believe something is off in my equals method but I can't figure out what's wrong.
public class Test {
private double[] info;
public Test(double[] a){
double[] constructor = new double[a.length];
for (int i = 0; i < a.length; i++){
constructor[i] = a[i];
}
info = constructor;
}
public double[] getInfo(){
double[] newInfo = new double[info.length];
for(int i = 0; i < info.length; i++){
newInfo[i] = info[i];
}
return newInfo;
}
public double[] setInfo(double[] a){
double[] setInfo = new double[a.length];
for(int i = 0; i < a.length; i++){
setInfo[i] = a[i];
}
return info;
}
public boolean equals(Test x){
return (this.info == x.info);
}
}
and in my tester class I have the following code:
public class Tester {
public static void main(String[] args) {
double[] info = {5.0, 16.3, 3.5 ,79.8}
Test test1 = new Test();
test 1 = new Test(info);
Test test2 = new Test(test1.getInfo());
System.out.print("Tests 1 and 2 are equal: " + test1.equals(test2));
}
}
the rest of my methods seem to function correctly, but when I use my equals method and print the boolean, the console prints out false when it should print true.
You are just comparing memory references to the arrays. You should compare the contents of the arrays instead.
Do this by first comparing the length of each array, then if they match, the entire contents of the array one item at a time.
Here's one way of doing it (written without using helper/utility functions, so you understand what's going on):
public boolean equals(Test x) {
// check if the parameter is null
if (x == null) {
return false;
}
// check if the lengths are the same
if (this.info.length != x.info.length) {
return false;
}
// check the elements in the arrays
for (int index = 0; index < this.info.length; index++) {
if (this.info[index] != x.info[index]) {
return false;
} Aominè
}
// if we get here, then the arrays are the same size and contain the same elements
return true;
}
As #Aominè commented above, you could use a helper/utility function such as (but still need the null check):
public boolean equals(Test x) {
if (x == null) {
return false;
}
return Arrays.equals(this.info, x.info);
}

Java Why am I getting a NullPointerException while instantiating my array

I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}
Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]
When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.
You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}

Using Arrays.sort, empty array returned

I'm using the Arrays.sort method to sort an array of my own Comparable objects. Before I use sort the array is full, but after I sort the array and print it to System nothing is printing out. EDIT. the array prints nothing at all. not empty line(s), just nothing.
here is the code for my method which uses sort :
public LinkedQueue<Print> arraySort(LinkedQueue<Print> queue1)
{
Print[] thing = new Print[queue1.size()];
LinkedQueue<Print> newQueue = new LinkedQueue<Print>();
for(int i = 0; i <queue1.size(); i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}
Arrays.sort(thing);
for(int j = 0;j<thing.length-1;j++)
{
System.out.println(thing[j]); //printing does not work here
newQueue.enqueue(thing[j]);
}
return newQueue;
}
and here is the class for the Comparable object called Print.
public class Print implements Comparable<Print>
{
private String name;
private int numPages,arrivalTime,startTime,endTime;
public Print(String n, int p, int time, int sTime, int eTime)
{
name = n;
numPages = p;
arrivalTime = time;
startTime = sTime;
endTime = eTime;
}
public int getPages()
{
return numPages;
}
public int compareTo(Print other)
{
if(this.getPages()<other.getPages())
return -1;
else if(this.getPages()>other.getPages())
return 1;
else
return 0;
}
public String toString()
{
return name+"("+numPages+" pages) - printed "+startTime+"-"+endTime+" minutes";
}
}
Your last for loop doesn't print the last element in the array. If the array has only one element, it won't print anything at all. Change to:
for (int j = 0; j < thing.length; j++) //clean code uses spaces liberally :)
{
System.out.println(thing[j]);
newQueue.enqueue(thing[j]);
}
or (if supported by the JDK/JRE version used):
for (Print p : thing)
{
System.out.println(p);
newQueue.enqueue(p);
}
I hope the problem is this part of code
for(int i = 0; i <queue1.size(); i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}
replace the above with
for(int i = 0; !queue1.isEmpty() ; i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}

Categories