SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Recursion
Exercise:
Exercises
Question:3 | ISBN:9780136091813 | Edition: 2

Question

Write a method called writeSequence that accepts an integer n as a parameter and prints to the console a symmetric sequence of n numbers composed of descending integers that ends in 1, followed by a sequence of ascending integers that begins with 1. The following table indicates the output that should be produced for various values of n:
Method call Output produced
-----------------------------------------
writeSequence(1); 1
writeSequence(2); 1 1
writeSequence(3); 2 1 2
writeSequence(4); 2 1 1 2
writeSequence(5); 3 2 1 2 3
writeSequence(6); 3 2 1 1 2 3
writeSequence(7); 4 3 2 1 2 3 4
writeSequence(8); 4 3 2 1 1 2 3 4
writeSequence(9); 5 4 3 2 1 2 3 4 5
writeSequence(10); 5 4 3 2 1 1 2 3 4 5

Notice that when n is odd the sequence has a single 1 in the middle, while for even values it has two 1s in the middle. Your method should throw an IllegalArgumentException if it is passed a value less than 1.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package recursion;

public class WriteSequence {

	public static void helper1(int value) {
		System.out.print((value / 2) + " ");
        writeSequence(value - 2);
        System.out.print(" " + (value / 2));
	}
	public static void helper2(int value) {
		 System.out.print(((value + 1) / 2) + " ");
	        writeSequence((value - 2));
	        System.out.print(" " + ((value + 1) / 2));
	}
	public static void writeSequence(int value) {
		if (value < 1)
			throw new IllegalArgumentException();

		if  (value == 1)
			System.out.print("1");
	        
		else if(value == 2) {
	        System.out.print("1 1");
	    }
		// we use helper function to write the  sequence based on even or odd number 
		else if(value%2==0) {
			helper1(value);
		}else
			helper2(value);
		
	}
		
	public static void main(String[] args) {
         int x = 10;
		System.out.print("writeSequence("+x+"): ");
		writeSequence(x);

	}

}
Output:

writeSequence(10): 5 4 3 2 1 1 2 3 4 5

 

0 0

Discussions

Post the discussion to improve the above solution.