Java class to calculate shortest and longest side of a triangle - java

I've been working on my assignment all day and am stuck at just one part. I am pretty good at searching the internet and finding answers and have checked here as well. I still can't seem to figure out what is going on.
For the assignment we need to write a class with methods that will test a triangle. I am struggling with understanding classes, but have been able to get most of the code to work. The only issue I have now is with the is_equilibrium(); method. When running with the program provided with the assignment, the equilibrium method will return true every time.
problem code:
public boolean is_equilateral()
{
if(longest == shortest)
{
return true;
}
else
{
return false;
}
}
When I change it to:
public boolean is_equilateral()
{
if(side1 == side2 && side2 == side3&& side3 == side1)
{
return true;
}
else
{
return false;
}
}
I the code works fine and will return the true or false values.
I hope I am asking everything right, I am still trying to learn java so please bear with me! Any help is greatly appreciated!

Related

Wrap Around Grid - errors on east/west only

I have four methods that check whether or not a given grid location is next to an occupied location (value of 1). The grid is assumed to wrap around, ie, if in a 50x50 grid[0][1] is the given location and grid[49][1] is occupied, the method should return true/ My checkNorth and checkEast method are working fine, but I get an ArrayIndexOutofBoundsException: -1 error for either the south or west methods every time I run the program. I checked my math and I think it should work - am I using the modulo incorrectly, or am I missing something else?
EDIT: Clarified the wrapping criterion, word use correction.
boolean checkWest(int indexA, int indexB)
{
if (indexA-1 > 0)
{
if (grid[indexA-1][indexB] == 1)
{
return true;
}
}
if (indexA-1 < 0)
{
if (grid[(indexA-1)%width][indexB] == 1)
{return true;}
else return false;
}
return false;
}
I see a couple problems. First, Java arrays are zero-indexed, which means that the first element is at index 0. So it's okay to check grid[indexA-1][indexB] when indexA-1 is equal to 0. Second, you're not properly handling when indexA equals 0. Here is my implementation. I also simplified the logic a bit.
boolean checkWest(int indexA, int indexB)
{
if (indexA > 0)
return grid[indexA - 1][indexB] == 1;
else
return grid[width + indexA - 2][indexB] == 1;
}
EDIT: I'm pretty sure I butchered the math with the second return statement. It should be right now...

I can't figure out why this Recursion isn't working

I am learning about Recursions, and I haven't fully grasped it yet. So here I am trying to do an assignment on recursion but I'm stuck.
In this assignment, I am supposed to ask the user to input phrases, and the program determines whether it's a palindrome or not. We are supposed to accomplish this task using recursions.
This is the section with the recursion, and I can't quite figure out how to tackle it, as when I run it, I get no error, but it always comes up as false.
I'm using a ArrayList to keep all the user input.
Here's the code I've got right now
//instance variables
private boolean det;
private String input;
private String inputHelp;
//constructor
public RecursivePalindrome(String i)
{
det = false;
input = i;
inputHelp = "";
}
//determines if the method is a palindrome or not using recursions
public boolean palindrome(String b)
{
if(inputHelp.length() == 0)
{
det = true;
}
if(inputHelp.substring( 0 , 1 ).equals(inputHelp.substring( inputHelp.length() )))
{
inputHelp = inputHelp.substring( 1, inputHelp.length());
palindrome(inputHelp);
}
else
{
det = false;
}
return det;
}
There are three mistakes. First, note the substring documentation: second parameter is the end index "exlusive". Secondly, you need to use the result of the recursive call. And finally (as pointed out correctly by ajb in the comments), you should account for palindromes with odd letter count (first condition):
if (inputHelp.length() <= 1)
{
det = true;
}
else if (inputHelp.substring(0, 1)
.equals(inputHelp.substring(inputHelp.length() - 1)))
{
inputHelp = inputHelp.substring( 1, inputHelp.length() - 1);
det = palindrome(inputHelp);
}
else
{
det = false;
}
Also, you can make it a bit more readable:
public boolean palindrome(String b)
{
if (b.length() <= 1)
{
return true;
}
if (b.substring(0, 1)
.equals(b.substring(b.length() - 1)))
{
return palindrome(b.substring(1, b.length() - 1));
}
return false;
}
Further improvements can be made - lines still seem to long, especially the second condition (left as an exercise for the reader ;)).
As far as I can tell you are never setting inputHelp to anything other than an empty string, and the string b which is passed in to your method is not used anywhere.
So the method will never call back on to itself, and even if it did the value passed in would not be used for anything, rendering the recursion useless.

