Palindrome Recursion Program - recursion

public static boolean palindrome(String input, int i, int j)
{
if (i >= j)
return true;
if (input.charAt(i) == input.charAt(j))
{
i++;
j--;
palindrome(input, i, j);
}
else if (input.charAt(i) != input.charAt(j))
return false;
}
My Java platform (eclipse) won't accept this code as working, due to a "lack of return type." Now I know in proper coding ediquite, it's better to use only one return value, but when it comes to recursion, this is somewhat new to me. How can I go about doing this? If I instantiate a Boolean type at the top of this method, it's creating a new instance of that variable (and instantiating it as null or whatever I set it to) each time the method runs, but if I place it above my constructor, my method won't assign a value to it/can't return it.
Basically, how do I go about modifying my code to have a single return value that Eclipse will accept as always executing? I can do this easily enough with loops, but I'm not sure how to approach the topic with Recursion.

Just for improved readability:
public static boolean palindrome(String input, int i, int j)
{
if (i >= j)
return true;
if (input.charAt(i) != input.charAt(j))
return false;
return palindrome(input, i + 1, j - 1);
}
If we could use C# and Linq (since I don't have Java dev environment here) to reversing a char array:
public static bool palindrome(String input)
{
return input.Equals(new String(input.ToCharArray().Reverse().ToArray()));
}

The issue is that you have no return inside the second if statement. If charAt i and j are equal you never return anything.
Keeping the spirit of your code I'd shorten the whole thing up to be:
public static boolean palindrome(String input, int i, int j)
{
if (i >= j)
{
return true;
}
if (input.charAt(i) == input.charAt(j))
{
return palindrome(input, i + 1, j - 1);
}
return false;
}

You can certainly just do this:
return palindrome(input, i, j);
However it is good practice to have a single return to improve readability. Try this on for size:
boolean isPalindrome = false;
if (i >= j)
isPalindrome = true;
else if (input.charAt(i) == input.charAt(j))
{
i++;
j--;
isPalindrome = palindrome(input, i, j);
}
else if (input.charAt(i) != input.charAt(j))
isPalindrome = false;
return isPalindrome;
}
Have that boolean always instantiated. The key here is to make palindrome's return be stored in that boolean.
The recursive portion comes in at the call to palindrome. It will only finally return the final value after all of the recursive calls, because it only ever determines if its a palindrome when it reaches the end of the recursive cycle.

In the second if block, you don't return anything.
Just change the recursive call so that you return its value:
return palindrome(input, i, j);
Also, incidentally, you don't need to do i++ and j-- in the if block-- you can instead call the palindrome method with i+1 and j-1 instead, and that will have basically the same effect.

public static String palindrome(String input, int i, int j)
{
if (i >= j)
return "-1";
//--------------------------------------------//
if (input.charAt(i) == input.charAt(j))
{
i++;
j--;
//--------------------------------------------//
palindrome(input, i, j);
return "is palindrom";
}
//--------------------------------------------//
else
return "not palindrom";
}
}
//--------------------------------------------//

An other option might be this:
boolean isPalindrome(String s) {
boolean ret = true;
if (s.length() == 1 || s.equals("")) {
return ret;
} else {
char first = s.charAt(0);
char last = s.charAt(s.length() - 1);
if (first != last)
ret = false;
else if (s.length() > 2) {
String partial = s.substring(1, s.length() - 1);
ret = isPalindrome(partial);
}
}
return ret;
}

Probably this answer can help(in Python):
def isPalinr(str1):
if len(str1)<=1:
print('Palindrome')
return
if (str1[0] != str1[-1]):
print ('Not palindrome')
return
else:
return isPalinr(str1[1:len(str1)-1])
This will return None though we can return string in first 'if' clause because program will ultimately stop at that point.

Related

Why it is necessary to pass the anc vector by reference in the dfs function?

class Solution
{
public:
//Function to detect cycle in a directed graph.
bool dfs(int V, vector<int> adj[],vector <bool>& isvis,int start,vector<bool>**&**anc)
{
isvis[start]=1;
anc[start]=true;
for(auto nb : adj[start])
{
if(!isvis[nb])
{
if(dfs(V,adj,isvis,nb,anc))
return true;
}
if(anc[nb]==true)
return true;
}
for(int i=0;i<V;i++)
{
cout<<i<<" "<<anc[i]<<endl;
}
anc[start]=false;
return false;
}
bool isCyclic(int V, vector<int> adj[])
{
vector < bool > isvis(V,false);
vector <bool> anc(V,false);
for(int i=0;i<V;i++)
{
if(!isvis[i])
{
if(dfs(V,adj,isvis,i,anc))
return true;
}
}
return false;
}
};
Because the function modifies the argument (in anc[start]=true;). If it was passed by value, it would have its own copy of the vector and modify that copy, so the anc variable in isCyclic wouldn't be modified.

K-th largest element in BST

I am trying to find the K-th largest element in a Binary Search Tree using reverse inorder approach by using a counter. Here is what I have implemented:
int klargest(Node root,int k,int count)
{
if(root != null)
{
klargest(root.right,k,count);
count++;
if(count == k)
return root.data;
klargest(root.left,k,count);
}
return -1;
}
But the issue is that when count = k, the code does not return the answer to the caller function but instead to a sub-call. Due to this, the answer is lost. In other words, the recursion does not stop there and it keeps on going until all the nodes are visited. In the end, I get the answer -1. What I want is that the recursion should end when count = k and the required answer should be returned to the caller function. How can I do this?
Note: I neither want to use a global variable nor an iterative approach.
Actually, you do not return your node - the recursive call results are ignored. Rewrite it so it returns a Node:
Node klargest(Node root,int k,int count)
{
Node result = null;
if(root != null)
{
result = klargest(root.right,k,count);
if (result != null)
return result;
count++;
if(count == k)
return root;
result = klargest(root.left,k,count);
}
return result;
}
You can use this approach:
int kthLargest(Node node, int k) {
int rightCount = count(node.right);
if (k <= rightCount) {
return kthLargest(node.right, k);
} else if (k == rightCount+1) {
return node.data;
} else {
return kthLargest(node.left, k - rightCount + 1);
}
}
int count(Node node) {
if (node != null) {
return count(node.left) + count(node.right) + 1;
}
return 0;
}

Finding duplicates in Array of structure

I am using QT to search for duplicate entries in a structure.I have a struct as follows:
struct information{
QString fname;
QString lname;
QString gender;
QString age;
QString cod;
};
I have this code here which has bool variable for each variable in the structure and changes the bool value to true if data in the two arrays are the same and checks to see if all the bool values are true and prints out the two lines where duplicates are.
for (int i=0; i<numlines; i+=1){
for (int j=i+1; j<numlines; i+=1){
bool fname = false;
bool lname = false;
bool age = false;
bool cod = false;
bool gender= false;
if (person[i].fname == person[j].fname){
fname = true;
//qDebug() <<fname;
}
if (person[i].lname == person[j].lname){
lname = true;
//qDebug() <<lname;
}
if (person[i].gender == person[j].gender){
gender = true;
//qDebug() <<gender;
}
if (person[i].age == person[j].age){
age = true;
//qDebug() <<age;
}
if (person[i].cod == person[j].cod){
cod = true;
//qDebug() <<cod;
}
if (fname==true && lname==true && gender==true && age==true && cod==true){
//print out where duplicate are.
//duplicates at line i+1 and j+1
}
}
}
When I click my duplicate check button which activates the code it enters the loop once and terminates the program unexpectedly. Any suggestions?
for (int i=0; i<numlines; i+=1){
for (int j=i+1; j<numlines; i+=1){
// ^
Simple problem (probably cut'n'paste error) - you need to increment j, not i.
And, as an aside, you could probably refactor your code to make it a bit simpler since, if any field doesn't match, you can just move to the next, something like (pseudo-code):
for i = 0 to (sz - 2) inclusive:
for j = (i + 1) to (sz - 1) inclusive:
if person[i].fname != person[j].fname: continue
if person[i].lname != person[j].lname: continue
if person[i].age != person[j].age: continue
if person[i].cod != person[j].cod: continue
if person[i].gender != person[j].gender: continue
// they're all equal at this point, log the fact.
This removes the need for those boolean variables.
But, if you do decide to keep the booleans, you can make your code more readable by choosing their names carefully. I tend to prefer booleans to be readable such as customerIsDead or managerHasPsychopathicTendencies. That way, they "flow" easier when reading the code:
if (sameFName && sameLame && sameGender && sameAge && sameCod) {
You should generally never have compare a boolean value with true or false since that just gives you another boolean and, as per reductio ad absurdum, where do you stop?
if ((((x == true) == true) != false) == true) ...

Issue with Recursive Methods ("missing return statement")

so I have a program that is running a bunch of different recursive methods, and I cannot get it to compile/run. The error is in this method, according to my computer:
public static int fibo(int n)
// returns the nth Fibonacci number
{
if (n==0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else if (n>1)
{
return fibo(n-1) + fibo(n-2);
}
}
I have this method called correctly in my main method, so the issue is in this bit of code.
I think I can help you in this. Add return n; after your else if. Outside of the code but before the last curlicue.
The code will work as long as n ≥ 0 btw; another poster here is right in that you may want to add something to catch that error.
Make sure all possible paths have a return statement. In your code, if n < 0, there is no return statement, the compiler recognizes this, and throws the error.
public static int fibo(int n)
// returns the nth Fibonacci number
{
if (n<=0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else // All other cases, i.e. n >= 1
{
return fibo(n-1) + fibo(n-2);
}
}

How to match text in string in Arduino

I have some issues with Arduino about how to match text.
I have:
String tmp = +CLIP: "+37011111111",145,"",,"",0
And I am trying to match:
if (tmp.startsWith("+CLIP:")) {
mySerial.println("ATH0");
}
But this is not working, and I have no idea why.
I tried substring, but the result is the same. I don't know how to use it or nothing happens.
Where is the error?
bool Contains(String s, String search) {
int max = s.length() - search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i) == search) return true; // or i
}
return false; //or -1
}
Otherwise you could simply do:
if (readString.indexOf("+CLIP:") >=0)
I'd also recommend visiting:
https://www.arduino.cc/en/Reference/String
I modified the code from gotnull. Thanks to him to put me on the track.
I just limited the search string, otherwise the substring function was not returning always the correct answer (when substrign was not ending the string). Because substring search always to the end of the string.
int StringContains(String s, String search) {
int max = s.length() - search.length();
int lgsearch = search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i, i + lgsearch) == search) return i;
}
return -1;
}
//+CLIP: "43660417XXXX",145,"",0,"",0
if (strstr(command.c_str(), "+CLIP:")) { //Someone is calling
GSM.print(F("ATA\n\r"));
Number = command.substring(command.indexOf('"') + 1);
Number = Number.substring(0, Number.indexOf('"'));
//Serial.println(Number);
} //End of if +CLIP:
This is how I'm doing it. Hope it helps.
if (tmp.startsWith(String("+CLIP:"))) {
mySerial.println("ATH0");
}
You can't put the string with quotes only you need to cast the variable :)

Resources