Switchbox routing with stack (java language) - java

I've been working on my college assignment about stacks in java, but I can't seem to find the help for this assignment. It's about switchbox routing and I'm required to use stack for this assignment. The assignment is due tomorrow, but there's no need to rush for answers since I'm only looking for the solutions and not the grades. Since the problem isn't written in english, I'm going to give short explanation.
The switchbox contains 4n pins, with n pins on each side of the box. The switchbox is routable only when none of the lines connecting a pair of pins intersect another. The input will be pairs of connected pin numbers.
A few possible solutions I've found but can't understand:
1. The problem can be solved with a similar algorithm as the one for the parentheses matching
2. Putting the pin numbers in stack and an array and compare them (this is the most confusing one)
My code so far (trying the second algorithm):
import java.util.Scanner;
import java.util.Stack;
public class Tester {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int cases=sc.nextInt();
for(int i=0;i<cases;i++){
int pin=sc.nextInt();
SwitchBox box=new SwitchBox(pin);
for(int j=0;j<pin*4;j++){
box.add(sc.nextInt());
}
boolean res=box.isRoutable();
if(res){
System.out.println("routable");
}
else{
System.out.println("not routable");
}
}
}
static class SwitchBox{
Stack<Integer> pins;
int[] pairs;
int[] comparator;
public SwitchBox(int pin){
this.pins=new Stack<Integer>();
this.pairs=new int[(pin*4)];
this.comparator=new int[this.pairs.length];
}
public boolean isRoutable(){
Stack<Integer> s=new Stack<Integer>();
for(int i=0;i<pairs.length;i++){
pairs[i]=pins.peek();
s.push(pins.pop());
}
for(int i=pairs.length-1;i>=0;i--){
if(pairs[i]!=s.pop()){
return true;
}
}
return false;
}
public void add(int pinNum){
if(pins.isEmpty()){
pins.push(pinNum);
}
else{
Stack<Integer> temp=new Stack<Integer>();
int top=(int)pins.peek();
while(top>pinNum){
temp.push(pins.pop());
if(pins.isEmpty()) top=pinNum;
else top=(int)pins.peek();
}
pins.push(pinNum);
while(!temp.isEmpty()){
pins.push(temp.pop());
}
}
}
}
}

In your add method else block is wrong. I was unable to understand what you try to do but you need to do next thing
public void add(int pinNum) {
if (pins.isEmpty()) {
pins.push(pinNum);
} else {
Integer last = pins.peek();
if (last == pinNum) {
pins.pop();
} else {
pins.push(pinNum);
}
}
}
After that isRoutable method just need to check pins stack. If it empty, then all fine. Else there are intersecting lines.

Related

Program not working?

The question is to find the number of days between two dates.example-input-26/3/2000 and 12/8/2014.the output will be the no of days in between these two dates.
There is an error saying "identifier expected" and i=1 is highlighted.Also I am not sure whether the program is completely correct.
import java.util.*;
class yearst
{
int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
int i,s,s1,s2,s3,k,diy,m,m1,m2,d1,d2,y1,y2,y;
i=1;s1=0;s2=0;s3=0;diy=365;
void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
ob.leap(i+1)
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
ob.leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
ob.leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s)
}
}
Please help.
Your program is a bunch of errors. First, you are calling class variables in main method without declaring them static or initializing them in constructor. Second, you are calling leap() which is method of a class from object of Scanner. It is not possible. The program will never compile nor run this way. I have modified your code to make it compilable and runnable. But one thing is for sure. Its logic is incorrect. It is giving wrong output as you want to calculate number of days between two dates. That is your job. I removed its errors. Now it is running. Here you are :-
import java.util.*;
class yearst
{
static int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
static int i=1,s,s1=0,s2=0,s3=0,k,diy=365,m,m1,m2,d1,d2,y1,y2,y;
static void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
//i=1;s1=0;s2=0;s3=0;diy=365;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
leap(i+1);
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s);
}
}
All the Best :)
Only declarations and static blocks allowed out of the methods. The below executable statement must be either in static block or in constructor
int i=1,s1=0,s2=0,s3=0,diy=365;
So, I recommend you move above code to constructor.
yearst(){
i=1;s1=0;s2=0;s3=0;diy=365;
}
A few things:
You'll need to initialize your variables inside a constructor, as initializing inside a class isn't allowed
Have you checked out the Date class in Java? It might be more useful for this case.
According to convention, class names should start with a capital letter