Sudoku Solver brute force algorithm

Still working on my sudoku solver, I have once again run into some trouble. I have gotten the sudoku solver to work, however whenever I attempt to solve a really "hard" sudoku board, my solver tells me there are no possible solutions, due to a stack overflow error. And yes, I know for a fact that these boards DO have a solution.
I am using the brute force algorithm -- I start at square one (or [0][0] if you prefer) and insert the first legal value. I then do a recursive call to the next square, and so on. If my function has not gone through the entire board, and finds there are no possible legal values, it moves to the previous square and attempts to increment the value there. If that fails, it moves further back. If it ends up at square one with no possible solutions, it exits.
I admit my code is not pretty and probably quite inefftective, but please keep in mind that I am a first year student trying to do my best. I don't mind comments on how to effectivize my code though :)
For squares without a final predefined number, here's the solver function:
public void fillRemainderOfBoard(Square sender){
try {
while(true){
if(currentPos > boardDimension){
if(previous != null){
this.setNumrep(-1);
this.setCurrentPos(1);
previous.setCurrentPos(previous.getCurrentPos()+1);
previous.fillRemainderOfBoard(this);
return;
} else if(sender == this){
this.setCurrentPos(1);
} else {
break;
}
}
if((thisBox.hasNumber(currentPos)) || (thisRow.hasNumber(currentPos)) || (thisColumn.hasNumber(currentPos))){
currentPos++;
} else {
this.setNumrep(currentPos);
currentPos++;
break;
}
}
if(this != last){
next.setNumrep(-1);
next.fillRemainderOfBoard(this);
} else {
return;
}
} catch (StackOverflowError e){
return;
}
}
In my code, the numrep value is the value that the square represents on the board. The currentPos variable is a counter that starts at 1 and increments until it reaches a legal value for the square to represent.
For squares with a predefined number, here's the same function:
public void fillRemainderOfBoard(Square sender){
if((sender.equals(this) || sender.equals(previous)) && this != last){
System.out.println(next);
next.fillRemainderOfBoard(this);
} else if (sender.equals(next) && this != first) {
previous.fillRemainderOfBoard(this);
} else {
System.out.println("No possible solutions for this board.");
}
}
Now, my problem is, like I said, that the function DOES solve sudokus very well. Easy ones. The tricky sudokus, like those with many predefined numbers and only a single solution, just makes my program go into a stack overflow and tell me there are no possible solutions. I assume this indicates I am missing something in the terms of memory management, or the program duplicating objects which I call in my recursive functions, but I do not know how to fix them.
Any help is greatly appreciated! Feel free to pick on my code too; I'm still learning (oh, aren't we always?).
___________________EDIT________________
Thanks to Piotr who came up with the good idea of backtracking, I have rewritten my code. However, I still cannot get it to solve any sudoku at all. Even with an empty board, it gets to square number 39, and then returns false all the way back. Here is my current code:
public boolean fillInnRemainingOfBoard(Square sender){
if(this instanceof SquarePredef && next != null){
return next.fillInnRemainingOfBoard(this);
} else if (this instanceof SquarePredef && next == null){
return true;
}
if(this instanceof SquareNoPredef){
currentPos = 1;
if(next != null){
System.out.println(this.index);
for(; currentPos <= boardDimension; currentPos++){
if((thisBox.hasNumber(currentPos)) || (thisRow.hasNumber(currentPos)) || (thisColumn.hasNumber(currentPos))){
continue;
} else {
System.out.println("Box has " + currentPos + "? " + thisBox.hasNumber(currentPos));
this.setNumrep(currentPos);
System.out.println("Got here, square " + index + " i: " + numrep);
}
if(next != null && next.fillInnRemainingOfBoard(this)){
System.out.println("Returnerer true");
return true;
} else {
}
}
}
if(next == null){
return true;
}
}
System.out.println("Returning false. Square: " + index + " currentPos: " + currentPos);
return false;
}
I had to complicate things a bit because I needed to check whether the current object is the last. Hence the additional if tests. Oh, and the reason I am using boardDimension is because this sudoku solver will solve any sudoku -- not just those 9 by 9 sudokus :)
Can you spot my error? Any help is appreciated!
So your problem lies here:
previous.fillRemainderOfBoard(this);
and here
next.fillRemainderOfBoard(this);
Basically you have too many function calls on the stack because you are going forward and backward multiple times. You are not really returning from any call before answer is found (or you get StackOverflowError :)). Instead of increasing stack size by using recursive function try to think how to solve problem using a loop (pretty much always loop is better than recursive solution performance wise).
Ok so you can do something like this (pseudo code):
boolean fillRemainderOfBoard(Square sender){
if (num_defined_on_start) {
return next.fillRemainderOfBoard(this);
} else {
for (i = 1; i < 9; ++i) {
if (setting i a legal_move)
this.setCurrentPos(i);
else
continue;
if (next.fillRemainderOfBoard(this))
return true;
}
return false;
}
The stack size will be ~81.

Need help detecting collision between two objects

I'm having some issue regarding collision detection in a game i am making. I have the distance between the two objects using this:
double b1Dist = Math.sqrt((obOneX - obTwoX) * (obOneX - obTwoX)
+ ((obOneY - obTwoY) * (obOneY - obTwoY)));
double b1DistTwo = b1Dist - objectOneRadius;
b1DistFinal = b1DistTwo - objectTwoRadius;
and I was attempting to do collision detection with this:
if (b1DistFinal <= objectOneRadius && b1DistFinal <= objectTwoRadius ) {
return false;
}
else
return true;
}
I'm new to java so i'm sure theres probably much better/more efficient ways to write the above, however could anyone please help me out or point me in the right direction?
Thanks
There's nothing wrong with the efficiency of that. However, if obOneX, obOneY, etc are the x and y coordinates of the centers of the objects, then your formula is wrong.
The variable b1DistFinal is the distance between the outer edges of the two objects. If it's zero, those objects have collided.
Try:
if (Math.abs(b1DistFinal) < 0.001) {
return true;
} else {
return false;
}
Note: Rather than checking if it is exactly zero, I am checking if it is close to zero to allow for some rounding error during the double arithmetic.

