How to set max depth for recursive program in java? - java

I've written a recursive program in java that takes an array of characters and with two methods, one switching places of the two leftmost tiles and the other moving the rightmost tile to the left of the leftmost tile. It then returns the order of moves which makes the array in alphabetical order with the smallest number of moves. It seems to be working but I'm also supposed to set a max depth (15), and what I wonder is what do I return when it has reached max depth? It seems to be working right now, but I'm not sure it's correct.
This is part of the code:
public static String Sorter(char[] letters){
int nrOfMoves = 0;
return Sorter(letters,nrOfMoves);
}
private static String Sorter(char[] letters, int nrOfMoves){
if(sorted(letters)) return "";
if(nrOfMoves >= 15) return "" ; //??
switchLeft(letters);
String moveb = "b" + Sorter(letters,nrOfMoves+1);
switchLeft(letters);
rightToLeft(letters);
String moves = "s" + Sorter(letters,nrOfMoves+1);
leftToRight(letters);
if(moves.length()<moveb.length()) return moves;
return moveb;
}

The example seems fine. Personally, I would make use of nrOfMoves++ instead of nrOfMoves+1
and I would have it count down (number of moves left instead of number of moves performed). This makes sure that your Sorter method does not need to know at what depth it needs to stop. It just gets a limit of how many more recursions it can perform
public static String Sorter(char[] letters){
int nrOfMoves = 15;
return Sorter(letters,nrOfMoves);
}
private static String Sorter(char[] letters, int nrOfMoves){
if(sorted(letters) || nrOfMoves <= 0){
return "";
}
switchLeft(letters);
String moveb = "b" + Sorter(letters,nrOfMoves--);
switchLeft(letters);
rightToLeft(letters);
String moves = "s" + Sorter(letters,nrOfMoves--);
leftToRight(letters);
if(moves.length()<moveb.length()) return moves;
return moveb;
}

Related

Check for Palidrome using Recursion and Char Array search

I'm currently trying to use a function that compares the left and right side character to return a true or false Boolean value as to whether the string entered by the user is a palindrome or not, but I get a vague error statement to do with line 44. Not sure how to proceed. I am a beginner-level Java programmer who is open-minded and willing to learn, so don't roast me to hard haha.
import java.util.Scanner;
/**
*
* #author owner
*/
public class Q2_RecursivePalidrome {
public static void main(String[] args) {
int leftSideCharacter = 0;
int rightSideCharacter = 0;
Scanner scan = new Scanner (System.in);
System.out.println("Enter word to check whether palidrome: ");
String userInput = scan.next();
char[] checkPalidrome = userInput.toCharArray(); // creates an array of characters
System.out.println(isPalidrome(checkPalidrome, leftSideCharacter, rightSideCharacter));
}
public static boolean isPalidrome(char[] checkPalidrome, int leftSideCharacter, int rightSideCharacter) {
leftSideCharacter = 0;
rightSideCharacter = checkPalidrome.length - 1; // java arrays start at 0, not 1.
if (rightSideCharacter > leftSideCharacter) { // check both ends of string character by character
// to be palidrome, both sides of string should be same
//
if (checkPalidrome[leftSideCharacter] == checkPalidrome[rightSideCharacter]) {
return (isPalidrome(checkPalidrome, leftSideCharacter + 1, rightSideCharacter - 1));
}
else {
return false;
}
}
return true;
}
}
There are a couple main issues here, but you have the right idea:
Your recursive function uses left and right indices to determine which characters to compare in the test string. However, these two pointers are immediately set to the left and right ends of the string when the function is called, so they never recursively move towards the middle. Since the base case where the indices are equal is unreachable, the stack overflows. Remember, these calls are identical all the way down the stack, but with different parameters, so one-time "set up" tasks like setting initial indices should be moved outside of the recursive function.
Your initial pointer indices are 0, 0. This is an inaccurate "set up" call to the recursive function--it should be 0, string.length - 1.
Here is code that fixes these problems and cleans up comments and variable names:
import java.util.*;
public class Q2_RecursivePalidrome {
public static void main(String[] args) {
String test = "racecar";
System.out.println(isPalidrome(test.toCharArray(), 0, test.length() - 1));
}
static boolean isPalidrome(char[] test, int l, int r) {
if (l < r) {
if (test[l] == test[r]) {
return isPalidrome(test, l + 1, r - 1);
}
else {
return false;
}
}
return true;
}
}
By the way, the important lesson to take from all this is how to debug your program. In this case, printing your indices (the arguments that change from one call to the next) at the top of your recursive function will clearly show that they aren't doing what you expect.

Java Min-Heap Implementing Priority Queue - Iteration