Can methods return exceptions? [duplicate]

This question already has answers here:
Java exception handling
(8 answers)
Closed 7 years ago.
Well im really new to java and im really trying hard to understand what can be done in java and what can't. I'm making a console application based on the well known game Hangman. Basiclay what i'am trying to do is stop the user from typing 'e's more than twice, to do that i made 2 methods:
The first one adds 1 to the int variable mManyTimes whenever the user types e.
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
the second method is the one that sends an exception
to the user when the user types e more then twice.
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
Basicly i created two files, one that holds the code of the game(Which those two methods are in) and other one.
the file that holds the logic of the game is Game.java and here is the code that is inside it:
public class Game {
private String mAnswer;
private String mHits;
private String mMisses;
private int mManyTimes;
public char letter;
public Game(String answer) {
mAnswer = answer;
mHits = "";
mMisses = "";
}
public boolean applyGuess(char letter) {
//checks for char letter inside the mAnswer variable.
//If it is there the indexOf() method should return the index of the letter.
//If it is not there it will return -1.
//We are basicly saing if indexOf() method returns 0 or more then that then the isHit
//if it is not then the isHit boolean will return false.
boolean isHit = mAnswer.indexOf(letter) >= 0;
if (isHit) {
mHits = mHits + letter;
} else {
mMisses = mMisses + letter;
}
adder();
return isHit;
}
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
The other file that holds the main() method and prints the code to the console is Hangman.java:
public class Hangman {
public static void main(String[] args) {
// Enter amazing code here:
Game game = new Game("treehouse");
game.applyGuess('e');
game.applyGuess('e');
System.out.println(game.cheatStopper());
}
}
So here is the question that frustrated me and i never found and answer for:
How do i get my code to work and stop the user from typing more then two e.
Well well i know my code has many errors and bad structure but dont forget that im new to java, and thanks for advance :).
You need a catch block. Look up how to catch exceptions.

JTextFields looping in JFrame

I have a simple JForm that has some text fields.The problem is, my evaluate() method is not cycling through the text fields as I expected.All I get is the first text fields, of getText() that are executed. I'm stuck in this. Help would be great. Here is the code. Also here is a screen capture of the program: https://www.dropbox.com/s/w5ie4dfnc9wi216/Capture.JPG?dl=0
public MAppGest() {
initComponents();
}
public double a=2.6;
public double index0;
public Iterator itr;
public void getText(String ind, String inde){
evaluate();
index0=Double.parseDouble(txtNewIndex.getText())-Double.parseDouble(txtOldIndex.getText());
txtTotalIndex.setText(Double.toString(index0));
txtRoom1.setText(Double.toString(index0));
txtTotal1.setText(Double.toString((index0*a)));
}
public void evaluate(){
if(Boolean.valueOf(txtNewIndex.getText())&&Boolean.valueOf(txtOldIndex.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtNewIndex2.getText())&&Boolean.valueOf(txtOldIndex2.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtNewIndex3.getText())&&Boolean.valueOf(txtOldIndex3.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtOldIndex4.getText())&&Boolean.valueOf(txOldIndex4.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtNewIndex5.getText())&&Boolean.valueOf(txtOldIndex5.getTex())==true){
getArray();
}
else{
JOptionPane.showMessageDialog(MAppGest.this,"An error occured");
}
}
public void getArray() {
ArrayList<String> al=new ArrayList<>();
al.add(txtNewIndex.getText());
al.add(txtOldIndex.getText());
al.add(txtNewIndex2.getText());
al.add(txtOldIndex2.getText());
al.add(txtNewIndex3.getText());
al.add(txtOldIndex3.getText());
al.add(txtOldIndex4.getText());
al.add(txOldIndex4.getText());
al.add(txtNewIndex5.getText());
al.add(txtOldIndex5.getText());
for (int i = 0; i< al.size(); i++) {
String fields []=null;
fields[i] = al.get(i);
}
}
private void btnGrandTotalActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
getText(txtNewIndex.getText(),txtOldIndex.getText());
getText(txtNewIndex2.getText(),txtOldIndex2.getText());
getText(txtNewIndex3.getText(),txtOldIndex3.getText());
getText(txtOldIndex4.getText(),txOldIndex4.getText());
getText(txtNewIndex5.getText(),txtOldIndex5.getText());
}
If your problem is that evaluate() is only completing the first if statement, it's because you are using if-else statements when you want to just use if. If you use if-else, once the first if is verified true it will skip the rest. If my answer is not what you are looking for, then I advise you to ask a better question. Like the comments have said, give an SSCCE so the answerers aren't left guessing.
A side note: Boolean.valueOf() returns a boolean, so your ==true is unnecessary.

