compare between two queue list - java

I have two queue lists and I want to check if q2 is reverse for q1.
This is my code.
public static boolean reverse ( LinkedQueue q1, LinkedQueue q2 ) {
for ( int i = 0; i < q1.length() ; i ++)
if ( q1.serve () == q2.gettail().getdata() ) {
q1.enqueue(q1.serve ());
return true ;
} else {
return false;
}
return false;
}
I just check if the head of q1 equal the tail of q2 but my problem is I want to check for all elements that they are equal and I don't know how.

The way one normally approaches it is to return true in the end. Iterate through and only return false if i+n i+length-n.
Assuming everything else is working it will be like this.
public static boolean reverse ( LinkedQueue q1, LinkedQueue q2 ) {
for ( int i = 0; i < q1.length() ; i ++) {
if ( q1.serve () == q2.gettail().getdata() ) {
q1.enqueue(q1.serve ());
} else {
return false;
}
}
return true;
}
Note: You also missed curly brackets around your for.

Related

How to use a "Do While" loop to iterate through a list

public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
(JAVA only)
P.s This is a function i have tried, in order to check the first argument, and if it contains a number that is larger than the second argument, it will then return true, and flase otherwise.
Note that it is using do while loop. I just don't know which part of this code i have done wrong, because the system keeps telling me that "java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0".
Thank u, any hint will be much appriciated.
your list of Integers is empty. you can't access an index of an empty list:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
if (numbers.isEmpty()) return false;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
A do-while control block works as follows:
Execute the do block
Check the condition. If it holds, return to (1)
Notice the order of this flow. Unlike a standard while, do-while will always execute one iteration before checking the condition. Therefore, for an empty list you will always try to access the 0-index element of the table, which does not exist, hence the error. You can use a while loop to avoid this:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
while (d < numbers.size()) {
if (numbers.get(d) > number){
return true;
}
d++;
}
return false;
}
You should check whether the collection is empty
like this
if(numbers == null || numbers.isEmpty()) {
return false;
}
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;

Write a method that takes a string of curly brackets and returns true if the brackets match up and false if they don’t

I was working on this problem in CodeHS, where I have to write a method that takes a string of curly brackets and returns true if the brackets match up and false if they don’t.
this is my coding so far, and I do not know what to do when there's same amount of left curly bracket and right curly bracket, but those just does not match like ( }}{{ ) this for an example.
public boolean bracketsMatch(String brackets)
{
boolean result = true;
int leftCtr = 0 ; //"{";
int rightCtr =0 ; // "}";
int count = 0;
for (int i=0; i<brackets.length(); i++)
{
char c = brackets.charAt(i);
if ( c == '{')
{
leftCtr++;
}
if (c =='}')
{
rightCtr++;
}
}
if (rightCtr==leftCtr)
{
result= true;
}
else
{
return false;
}
return result;
}
Thank you
I think the easiest way is just to keep a single count, which you increment for an open bracket and decrement for a closed bracket. then use the following rules:
If the count is ever below 0, then it is invalid (i.e. a closing bracket that was never opened)
If at the end the count is not 0, then it is invalid (i.e. too many open brackets)
With that in mind your code would look like this:
public boolean bracketsMatch(String brackets)
{
int count = 0;
for (int i=0; i< brackets.length(); i++)
{
char c = brackets.charAt(i);
if ( c == '{')
{
count++;
}
else if (c =='}')
{
count--;
}
// Process the first rule.
// Check if we have a negative count (i.e. close bracket without a matching opener).
// If we have a negative then we know the string is invalid, so we can stop processing and return (false) early.
if (count < 0)
{
return false;
}
}
// Process the second rule.
// If we got this far then we know there are no invalid close brackets, so now we need to just check to make sure we didn't have too many open brackets.
// Return true if everything matching (i.e. 0), otherwise false.
return count == 0;
}
Already Musefan gave a brilliant answer. Here is an another implementation. Using Stack Data Structure.
public static boolean isBracketMatch(String str) {
Stack<Character> stack = new Stack<>();
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (c == '{')
stack.push('}');
else if (c == '}') {
if (!stack.empty() && stack.peek() == c)
stack.pop();
else
return false;
}
}
return stack.empty();
}

Recursively Find and Remove Node from LinkedList

Given a string to search for, I want to write a recursive function that takes in only one parameter (The string to search for). The function will search for the value recursively and if it is found then it will remove the item and return it. If it is not found then, the function will reach the end of the list and return null. What I have so far I think is the right idea except it is not functioning properly:
Main Test Class
public static void main(String[] args) {
RecLinkedList list = new RecLinkedList();
list.add("A");
list.add("B");
list.add("D");
list.add("C", 2);
list.add("E", 4);
list.add("G", 6); //this should be invalid
System.out.println( list );
System.out.println( list.remove( 1 ).getValue() );
System.out.println( list.remove("D").getValue() );
System.out.println( list.remove("G").getValue() );
System.out.println( list.size() );
System.out.println( list );
}
Linked List Class (Showing only what I need help on)
public class RecLinkedList {
private Node first;
private int size = 0;
public RecLinkedList(){
first = null;
}
public boolean isEmpty() {
return first == null;
}
public Node remove( String s ){
return remove( s, 0, first );
}
private Node remove( String s, int count, Node list ){
if( list == null ){
return null;
}else if( s.equals(s) ){
first = list.getNext();
return list;
}else if( s.equals(count+1) ){
Node n = list.getNext();
if( list.getNext() != null ){
list.setNext( list.getNext().getNext() );
}
return n;
}else{
return remove( s, count+1, list.getNext() );
}
}
So far, I am able to remove the item but as of now the item "A" is getting removed when it should not be. The final list should be A,C,E. (G should return and print null because it does not exist). I think I am close, but off by something minor, but I can not seem to figure it out.
There are several errors in your code (see comments below) :
private Node remove( String s, int count, Node list ){
if( list == null ){
return null;
}else if( s.equals(s) ){ // comparing s to itself means you always remove
// the first element from the list (since this
// condition is always true)
first = list.getNext();
return list;
}else if( s.equals(count+1) ){ // comparing the String s to an int - makes
// no sense, will never be true
Node n = list.getNext();
if( list.getNext() != null ){
list.setNext( list.getNext().getNext() );
}
return n;
}else{
return remove( s, count+1, list.getNext() );
}
}
It seems to me like there is some ambiguity in your question. I understand that your method should search for an element, remove it if present, and return the same object. If the element is not present, the method should return null. That seems pretty straight-forward since most of your utility methods are already implemented in LinkedList. I thus recommend to extend that class:
public class RecLinkedList<E>
extends LinkedList<E>
{
public E removeAndReturn(E element)
{
E result;
if (this.contains(element)) {
remove(element);
result = element;
}
else {
result = null;
}
return result;
}
}
I don't see why you would want to implement this recursively.
This could clearly be written more concisely, but the explicit if-else should make it clearer.
EDIT: The more concise and probably better implementation would be:
public E removeAndReturn(E element)
{
return remove(element) ? element : null;
}

Methods that return boolean values

Okay, so my question is regarding boolean returns. For my Comp Sci homework, I have to make a course registration program using methods, and one of them is an add course method. Basically, you search for the class in a catalog, and if it matches you add it to the students schedule and return a boolean value of true. I did this, but for some reason it is giving me an error. Here is the code:
public static boolean addCourse(
Course[] catalog,
Course[] mySchedule,
int myNumCourses,
int dept,
int courseNum)
{
int j;
int i;
int k;
int deptCat;
int courseNumCat;
Course courseAdd = null;
char checkDay;
int checkTime;
if (mySchedule.length == myNumCourses) {
return false;
}
for (i = 0 ; i < catalog.length ; i++) {
Course course = catalog[i];
deptCat = course.getDepartment();
courseNumCat = course.getCourseNumber();
if (deptCat == dept && courseNumCat == courseNum) {
courseAdd = catalog[i];
break;
}
else continue; }
for (j = 0 ; j < myNumCourses ; j++) {
if (mySchedule[j] == null) {
mySchedule[j] = courseAdd;
return true;
}
else continue;
}
for (k = 0 ; k < mySchedule.length ; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay() && checkTime == courseAdd.getPeriod()) {
return false;
}
}
else continue;
}
}
Why doesn't it recognize the boolean return values? Is it because I placed them inside a loop?
You need to place a return-statement at the end of your method, even if you might know it will never be reached (the compiler is not smart enough to know that, which explains the error).
For instance, even this will not compile:
public static boolean foo() {
if (true)
return true;
}
unless we add a final return statement. What you have is analogous.
There is nothing wrong with putting your return values in loops, however, the compiler sees no guarantee that this method will return a value and thus raises an error. At the very end of the method you need to return either true or false, whichever is most appropriate. All of your returns are within conditionals and therefor could fail to execute leaving your function with no return statement.
You must explicitly return a boolean(true/false) in ALL code path.Because your function's return type is "boolean".
In your case,you must add a return statement after the last loop.
If you don't want to write to many "return xx" statement,you can change the return type of this function to "void".And throw Exception in the false cases.
I think there is a problem with the last loop. If the condition for returning false is never met, it continues until it get to the end of the schedule, without returning anything. If you were to add a return at the end of the method this loop could fall through to it. Did you mean to return true after the loop, if no 'return false' is executed?
for (k = 0; k < mySchedule.length; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay()
&& checkTime == courseAdd.getPeriod()) {
return false;
}
} else
continue;
}
Where ever you are using if statement its possible else also must return or flow must go to another return.ELSE is missing with return.

