Check that every if has a matching endif - java

I recently had to code up an interpreter for Bitcoin's script language; part of this involved coming up with an algorithm to check that the control flow in a given script made sense (i.e. every OP_IF had a matching OP_ENDIF, every OP_ELSE and OP_ENDIF had a matching OP_IF, etc.).
This is what I came up with:
public class if_else_checker {
public static boolean search(String[] commands, String[] tracker, int if_index) {
boolean seenElse = false;
for (int i = if_index; i < commands.length; i++) {
if (commands[i].equals("OP_ELSE")) {
if (seenElse == true && tracker[i] == null) return false;
if (tracker[i] == null) {
tracker[i] = "OP_ELSE";
seenElse = true;
}
}
else if (commands[i].equals("OP_ENDIF")) {
if (tracker[i] != null && tracker[i].equals("OP_ENDIF"))
{
continue;
}
tracker[i] = "OP_ENDIF";
return true;
}
else if (commands[i].equals("OP_IF")) {
if (tracker[i] != null && tracker[i].equals("OP_IF")) {
continue;
}
tracker[i] = "OP_IF";
if (search(commands, tracker, i + 1) == false) return false;
}
}
return false;
}
public static boolean validate(String[] args)
{
String[] tracker = new String[args.length];
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("OP_IF"))
{
if (tracker[i] == null || !tracker[i].equals("OP_IF"))
{
tracker[i] = "OP_IF";
if (search(args, tracker, i + 1) == false) return false;
}
else continue;
}
else if (args[i].equals("OP_ELSE"))
{
if (tracker[i] == null || !tracker[i].equals("OP_ELSE")) return false;
}
else if (args[i].equals("OP_ENDIF"))
{
if (tracker[i] == null || !tracker[i].equals("OP_ENDIF")) return false;
}
}
return true;
}
public static void main(String[] args)
{
System.out.println(validate(args));
}
}
It works, but I was wondering if there is a way to optimise it/if there is a standard way of doing this? (One optimisation is to have validate() return the index of the OP_ENDIF it finds, rather than a boolean; this would change runtime from quadratic-time to linear).

The best way of solving this is by using a Stack data structure. Every new opening instruction (e.g. OP_IF) is pushed into the stack. When you find a closing instruction (e.g. OP_ENDIF), you pop the top element of the stack and check if it is the corresponding opening instruction for that closing instruction. If so, then it's valid, and you proceed to the next step. In the end, if the stack is empty then the control flow you're checking is correct. Otherwise, it's not.

Related

Fatal Exception: java.lang.IllegalArgumentException: Comparison method violates its general contract