java - Stack and queue confusion

What is the difference between these two ways of dealing with stacks and queues? What are the both called?
First way:
import java.util.Arrays;
public class StackMethods {
private int top;
int size;
int[] stack ;
public StackMethods(int arraySize){
size=arraySize;
stack= new int[size];
top=-1;
}
public void push(int value){
if(top==size-1){
System.out.println("Stack is full, can't push a value");
}
else{
top=top+1;
stack[top]=value;
}
}
public void pop(){
if(!isEmpty())
top=top-1;
else{
System.out.println("Can't pop...stack is empty");
}
}
public boolean isEmpty(){
return top==-1;
}
public void display(){
for(int i=0;i<=top;i++){
System.out.print(stack[i]+ " ");
}
System.out.println();
}
}
Second way:
public class StackReviseDemo {
public static void main(String[] args) {
StackMethods newStack = new StackMethods(5);
newStack.push(10);
newStack.push(1);
newStack.push(50);
newStack.push(20);
newStack.push(90);
newStack.display();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.display();
}
}
Also are they correct? trying to learn these well, but explanations across the internet are vague about these..
I'm not 100% sure what you mean with two ways.
Looking at your first code snippet, we can see that you are declaring the class StackMethods. In the second one you are instantiating an object of the class StackMethods.
So all you do in the main-method of your second code snippet is to create an object which is calling the methods push(), pop() and display() you declared in the class above. You didn't actually implement two datastructures, but just a basic stack.
The good news is, over all you have grasped the concepts of stacks, since your implementation of the class 'StackMethods' is correct overall.
In regards to what the difference between a Queue and a Stack is, this question might help you:
In case this didn't answer your question and I simply misunderstood it, please just comment and let me know so I can try to help you out a little better.

Talent Buddy Tweets per second

I am trying to solve this question from talent buddy.
http://www.talentbuddy.co/challenge/52a9121cc8a6c2dc91481f8d5233cc274af0110af382f40f
My code compiles and runs for small input, but is giving wrong ans for the following input-
http://tb-eval4.talentbuddy.co/5411559648d3e7eb5100024191810645628720530000.html
My Code is as follows -
import java.util.*;
class MyClass {
public void tweets_per_second(Integer[] tps, Integer k) {
PriorityQueue<Integer> pq =new PriorityQueue<Integer>(k, new Comparator<Integer>(){
public int compare(Integer i1, Integer i2){
if (i1.intValue()< i2.intValue()){
return 1;
}
else if(i1.intValue() ==i2.intValue()){
return 0;
}
else {
return -1;
}
}
});
for(int i=0;i<tps.length;i++){
if (pq.size()<=k){
pq.add(tps[i]);
System.out.println(pq.peek());
}
else{
pq.remove(tps[i-k]);
pq.add(tps[i]);
System.out.println(pq.peek());
}
}
}
public static void main(String[] args) {
MyClass t = new MyClass();
Integer[] tps = {6,9,4,7,4,1};
t.tweets_per_second(tps, 3);
}
}
Can someone please let me know what am I doing wrong? Any help will be appreciated. Thanks.
The code is entirely correct. At the end of the page you can see the following:
Error: your code didn't finish in less than 2 seconds.
Which tells you all you need to know.
As to why your code is slow - while using PriorityQueue or any built in collections etc is overall a good idea, it is very much not so in this case. I don't want to make educated guesses about how it's implemented, but one of add, remove, peek is not O(1) and eats up your time.

Categories

Resources