Stackoverflow exception in java minesweeper game

I was trying to make a minesweeper game in Java, but I keep running into this error. This function sets the current square to clicked and any adjacent squares to be clicked and continues recursively. It should stop when it runs out of squares, but even when I set the field size to 2x2 with 0 mines, it overflows.
public void setClicked(boolean clicked){
this.clicked = clicked;
if(adjacentMines == 0)
for(mine m : adjacent){
if(!m.isClicked() && !m.isMine()){
setClicked(true); //Should be m.setClicked(true);
}
}
}
Problem solved, I was missing the "m." in my method call. Thanks to everyone for your help.
You need to call setClicked on the adjacent mine, not on original mine, otherwise, you'll get setClicked(true) called over and over again for the source mine
public void setClicked(boolean clicked){
this.clicked = clicked;
if(adjacentMines == 0)
for(mine m : adjacent){
if(!m.isClicked() && !m.isMine()){
m.setClicked(true); // setClicked should be called on the adjacent mine, not on itself!
}
}
}
You are calling setClicked on the same mine instead of the adjacent ones.
Change to:
public void setClicked(boolean clicked){
this.clicked = clicked;
if(adjacentMines == 0)
for(mine m : adjacent){
if(!m.isClicked() && !m.isMine()){
//missing the "m."
m.setClicked(true);
}
}
}
Well, I can only guess that setClicked() method is a member of mine, but shouldn't you be calling m.setClicked(true) inside your condition instead of just setClicked(true)?
Difficult to tell from your code snippet, but I would say you do not iterate over the cells. That means you are recursively checking the same cell over and over (to infinity and beyond woosh). The surrounding code would be very useful to see, though.

Categories