Reputation: 95
The wording of the problem is "Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:"
The table is essentially:
1 = 1
2 = 1 1
3 = 2 1 2
4 = 2 1 1 2
5 = 3 2 1 2 3
6 = 3 2 1 1 2 3
My attempted code is
public void writeSequence(int n){
if (n < 1){
throw new IllegalArgumentException();
}
if (n == 1){
System.out.print(n + " ");
}
else if (n == 2){
System.out.print(1 + " " + 1 + " ");
}
else if (n % 2 == 0){
System.out.print(n - (n/2) + " ");
writeSequence(n - (n/2));
System.out.print(n - (n/2) + " ");
}
else{
System.out.print(n-(n/2) + " ");
writeSequence(n - 2 );
System.out.print(n-(n/2)+ " ");
}
}
For inputs 1-10, my code is not generating the correct answer for 6, 8, and 10. Any help is greatly appreciated.
Edit:
Fixed spelling in title
Edit 2:
My results are
1 = 1
2 = 1 1
3 = 2 1 2
4 = 2 1 1 2
5 = 3 2 1 2 3
6 = 3 2 1 2 3 (wrong)
7 = 4 3 2 1 2 3 4
8 = 4 2 1 1 2 4 (wrong)
9 = 5 4 3 2 1 2 3 4 5
10 = 5 3 2 1 2 3 5 (wrong)
If someone could show me where I have made an error in my code that would be great!
Upvotes: 0
Views: 315
Reputation: 424953
Your recursive call passes the incorrect value. Each time the algorithm recurses, it should decrease the value by 2
.
Change this:
writeSequence(n - (n/2));
to this:
writeSequence(n - 2);
Upvotes: 2