I'm trying to use this code to implement a Priority Queue. There are a number of questions regarding this implementation on the site, but given how many different ways you can write code to do essentially the same thing I am still at a loss after looking through a handful of other examples.
There are some missing lines in this code, but I am limited to editing only the four marked lines and so I find myself stuck on one particular aspect. I can't seem to understand how 'quantity' is incremented.
From my understanding main creates a new object of maxSize = 5. Then calls the insertItem method passing the value of 130. This should be placed into the root (I had put queArray[quantity] = item; into the first blank) at which point the insertItem method exits and is then called again with the next value. So at what point is 'quantity' incremented? Maybe I am missing something incredibly simple, or maybe there is another way of solving this that may not be apparent or known to beginners like me?
I would think you would want to increment quantity under the initial if statement, but that doesn't seem to be an option, so as far as I can tell the else statement can never be executed as quantity doesn't change. I know I am incorrect, but I don't know how, some help would be greatly appreciated.
public class Main {
/**
* #param args the command line arguments
*/
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int quantity;
public Main(int s) {
maxSize = s;
queArray = new long[maxSize];
quantity = 0;
}
public void insertItem(long item) {
int i;
if (quantity == 0)
__________; // insert at 0
else
{
for (i = quantity - 1; i >= 0; i--) // start at end,
{
if (item > queArray[i]) // if new item larger,
__________; // shift upward
else
// if smaller,
break; // done shifting
}
__________; // insert it
__________;
} // end else (quantity > 0)
}
public boolean PQEmpty(){
return (quantity == 0);
}
public long removeItemPQ(){
return queArray[--quantity];
}
public long peekMin(){
return queArray[quantity - 1];
}
public static void main(String[] args) {
Main thePQ = new Main(5);
thePQ.insertItem(130);
thePQ.insertItem(450);
thePQ.insertItem(110);
thePQ.insertItem(430);
thePQ.insertItem(280);
while (!thePQ.PQEmpty()) {
long item = thePQ.removeItemPQ();
System.out.print(item + " ");
}
System.out.println("");
}
}
It isn't a style I'd recommend, but you could use queArray[quantity++] = item;.

Finding prefix exists in a list of words

Right now, I have a method that is supposed to use binary search to find if a prefix is in a list.
For example, user enters "ca" and if dictionary contains "cat", then the method should return true.
This is my method and along it is a helper method. The problem I have right now is that when I call the recursive method and the prefix is greater than the words in the dictionary, I will get an index out of bounds error because of the substring() method.
I'm using this method in conjunction with a recursive function in order to find all permutations of a string. (The generateWords() method).
How can I modify this function in order to check whether a prefix is in a list of words given that the list of words have words of varying lengths?
public boolean findPrefix(String Prefix){
return findBinaryPrefix(listOfWords, Prefix,0, listOfWords.size()-1, 0);
}
/**
* Helper function for findPrefix.
* #param list arraylist
* #param prefix prefix you want to find
* #param low lowest index
* #param high highest index of the array.
* #return returns true if prefix is in the dictionary, else false.
*/
private boolean findBinaryPrefix(ArrayList<String> list, String prefix, int low, int high, int prefixLength){
int charCounter = prefixLength;
if(low>high){
return false;
}
int mid = (low+high)/2;
if(list.get(mid).substring(0, charCounter).equals(prefix.substring(0, charCounter))){
//If the word is equal, then that's the base case.
return true;
}
else if (list.get(mid).substring(0, charCounter).compareTo(prefix.substring(0, charCounter)) < 0){
return findBinaryPrefix(list, prefix, mid+1, high, charCounter);
}
else
return findBinaryPrefix(list, prefix, low, mid-1, charCounter);
}
private ArrayList<String> generateWords(Dictionary dict,String prefix, String seq){
if(seq.length() == 0){
if(dict.findWord(prefix)){
permList.add(prefix);
}
}
else{
for(int i = 0;i<seq.length(); i++){
if(!dict.findPrefix(prefix)){break;}
//if prefix is not even in dictionary, don't bother generating.
//generate permutations when the character is in a different position with each iteration of the loop.
generateWords(dict, prefix + seq.charAt(i) ,seq.substring(0,i) + seq.substring(i+1, seq.length()));
}
}
return permList;
}
add
if(list.get(mid).length() < charCounter) {
//do something
}

Searching for a specific number in a int variable