Problems getting into an "if" statement, JAVA

I've got a program that goes through and reads "tokens" that can either be a String (Symbol) or a number. It uses postfix and a stack to evaluate simple commands.
For example:
/x 100 def
/y 200 def
x y add
should return 300. The first line defines a variable called "x" and sets it to 100. To do this a reader adds "/x" and "100" on the stack and stops when it gets to the "def" operator, which tells it to go make a token with a Symbol called "x" and its value being 100. The stack is then empty, and next time "x" would be pushed, the interpreter should automatically replace it with its value. This is where my problem lies.
This is my interpreter:
while ( r.hasMoreTokens() ) {
Token t = r.nextToken();
if ( !t.isSymbol() ) {
operands.push( t );
} else if (env.contains(t.getSymbol())) {
Token tmp = env.get(t.getSymbol());
operands.push(tmp);
} else if (t.getSymbol().startsWith("/")) {
operands.push(t);
} else if ( t.getSymbol().equals( "def" ) ){
execute_def();
} else if ( t.getSymbol().equals( "add" ) ) {
execute_add();
} else if ( t.getSymbol().equals( "sub" ) ) {
execute_sub();
} else if ( t.getSymbol().equals( "mul" ) ) {
execute_mul();
} else if ( t.getSymbol().equals( "exch" ) ) {
execute_exch();
} else if ( t.getSymbol().equals( "dup" ) ) {
execute_dup();
} else if ( t.getSymbol().equals( "pop" ) ) {
execute_pop();
} else if ( t.getSymbol().equals( "pstack" ) ) {
execute_pstack();
} else if ( t.getSymbol().equals( "moveto" ) ) {
execute_moveto();
} else if ( t.getSymbol().equals( "lineto" ) ) {
execute_lineto( g );
} else if ( t.getSymbol().equals( "arc" ) ) {
execute_arc( g );
} else if ( t.getSymbol().equals( "quit" ) ) {
execute_quit();
} else {
System.out.println( "ILLEGAL SYMBOL: " + t );
}
}
Once the variables get defined correctly, I cant get into that first else if and change the value. Because I can't do this, I never push anything on the stack and end up with an empty stack error. Here are the methods contains() and get() from env (environment):
public boolean contains(String key) {
Elem tmp = top;
for (int i = 0; i < size; i++) {
if (tmp.key == key) {
return true;
} else {
tmp = tmp.next;
}
}
return false;
}
public Token get(String key) {
Elem tmp = top;
int counter = 0;
boolean found = false;
for (int i = 0; i < size; i++) {
if (tmp.key == key) {
found = true;
break;
} else {
tmp = tmp.next;
}
counter++;
}
if (found == true) {
tmp = top;
for (int i = 0; i <= counter; i++) {
tmp = tmp.next;
}
return tmp.value;
} else {
throw new BadKeyQueryException();
}
}
I'm using linked elements in the environment to keep track of symbols. Elem is a nested class in Environment:
private static class Elem {
private String key;
private Token value;
private Elem next;
private Elem(String key, Token value, Elem next) {
this.key = key;
this.value = value;
this.next = next;
}
}
Thanks for any help from you guys!
Strings in java are Objects, rather than primitives.
When you say:
int i = 5;
i stores the value "5".
When you say:
String s = "string";
s stores the value of a reference to "string".
Comparing s to "string" would return false, even though they contain the same value when you print there. This is because the computer compares a reference to memory containing "string" to another reference to memory containing "string". Same values, but different references.
Also, you're setting "t" to multiple different values in your code. Try setting t once, before everything, and a precomputed t value against your if-else-if block.
You can only call getSymbol() once, so you just need to store the value from it. Here is the start of your statements, you should be able to change the others the same way
if ( !t.isSymbol() ) {
operands.push( t );
continue;
}
String symbol = t.getSymbol();
if (env.contains(symbol)) {
Token tmp = env.get(symbol);
operands.push(tmp);
} else if (symbol.startsWith("/")) {
operands.push(t);
...

Categories

Resources