Question

In: Computer Science

Without using extra structures, write a recursive method recursivenumberOfNonZeros (Queue<Integer> q)in Test class (in stacks_queues package)...

Without using extra structures, write a recursive method recursivenumberOfNonZeros (Queue<Integer> q)in Test class (in stacks_queues package) that receives a queue contains integer objects and return total number of non zeros in this queue. Then don’t forget to test the method in the main.
Note: Make sure not to change the order of the other values in queue after calling the method.

Solutions

Expert Solution

I have implemented the recursivenumberOfNonZeros (Queue<Integer> q) method which returns total of non zero elements of Queue. So for this method, we have to create one auxillary method (extra method) which maintain the elements order after removing and then count sum of removed element.

It means that we have two methods::

1> public intrecursivenumberOfNonZeros (Queue<Integer> q) :- This method call the recursiveTotal(q,q.size()) which maintain the order and also retrn the total sum of queue elements in recusive mannar.

2> public int recursiveTotal(Queue<Integer> q, int size) :- This method calculate sum of non zero element of queue and also add each element into the queue simultaneously so we can maintain the queue order. It will return sum of queue elements when queue size will becomes zero.

In this method, we remove element then after add that element and call the method recusively by calculating sum of non ero elements.

Note: In below program, I used in-build linkedlist class of java collection framework which is used to store the elements in the Queue data structure. Because Queue<Geneirc> is interface so we can not create object so we have to pass reference of another data structure for storing elements then after we can use Queue methods like q.remove(), q.peek(), etc.

I never used any data structure which calculate sum of non zero elements using recursion. It means that I did not used any data structure in recursiveNumberOfNonZeros() method.

Program:-

package stacks_queues;

/*
    Here we have to use linkedlist which is
    used to create the object of Queue
    
*/
import java.util.LinkedList;

/*
    Here Queue is interface so we have to use linkedlist and give 
    the reference to the queue object
*/
import java.util.Queue;


public class Test {
    
    
    /**
     * return the sum of queue elements
     * @param q
     * @return sum of non zero elements
     */
    public int recursiveNumberOfNonZeros(Queue<Integer> q){
        
        // sum variable pass to the recursiveTotal() which will add the queue elemnts
        int sum = 0;
        
        // call the recursiveTotal() methhod
        int total = recursiveTotal(q,q.size(),sum);
        
        // return the total of non zero queue elements
        return total;
    }
    
    /**
     * return sum of non zero elemnts (Auxillary function)
     * @param q store elements first in first out mannar
     * @param size store the queue length
     * @param sum of non zero element
     * @return 
     */
    public int recursiveTotal(Queue<Integer> q, int size, int sum) {
        
        // when size of queue is become zro then method returns zero
        if(size == 0){
            
            return sum;
        }
        
        int removedElement = 0;
        
        // check whether element of queue is zero or not
        if((removedElement = q.remove()) != 0){
            
            // decrement the current size of the queue
            size--;
            
            
            // add removed element so order of queue is not changed
            q.add(removedElement);

            // calculate sum
            sum = sum + removedElement;
            // call recursively by calculating each removed element
            return recursiveTotal(q, size, sum);
            
        }
        
        // add zero element when queue element is zero
        q.add(0);
        
        // decrement the current size of the queue
        size--;
        // call recursively when queue element is zero
        return recursiveTotal(q, size, sum);
    }
    
    public static void main(String[] args) {
        
        
        // now create an object of Test class
        Test test = new Test();
       // crete an Queue which hold Integers
        Queue<Integer> q = new LinkedList<>();
        
        // add element to the queue
        q.add(0);
        q.add(20);
        q.add(30);
        q.add(0);
        q.add(50);
        
        // call the recursiveNumberOfNonZeors(q)
        System.out.println("result of recursiveNumberOfNonZeros(q) is "+test.recursiveNumberOfNonZeros(q));
        
        System.out.println("\nOrder of Queue is same");
        System.out.println("Queue : "+q.toString());
    }

}

Output:-

I hope you will understand how to calculate the sum of non zero element without affecting the queue order.

Do you feel needful and useful then please upvote me.

Thank you.


Related Solutions

Without using extra data structures, write a recursive method recursiveProdcutQueue ( Queue <Integer> q) in Test...
Without using extra data structures, write a recursive method recursiveProdcutQueue ( Queue <Integer> q) in Test class (in stacks_queues package) that receives a queue of integers and return the product of the integers inside the queue. Then don’t forget to test the method in the main. Make sure not to change values in queue after calling the method use java eclipse please
Write a recursive method that displays an integer value reversely on the console using the following...
Write a recursive method that displays an integer value reversely on the console using the following header: public static void reverseDisplay(int value) For example, reverseDisplay(12345) displays 54321. Write a test program that prompts the user to enter an integer, invokes the method above, and displays its reversal.
/** * Write a recursive function that accepts a Queue<Integer>. It * should change every int...
/** * Write a recursive function that accepts a Queue<Integer>. It * should change every int in this queue to be double its original * value. You may NOT use loops or any other data structures besides * the queue passed in as a parameter. You may use a helper function. * @param q */ public static void doubleElements(Queue<Integer> q) {}
Without using method size(), write recursive method stackSize(Stack > s1 ) that receives a stack and...
Without using method size(), write recursive method stackSize(Stack > s1 ) that receives a stack and returns number of elements in the stack. The elements in the stack should not be changed after calling this method. please do it in java
Write a RECURSIVE method that receives as a parameter an integer named n. The method will...
Write a RECURSIVE method that receives as a parameter an integer named n. The method will output n # of lines of stars. For example, the first line will have one star, the second line will have two stars, and so on. The line number n will have "n" number of ****** (stars) so if n is 3 it would print * ** *** The method must not have any loops!
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Please write in java: Write a recursive method toNumber that forms the integer sum of all...
Please write in java: Write a recursive method toNumber that forms the integer sum of all digit characters in a string. For example, the result of toNumber("3ac4") would be 7. Hint: If next is a digit character ('0' through '9'), Character.isDigit(next) is true and the numeric value of next is Character. digit(next, 10).
Write, in Java, a recursive method countBinaryStrings that has one integer parameter n and returns the...
Write, in Java, a recursive method countBinaryStrings that has one integer parameter n and returns the number of binary strings of length n that do not have two consecutive 0’s. For example, for n = 4, the number of binary strings of length 4 that do not contain two consecutive 0’s is 8: 1111, 1110, 1101, 1011, 1010, 0111, 0110, 0101. For this problem, your method needs to return only the number of such strings, not the strings themselves. You...
java Write a recursive program to reverse a positive integer. . Your method should take a...
java Write a recursive program to reverse a positive integer. . Your method should take a non negative integer as a parameter and return the reverse of the number as an integer. e.g. if you pass 12345, your method should return 54321.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT