finding integer element in integer array:recursion issue - java

I wrote this recursive method to find an integer in an integer array but it's not working. I tried debugging it but I don't know what the problem could be.
Here's the code
public static String inList(int[] primes,int a){
int index = -9;
if(primes.length>1){
index = primes.length/2;
}else{
if(primes[0] == a){
return "True";
}else{
return "False";
}
}
if(primes[index] == a){
return "True";
}
if(primes[index] > a){
inList(Arrays.copyOfRange(primes, 0, index),a);
}
if(primes[index]<a){
inList(Arrays.copyOfRange(primes, index, primes.length),a);
}
//shouldn't even get to this point, but eclipse insisted I needed another return
//statement
return "Whyyyyy?";
}

you have forgot to add return
did you sort your array?
if(primes[index] > a){
return inList(Arrays.copyOfRange(primes, 0, index),a);
}
if(primes[index]<a){
return inList(Arrays.copyOfRange(primes, index, primes.length),a);
}

Just use Arrays.binarySearch(). As you will see from its different prototypes, it will return a negative value if and only if the value you are looking for in the array is not there.

Recursive function to find something in an array would be:
public static String inList(int[] primes,int index, int a) {
/* two breaking conditions for recursion: end of array or number found */
if(index >= primes.length)
return "False";
if(primes[index] == a)
return "True";
/* recursion */
return inList(primes, ++index, a);
}
You can call above method with index = 0 ex. inList(primes, 0, a). This will be much slower than non-recursive find method.

Related

Keep multiplying found values in an array error with recursion

I struggle with this coding "challenge".
I need to look for the original value in nums. If its there, multiply by two
and redo the whole thing.
Return the value if there is no more same value.
It works on a lot of test cases but I get a weird error with this set while debugging.
After I iterate the array and was ready to return the right value, instead of returning the 16, it calls the findFinalValue again and iterates itself from 16 down again to 4.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
int[] nums = {8,19,4,2,15,3};
System.out.println(s.findFinalValue(nums, 2));
}
}
class Solution {
public int findFinalValue(int[] nums, int original) {
for(int n: nums){
if(n == original){
original*=2;
findFinalValue(nums, original);
}
}
return original;
}
}
It is not iterating from 16 to 4, it is how recursion works. You need to pass the result back or store it in a global variable. Once the dead-end is achieved in recursion it backtracks and comes back to its original state.
Solution
class Solution {
public int findFinalValue(int[] nums, int original) {
int isPresent = false;
for(int n: nums){
if(n == original){
isPresent = true;
break;
}
}
if(isPresent) {
original = findFinalValue(nums, original*2);
}
return original;
}
}
Frankly speaking, you can optimize it by sorting the array at first and then using binary search for finding elements, in addition, the array passed in the next state can be reduced till the index has read. Because original has become twice
I wouldn't use recursion, but since I think you're asking about a recursive solution, I would do it like this:
public int findFinalValue(int[] nums, int original) {
return IntStream.of(nums).anyMatch(n -> n == original)
? findFinalValue(nums, 2 * original)
: original;
}
Guessing that your problem is that your have not implemented recursion properly:
class Solution {
public int findFinalValue(int[] nums, int original) {
int found = original;
for(int n: nums){
if(n == original){
found = findFinalValue(nums, found * 2);
}
}
return found;
}
}

How do I make this function return the value I'm looking for?

