Reputation: 219
I am trying to write a method that finds how many odd numbers are between first position and last position. The method accepts an array, and then two int
s for the low and high position. This method needs to be made recursively. Here is what I have so far. Here is the method call and the int array. I'm getting an output of 1 but the answer should be 2.
int array [] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 1, 4)
public static int countOddsInRange(int [] a, int first, int last)
{
int count = 0;
if(first <= last)
{
countOddsInRange(a, a[first + 1], a[last]);
if(a[first] % 2 == 0)
{
count++;
}
}
return count;
}
Upvotes: 0
Views: 5736
Reputation: 18035
public class CountOddsInRange {
public static void main(String[] args) {
int array[] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 0, array.length - 1, 0);
System.out.println("No of odds is " + n);
}
public static int countOddsInRange(int[] a, int first, int last, int count) {
if (first <= last) {
if (a[first] % 2 != 0) {
count++;
}
return countOddsInRange(a, first + 1, last, count);
}
return count;
}
}
Upvotes: 0
Reputation: 393856
You have some bugs in your code :
if(a[first] % 2 != 0)
count+=countOddsInRange(a, first + 1, last)
To summarize :
public static int countOddsInRange(int [] a, int first, int last)
{
int count = 0;
if(first <= last)
{
count+=countOddsInRange(a, first + 1, last);
if(a[first] % 2 != 0)
{
count++;
}
}
return count;
}
Upvotes: 5
Reputation: 18035
public class CountOddsInRange {
public static void main(String[] args) {
int array[] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 0, array.length - 1);
System.out.println("No of odds is " + n);
}
public static int countOddsInRange(int [] a, int first, int last)
{
int count = 0;
if(first <= last)
{
count+=countOddsInRange(a, first + 1, last);
if(a[first] % 2 != 0)
{
count++;
}
}
return count;
}
}
Upvotes: 0
Reputation: 1571
Your function should looks like :
public static int countOddNumber(int [] a, int first, int last){
return countOddNumber(a, first, last, 0);
}
public static int countOddNumber(int [] a, int first, int last, int count){
//in recursive function start with termination test.
if (first == last){
return count + isOdd(a[first]);
}
else{
return countOddNumber(a, first+1, last, count) + isOdd(a[first]);
}
}
public static int isOdd(int number){
if(number%2 == 0){return 1;}
else{return 0}
}
You should also add a test to check if first is lesser than last to avoid infinite loop ;)
PS : filter element whose mod(element,2) = 0 and then get the size of the collection. That method use functional style too, and use new Java8 feature. And is probably much more faster.
Upvotes: 0