I know there many similar questions and I have received big help by reading answers to those questions, however I am not able to see how is my client facing this problem. And there is only one client who is facing this problem.
I have a List, and I am sorting that list using Comparator interface. Does any of you see problem with the following code?
private static class BiologySamplesComparator implements Comparator<BiologySample>, Serializable {
#Override
public int compare(BiologySample left, BiologySample right) {
if (left == right || (left != null && right != null && left.getSampleDateTime() == right.getSampleDateTime())) {
return 0;
}
if (left == null || left.getSampleDateTime() == null) {
return 1;
}
if (right == null || right.getSampleDateTime() == null) {
return -1;
}
return right.getSampleDateTime().compareTo(left.getSampleDateTime());
}
}
And this how I am calling this function
Collections.sort(biologySamples, new BiologySamplesComparator());
I know that the main problem in this kind of scenario is Transitivity. However I couldn't figure what is violating that rule.
This how getSampleDateTime() is returning date Fri Apr 09 17:00:00 PDT 2021
Update
This is how I was able to fix my problem.
I hope this helps, I was stuck for so long on this problem.
private static class BiologySamplesComparator implements Comparator<BiologySample>, Serializable {
#Override
public int compare(BiologySample left, BiologySample right) {
if (left == null) {
if (right == null) {
return 0;
} else {
return 1;
}
} else if (right == null) {
return -1;
} else if (left == right) {
return 0;
}
if (left.getSampleDateTime() == null) {
if (right.getSampleDateTime() == null) {
return 0;
} else {
return 1;
}
} else if (right.getSampleDateTime() == null) {
return -1;
} else if (left.getSampleDateTime() == right.getSampleDateTime()) {
return 0;
}
return right.getSampleDateTime().compareTo(left.getSampleDateTime());
}
}
You have a possible inconsistency when comparing a null "sample" to a non-null sample with a null timestamp.
Sample a = null;
Sample b = new Sample(null);
bsc.compare(a, b); // -> 1, a > b
bsc.compare(b, a); // -> 1, b > a
First, you should replace the Date in your sample class with Instant if at all possible, and then make your life simpler by saying this:
public static final Comparator<Sample> ORDER_BY_TIMESTAMP =
Comparator.nullsLast(Comparator.comparing(
Sample::getDateTime,
Comparator.nullsLast(Comparator.naturalOrder())
);
If you can rule out null values, even simpler:
Comparator.comparing(Sample::getDateTime);
I was missing some conditional for some cases and this is how I was able to solve my problem.
private static class BiologySamplesComparator implements Comparator<BiologySample>, Serializable {
#Override
public int compare(BiologySample left, BiologySample right) {
if (left == null) {
if (right == null) {
return 0;
} else {
return 1;
}
} else if (right == null) {
return -1;
} else if (left == right) {
return 0;
}
if (left.getSampleDateTime() == null) {
if (right.getSampleDateTime() == null) {
return 0;
} else {
return 1;
}
} else if (right.getSampleDateTime() == null) {
return -1;
} else if (left.getSampleDateTime() == right.getSampleDateTime()) {
return 0;
}
return right.getSampleDateTime().compareTo(left.getSampleDateTime());
}
}
courtesy of Why does my compare methd throw IllegalArgumentException sometimes?

How to java Program to Check if an array contains a given two different values?

I want to write a code to check the existence of given two values in a List.
List<Tag> tags = new ArrayList<>();
The requirement is to return true only if the List tag contains both "start" and "end" values.
My code is like this, but it doesn't cater to the requirement.
public static boolean checkStartAndEndTimeTag(List<Tag> tags) {
boolean isSuccess = false;
int count = 0;
for (Tag tag : tags) {
if (tag.getKey().equals("start") || tag.getKey().equals("end")) {
count++;
if (count == 2)
break;
isSuccess = true;
}
}
return isSuccess;
Can someone help me with to resolve this issue?
This...
if (count == 2)
break;
isSuccess = true;
doesn't make sense. This will set isSuccess even if there is only one match
The long winded approach
Okay, let's assuming for a second that you only care if there is at least one start and one end (discounting duplicates). One approach would be to use to state flags, one for start and one for end. To keep it simple, they would start of as 0 but would only ever be a maximum of 1 (because we don't want duplicates), then you might be able to do something like...
public static boolean checkStartAndEndTimeTag(List<Tag> tags) {
boolean isSuccess = false;
int starts = 0;
int ends = 0;
for (Tag tag : tags) {
if (tag.getKey().equals("start")) {
starts = 1;
} else if (tag.getKey().equals("end")) {
ends = 1;
}
}
isSuccess = (starts + ends) == 2;
return isSuccess;
}
Ok, you don't need isSuccess = (starts + ends) == 2; and could simply return the result of the comparison. You could also break out of the loop if (starts + ends) == 2 and save yourself from unnecessary computation
for (Tag tag : tags) {
if (tag.getKey().equals("start")) {
starts = 1;
} else if (tag.getKey().equals("end")) {
ends = 1;
}
if ((starts + ends) == 2) {
break;
}
}
Using streams...
One approach might be to make use the streams support and simply filter the List and count the results, for example...
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
List<Tag> tags = new ArrayList<Tag>(25);
tags.add(new Tag("begin"));
tags.add(new Tag("front"));
tags.add(new Tag("start"));
tags.add(new Tag("finish"));
tags.add(new Tag("tail"));
tags.add(new Tag("end"));
boolean isSuccessful = tags.stream().filter(tag -> tag.getKey().equals("start") || tag.getKey().equals("end")).count() >= 2;
System.out.println(isSuccessful);
}
public class Tag {
private String key;
public Tag(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
}
Updated...
Okay, this got complicated fast. Let's assume you don't want to match two start tags, so you MUST have both one end and one start tag
So, using the above, example, we can modify the Tag class to support equals (and by extension hashcode)
public class Tag {
private String key;
public Tag(String key) {
this.key = key;
}
public String getKey() {
return key;
}
#Override
public String toString() {
return getKey();
}
#Override
public int hashCode() {
int hash = 7;
hash = 73 * hash + Objects.hashCode(this.key);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Tag other = (Tag) obj;
if (!Objects.equals(this.key, other.key)) {
return false;
}
return true;
}
}
Then we can simply use distinct to filter out any duplicates, for example...
boolean isSuccessful = tags
.stream()
.distinct()
.filter(tag -> tag.getKey().equals("start") || tag.getKey().equals("end"))
.count() >= 2;
Probably not the most efficient solution, but certainly one of the shortest
In this code
if (tag.getKey().equals("start") || tag.getKey().equals("end")) {
count++;
if (count == 2)
break;
isSuccess = true;
}
you are setting isSuccess to true whenever the tag is start or end.
Better way would be
if (tag.getKey().equals("start") || tag.getKey().equals("end")) {
count++;
if (count == 2)
return true;
}
You could also use
tags.stream()
.map(Tag::getKey)
.distinct()
.filter(t -> "start".equals(t) || "end".equals(t))
.count() == 2;
This would also fix the issue that your original code falsely returns true if the list contains statt or end twice.
What about
tags.containsAll(Arrays.asList(new Tag("start"), new Tag("stop")))

Printing datastructure from input doesn't work

I'm trying to create a program which prints a datastructure from the input. The input and output looks like this: http://puu.sh/kDMc9/2d46462d4d.png. So for example, in the first test case: the first line indicates how many lines will follow in that case. Then if it's the number 1 as the first number on a line it means that you want to add elements to stack/queue/priority-queue and 2 means you want to take out an element, so the second number on a line is the value. Then the output prints if it's stack,queue, priority-queue, impossible or not sure(can be more than one)
This is the code I have now:
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
But when I run the test-case on the picture above, my program prints this: https://ideone.com/mIO1bs which is wrong. I can't find why it does that, can anyone else here maybe see?
Assuming that your logic setting the boolean flags is correct then this part
if(stackBool == true)
{
System.out.println("stack");
}
...
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
will never work as intended because parts of the second condition were already caught by the first condition.
The better suggestion is to come up with a clearer way of representing this. A suggestion that will still probably work is to put your more complicated if statements at the start of the if-else chain.
Disregarding above assumption:
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
These should not be elses, they're all completely independent.

Why is my break statement being ignored?

In my method under the if statement:
if (currentLocationX == 0 && currentLocationY == 4)
I have a break statement that should make the program exit out of the while loop and return true for 'answer' and for the method. Yet after some testing it seems that after returning true for 'answer', it goes back into the while loop giving the wrong results int the end. Why is my break statement not doing what it's supposed to? Thank you!
P.S. (this method calls on some other method that were not relevant to mention here)
public boolean solveMaze()
{
boolean answer = false;
int currentLocationX;
int currentLocationY;
//push starting location
pushX(2);
pushY(1);
while((isEmptyX() == false) && (isEmptyY() == false))
{
printMaze();
System.out.println();
currentLocationX = popX();
currentLocationY = popY();
//mark current location as visited
visited(currentLocationX, currentLocationY, maze);
System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);
if (currentLocationX == 0 && currentLocationY == 4)
{
answer = true;
break;
}
else
{
//push all unvisited OPEN neighbor locations into stack
if (checkEast(currentLocationX, currentLocationY) == 0)
{
pushX(eastX(currentLocationX));
pushY(eastY(currentLocationY));
}
else;
if (checkSouth(currentLocationX, currentLocationY)== 0)
{
pushX(southX(currentLocationX));
pushY(southY(currentLocationY));
}
else;
if (checkWest(currentLocationX, currentLocationY)== 0)
{
pushX(westX(currentLocationX));
pushY(westY(currentLocationY));
}
else;
if (checkNorth(currentLocationX, currentLocationY)== 0)
{
pushX (northX(currentLocationX));
pushY(northY(currentLocationY));
}
else;
}
}
return answer;
}
I wrote out the basic logic of your method as
public static boolean solveMaze() {
boolean answer = false;
int currentLocationX = 0;
int currentLocationY = 4;
while (true) {
if (currentLocationX == 0 && currentLocationY == 4) {
System.out.println("Hit the break");
break;
} else {
System.out.println("Missed the break");
}
}
return answer;
}
and if you execute it you get Hit the break. So your solveMaze() method is fine in terms of breaking out of the loop once it satisfies your if-statement. I would say that if you see your code subsequently going back into the while loop, it must be that solveMaze() was called a second time.

Why is this not returning true?

public void check() {
if (particle < 0) {
if (point[3].equals(point[3]) == true) {
check = true;
}
check = false;
}
}
Shouldn't point[3] be equal to itself? making it true?
Maybe you mean to say else check = false?
public void check(){
if(particle < 0){
if(point[3].equals(point[3]) == true){
check = true;
}else{
check = false;
}
}
//here it is true
}
or simply:
public void check(){
if(particle < 0){
check = point[3].equals(point[3]);
}
//here it is true
}
You must return after check = true; from the function, or use else. Else it will fall down from the if and return false always
if (...) {
check = true;
}
else {
check = false;
}
public void check(){
if(particle < 0){
if(point[3].equals(point[3]) == true){
check = true;
}else{
check = false;
}
}
}
Try this:
public boolean check() {
if (particle < 0) {
return point[3].equals(point[3]);
} else {
return false;
}
}
what about particle?
by convention point ought to be equal to itself, but you could always implement it otherwise.
but of course, the other reply is correct, this function will always end with check=false

Categories