I made a function that's meant to count the number of specific chars in a function recursively.
public static int countCharInString(String s, char c)
{
return countCharInString(s, c, 0);
}
public static int countCharInString(String s, char c, int index)
{
if(index==s.length())
{
return 0;
}
if(s.charAt(index) == c)
{
return 1 + countCharInString(s, c, index+1);
}
if(s.charAt(index)!=c)
{
return countCharInString(s, c, index+1);
}
}
How can I put a return statement at the end of the function that'll return the whole number I "counted" inside the function?
You don't need an extra return statement at the end of the method, the error you're getting is because the compiler isn't convinced that you've got all cases covered.
The easiest fix for this is to simply replace your second comparison against c with else. Either the character is equal to c or it isn't, you don't need a separate check.
e.g.
public static int countCharInString(String s, char c, int index) {
if (index == s.length()) {
return 0;
}
if (s.charAt(index) == c) {
return 1 + countCharInString(s, c, index + 1);
} else {
return countCharInString(s, c, index + 1);
}
}
I would use a for Loop, If the recursion is needed, Check If
Index+1 > s.length()
If this is the Case the recursion should return
You need to have a parameter to keep track of your running total. Add a parameter to your function which you'll increment each time you find the character. Then return that number instead of returning 0
Using recursion here does not make sense to me. The number of characters in a string is going to be `s.length()'.
However, since this is your requirement - I believe you want the count of some character - I recognized this as a classic 're-invent' the wheel program. While I dislike these, the important thing here is to understand what is happening.
Firstly, you don't need a variable for index... because you always set it to 0. So just use 0.
Secondly, let's use substring so we don't have to convert to chars and deal with character/String comparisons etc.
public static int countCharInString(String s, String c) {
// This will only happen when the string is empty to begin with, our we're done with recursion. Since we add this to another number in recursion - it works for our purpose
if (s.length() == 0) {
return 0;
}
// If we have a match, increment add add to our recursive sum
if ((s.substring(0, 1).equals(c))) {
return 1 + countCharInString(s.substring(1), c);
}
// do the final return and invoke recursion
return countCharInString(s.substring(1), c);
}

Searching for a String in an Array and returning the position

Hi I'm a complete newbie on programming and I try to search for a certain String in an array. When it's found the method should return the index but if the String is not found it should return -1.
public int poitionOfWord(String testWord) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i].equals(testWord)) {
return i;
}
}
return -1;
}
would this method return always -1 or would it actually terminate when finding a word and would return i.
Your method is correct and it will return the index in case it finds a match else if it doesn't find the match, it will come out of loop and return -1.
Just to make code crisp and concise, you can use something like this,
public static String[] wordArray = new String[]{"a", "b"};
public static int poitionOfWord(String testWord) {
return Arrays.asList(wordArray).indexOf(testWord);
}
Then test it with some code,
public static void main(String args[]) {
System.out.println(poitionOfWord("a"));
System.out.println(poitionOfWord("z"));
}
This prints,
1
-1
In general, when your function reaches a return statement, it will terminate and return the given value.

prefix to infix notation using an recursive algorithm

I am new here and I am somehow stuck.
I created an recursive algorithm that uses an global variable for remembering the Position he made the recursive call and I am trying to get rid of this variable as for me it seems to be not a good solution.
Is there any chance to get rid of this global variable? I cannot adjust the method-head so therefore the Interface of the method is fixed.
Here you can see my Code:
static int pos = -1;
static boolean writeInfix(char[] expr) {
boolean result;
pos++;
int printpos = pos;
if(expr[pos]=='+'||expr[pos]=='-'||expr[pos]=='/'||expr[pos]=='*'){
System.out.print("(");
writeInfix(expr);
System.out.print(expr[printpos]);
result = writeInfix(expr);
System.out.print(")");
return result;
}else if(expr[pos] >= 'a' && expr[pos] <= 'z'){
System.out.print(expr[pos]);
return true;
}else{
return false;
}
}
Thank you for your help :)
You can add a new auxiliary method, where you control its variables, and let writeInfix(char[]) be only a wrapper, that does nothing but calling the "real" method.
In this new method, pos is an arument.
This also ensures you can call your API method (writeInfix) twice (independently) without worrying from the side effects (pos is initialized with wrong value after first call).
You should be able to write another method with the position as additional argument:
private static boolean writeInfix(char[] expr, int pos) {
boolean result;
int printpos = pos;
if(expr[pos]=='+'||expr[pos]=='-'||expr[pos]=='/'||expr[pos]=='*'){
System.out.print("(");
writeInfix(expr);
System.out.print(expr[printpos]);
result = writeInfix(expr, pos + 1);
System.out.print(")");
return result;
}else if(expr[pos] >= 'a' && expr[pos] <= 'z'){
System.out.print(expr[pos]);
return true;
}else{
return false;
}
}
and in the method you already have, you just need to call
static boolean writeInfix(char[] expr) {
return writeInfix(expr, -1);
}
You can add pos as an argument to the writeInfix function.
static boolean writeInfix(char[] expr, int pos);
Whereever you are returning false, return -1. Whereever you are returning true, return the current pos value.

Comparing the values of two arrays using recursion?

I am trying to check if two arrays have the same length, and the same values in the same exact position.
My current code looks like this:
public class MyArray {
private int size;
private int[] array;
private boolean isSorted; //to check if array is sorted
private static int arrCount; //used to identify which MyArray object
public MyArray(){
size = 10;
array = new int[10];
arrCount+=1;
}
public MyArray(int Size){
size = Size;
array = new int[Size];
arrCount+=1;
}
public MyArray(MyArray arrOther){
this.size = arrOther.getSize();
this.array = arrOther.getArray();
arrCount+=1;
}
public int getSize(){
return size;
}
public int[] getArray(){
return array;
}
#Override
public boolean equals(Object other){
if (other instanceof MyArray){
MyArray second = (MyArray) other;
if (second.getSize() == this.getSize())
return equalsHelper(this.getArray(), second.getArray(), 0, (size-1));
}
//else
return false;
}
private boolean equalsHelper(int[] first, int[] second, int iStart, int iEnd) {
if (iStart == iEnd) {
return true;
}
if (first[iStart] == second[iStart]) {
if (equalsHelper(first, second, (iStart + 1), iEnd)) {
return true;
}
}
return false;
}
}//end class
for some reason it always returns true even if the arrays are in different order.
the equals method is called in the main program here:
--main method--
if (MA2.equals(MA1)) //the arrays are identical here
{
System.out.println("The first and second arrays are equal.");
}
else {System.out.println("The first and second arrays are NOT equal.");}
MA2.sort(); //the order of the elements changes
System.out.println("The second array has been sorted in ascending order.");
if (MA2.equals(MA1))
{
System.out.println("The first and second arrays are equal.");
}
else {System.out.println("The first and second arrays are NOT equal.");}
First check (preferably) outside of your helper should be to see if both the arrays have equal lengths. Makes no sense to continue otherwise.
equalsHelper should return true if end of array is reached.
I see no reason to have 2 separate pointers for index since the arrays are required to be of the same size and the same index is being checked.
Invocation:
....
....
if(first.length != second.length)
return false;
return equalsHelper(first, second, 0);
The helper method...
private boolean equalsHelper(int[] first, int[] second, int indx) {
if(indx == first.length)
return true;
if(first[indx] != second[indx)
return false;
return equalsHelper(first, second, indx+1);
}
Firstly, iStart and iEnd are redundant. use .length
String[] array = new String[10];
int size = array.length;
If you're trying to compare contents of arrays that may be identical, you need to pass through it manually.
for(int i = 0: (i > first.length || i > second.length; i++){
if(first[i] != second[i]){
return false;
}
}
return true
Your next problem is
if (iStart == iEnd){
return first[iEnd] == second[iEnd]; //return true or false
Your logic here is wrong. You can't directly compare arrays like this. It's comparing the memory address. This will always be false unless you pass through the exact same array when the method is called - which i don't think is what you're trying to do
Array lengths are set manually, so it's a conscious effort to get a difference.
Let me suggest using an ArrayList if you're expecting differing lengths. They're also more flexible.
ArrayList <Integer> a = new ArrayList <int>();
ArrayList <Integer> b = new ArrayList <int>();
Then you'll need to check their lengths. ArrayList uses the .length() method instead of an Array[].length property
if(a.length() == b.length()){
then if you want to see if each value in each index is identical, you'll need to pass through the array manually as shown above.

Categories