I'm currently "learning" JavaScript + Android Studio for school and I got a little problem for which I can't find the right answer on Google:
I want to know if an int variable has a specific number, for example, I'm looking for the number 7 now int numberOne = 25824 doesn't have a 7 inside, but int numberTwo = 12387 does have one. Is there a way to search for a specific number in int variables?
I tried converting the int into a new string variable, but somehow this doesn't work :(
Here's some code I'm working with:
public int round = 1;
public String nummerSieben = "" + round;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (round % 7 == 0 || nummerSieben.contains("7")==true) {
....
} else {
....
}
}
});
Thank you for your help!
public int round = 1;
public String nummerSieben = "" + round; // nummerSieben is now "1"
You're hard-coding the value of nummberSieben. You need presumably get some value from the view, and test that. If you get it as in int, use
Integer.toString(i).contains("7") // i is whatever number you get from your view.
If you get it as a String, then half the work is already done, and you just need
i.contains("7")
As noted above, this has nothing to do with JavaScript - both your example and my answer are in Java.
Couple of things:
Your comparison is not right, method String:contains() returns a boolean,
Module % does not assert you the number will contain 7 or one of it's multiples.
Integer.toString(value) converts easily your int to String.
Knowing this, you can do:
if (Integer.toString(round).contains("7")) {
// IT CONTAINS THE NUMBER!
} else {
// IT DOES NOT CONTAIN THE NUMBER
}
Here is perfect solution of your problem
public class Finder {
static int round = 123456789;
static String str = String.valueOf(round);
public static void main(String... args) {
if (str.contains("7")) {
System.out.println("Found");
} else {
System.out.println("Can't found...");
}
}
}
Just convert your integer to String and then try to found the specific value from that string.
You don't have to convert to string in order to search specific digit in integer.
You can use math for that purpose.
Here is the code:
private static boolean isFound(int round) {
while (round > 0) {
if (round % 10 == 7)
return true;
round /= 10;
}
return false;
}
basically what this code do is checking each last digit if it's equals to 7 if not he divides the num by 10 and remove the last digit and after checking again, it will do so until no digit left (num=0) or he will find 7.

Returning an int value from a method java

I'm pretty new to java, but I'm trying to make a simulation of the finger game, 'Sticks', using my limited knowledge. This may not be the neatest, but if you're going to make a suggestion on me to do something, link a page explaining what that thing is, and I'll read it.
Ok, so the issue comes up basically when I call a method to decide who's turn it is and trying to return the value for the "count" up to 5, but it's not returning to main()
public static int TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return Death;
}
Death is there because I was getting an error telling me that I always need to return SOMETHING so I'm returning a static value.
Basically, the problem is getting PLH (player left hand) or PRH (player right hand) to return to main. If I'm not wrong, they should return as their initial variable name (PL, and PR) with the returned value correct? If not, what can I do to fix this?
The code is a lot larger than this, and this issue is happening throughout the whole program, so I'm showing just 1 method and assuming they're all the same issue; the methods are almost all the same.
Also, while I'm typing a question already, is nextInt() the best way to do a random number generator? When I had it as nextInt(1) it was exclusively attacking the left hand, and when I switched it to nextInt(2) now it's attacking both, but occasionally the code... "crashes" (what I mean by crashes is that it generates a number outside of what the If statements are looking for). I obviously need to to generate either a 1 or a 2 (or 0 and 1 if 0 counts).
You can change your code to
public static Integer TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return null;
}
NOTE: make sure you first check for null values where you call this function.
You are generating random number twice, this is why you can observe "strange" behvior.
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5) {
...
}
else if(botAtk.nextInt(2) == 0 && PLH <= 5) {
...
}
Try generating random only once:
Random botAtk = new Random();
boolean right = botAtk.nextInt(2) == 1; // flip coin only once
if(right && PRH <= 5) {
...
}
else if(!right && PLH <= 5) {
...
}
I know the answer will not get accepted, because there is an accepted one, but nevertheless:
I suspect that you have a wrong understanding of method parameter passing in Java.
What I read from your question and comments is that you expect this to work:
public static int psInt = 0;
static void main() {
int someNumber = 1;
int someOtherNumber = 5;
method1( someNumber, someOtherNumber );
// You expect "someNumber" to be 6 right now.
// But in fact, the value will be unchanged.
// What WILL work: psInt is 0 now
method3(); // this method will modify the static class var
// psInt is 5 now.
}
static void method1( int numParam, int someothervalue ){
numParam = numParam + someothervalue;
}
static void method2( int someNumber, int someothervalue ){
someNumber = someNumber + someothervalue; // <- same name won't work either!
}
public static void method3(){
psInt = 5;
}
But in Java method arguments are passed by value. That is: a copy!
So no matter how you name the variables and arguments, you will never have an "out" argument here.
What you can do:
In a static method, you can use and modify static class variables.
In a non-static method, you can use and modify non-static and static class variables.
You can pass a State-Object, of which you can modify field values.
You can return a value.
... there are more possibilites. These just to start with.
In your case, 4. does not make so much sense, because you wouldn't know if it is the new right or left hand value.

Categories

Resources