montomono
montomono

Reputation: 3

Looping through boolean array using recursion

I have written a method that takes a boolean array as input, and returns the conjunction of all of the values in the array using a loop. However, I am trying to do the same thing except using recursion (no for loops allowed) and am having trouble. Any suggestions or hints? Thanks!

Here is what I have written for the iteration part:

public class LogicalOperators {
  public static void main(String[] args) {
    boolean[] queue = new boolean[] {true, false, true, true, true};
    System.out.println(conjunctionIter(queue));
  }

public static boolean conjunctionIter(boolean[] queue){
  boolean allArrayTrue = true;
  for(int i=0; i<queue.length; i++){
    if(queue[i] == false){
      allArrayTrue = false;
      break;
    }
  }
  return allArrayTrue;
}

Upvotes: 0

Views: 1586

Answers (3)

user5708826
user5708826

Reputation:

Here's one approach.

public static boolean conjunctionIter(boolean[] queue){
        boolean result = true;
        int index = 0;
        return conjunctionIter(queue, result, index);
    }

    private static boolean conjunctionIter(boolean[] queue, boolean result, int index){

        if(index == queue.length -1)
            return result = result && queue[index];

        return result = conjunctionIter(queue, result, ++index);

    }

Client code.

public static void main(String[] args) {
    // write your code here
        boolean[] queue = new boolean[] {true, false, true, true, true};
        System.out.println(conjunctionIter(queue));
    }

Upvotes: 0

KevinO
KevinO

Reputation: 4403

An example of a recursive function that effective && all booleans in an array

public static boolean recurse(boolean[] ary)
{
    if (ary.length == 1) {
        return ary[0];
    }

    return ary[0] && recurse(Arrays.copyOfRange(ary, 1, ary.length));
}

Test driver:

public static void main(String[] args)
{
    boolean[] ary = { true, true, true, true, true};

    System.out.println(recurse(ary));

    boolean[] ary2 = { true, true, false, true, true};

    System.out.println(recurse(ary2)); 
}
  • true
  • false

Upvotes: 1

arnav bhartiya
arnav bhartiya

Reputation: 333

You might be looking for something in the line of this :

public class LogicalOperators {
public static void main(String[] args) {
boolean[] queue = new boolean[] {true, false, true, true, true};
System.out.println(conjunctionIter(queue,0));
}

public static boolean conjunctionIter(boolean[] queue,int i){
if(i==queue.length)
    return true;
if(queue[i] == false)
  return false;
  else
return conjunctionIter(queue, i+1);
}
}

Tweak it the way you like. Hope it helped !! :)

Upvotes: 0

Related Questions