FizzBuzz, java code - java

I am trying to create a piece of code for the game 'fizzbuzz', if n|3 => n=Fizz, if n|5 => n= Buzz and if n|3 and n|5 then n=Fizzbuzz.
For some reason my code only displays 46 lines of code, can someone help me out? Thanks.
Here is my code:
import static java.lang.Math.*;
import java.io.*;
public class P2InventedExercise
{
static void FizzBuzz(int n)
{
/** Welcome Message **/
System.out.println("+----------------------------+");
System.out.println("| WELCOME TO FIZZ BUZZ |");
System.out.println("+----------------------------+");
/** Creating Strings to Print & Defines integer 'k'. **/
String Fizz = "Fizz";
String Buzz = "Buzz";
String FizzBuzz = "FizzBuzz";
int k = 0;
/** Printing Strings **/
while (k <= n)
{
/** Boolean Tests **/
boolean FizzTest = (k%3 == 0);
boolean BuzzTest = (k%5 == 0);
boolean FizzBuzzTest = (k%3 == 0 && k%5 == 0);
/** If Tests **/
if (FizzBuzzTest)
{
System.out.println(k+"= " + FizzBuzz);
k=k+1;
continue;
}
if (FizzTest)
{
System.out.println(k + "= " + Fizz);
k=k+1;
continue;
}
else if (BuzzTest)
{
System.out.println(k + "= " + Buzz);
k=k+1;
continue;
}
else
{
System.out.println(k + "= " + k);
k=k+1;
continue;
}
}
}
}

The code looks almost OK, check what is the n.
Also, pay attention you're missing else in the second if statement. It should be:
else if (FizzTest)

GentleCynic your solution is very close, please checkout my video for a detailed explanation located on youtube
This particular module will run 60 times
package java_basics;
public class FizzBuzz {
public static void main(String[] args) {
printFizzBuzz(60); // shorthand for initializing the runtimes
}
public static void printFizzBuzz(int runtimes) { //internal method using the "100 times to run" with declaration of n as integer
for (int number = 0; number <= runtimes; number++) { // create the number of times it should run
if ((number % 3 == 0) && (number % 5 == 0)) { //control flow using modulus operator "%" which means divisible by 3 and "&&" 5
System.out.println("FizzBuzz because the number is " + number + " which is divisible by both 3 and 5"); //prints out the actual number and fizzbuzz
}
else if (number % 3 == 0) { //otherwise if number is only divisible by 3 print "fizz"
System.out.println("Fizz because th number is " + number + " which is only divisible by 3 which is"); //prints fizz
}
else if (number % 5 == 0) {
System.out.println("Buzz because the number is " + number + " which is only divisbe by 5"); //prints buzz
}
else {
System.out.println(number + " This number is not divisible by 3 or 5, therfore there is no fizz or buzz condition met"); // this number is printed without a fizzbuzz
}
}
}
}

function fizzBuzz(n) {
//'n' is integer to know the limit
for(let i =1; i <= n;i++){
//if i multiple of 3 and 5 print 'FizzBuzz'
if(i % 3==0 && i%5==0){
console.log('FizzBuzz')}
//if i multiple of 3 but not 5 print 'Fizz'
else if(i % 3==0 && i%5!==0){
console.log('Fizz')}
//if i not multiple of 3 and multiple 5 print 'Buzz'
else if(i % 3!==0 && i%5==0){
console.log('Buzz')}
//if i not multiple of 3 and not multiple 5 print 'Buzz'
else if(i % 3!==0 && i%5!==0)
{
console.log(i);}
}
}
/*
if n = 15
output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
undefined

Related

Palindromic numbers in Java

I write program to solve several problems with numbers. My program should:
Welcome users;
Display the instructions;
Ask for a request;
Terminate the program if a user enters zero;
List item
If a number is not natural, print an error message;
Print the properties of the natural number;
Continue execution from step 3, after the request has been processed.
I got an error:
The program should continue to work till the user enter 0.
Here is my code:
package numbers;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Amazing Numbers!\n" +
"\n" +
"Supported requests:\n" +
"- enter a natural number to know its properties;\n" +
"- enter 0 to exit.\n" +
"\n" +
"Enter a request:");
int number = scanner.nextInt();
if (number >= 0) {
System.out.println("Properties of " + number);
System.out.println("\t even: " + (number % 2 == 0));
System.out.println("\t odd: " + (number % 2 != 0));
System.out.println("\t buzz: " + checkBuzzNumber(number));
System.out.println("\t duck: " + checkDuckNumber(number));
System.out.println("\t palindromic: " + checkPalindromicNumber(number));
} else {
System.out.println("The first parameter should be a natural number or zero.");
}
}
public static boolean checkBuzzNumber(int number) {
return number % 7 == 0 || String.valueOf(number).endsWith("7");
}
public static boolean checkDuckNumber(int number) {
String num = String.valueOf(number);
boolean flag = false;
if (num.startsWith("0")) {
return false;
} else {
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) == '0') {
flag = true;
break;
}
}
return flag;
}
}
public static boolean checkPalindromicNumber(int number) {
int rem, rev = 0, temp;
temp = number;
while (number != 0) {
rem = number % 10;
rev = rev * 10 + rem;
number = number / 10;
}
if (temp == rev)
return true;
else
return false;
}
}
You are just a loop away from getting the desired output, below is the code with comments to understand properly. Also, I have commented the code which you wrote but I removed from there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// System.out.println("Welcome to Amazing Numbers!\n" +
// "\n" +
// "Supported requests:\n" +
// "- enter a natural number to know its properties;\n" +
// "- enter 0 to exit.\n" +
// "\n" +
// "Enter a request:");
// int number = scanner.nextInt();
//-------------------------------------------------------------
while (true)// added an infinite while loop, in order to display and take input continuously
{
System.out.println("Welcome to Amazing Numbers!\n" +
"\n" +
"Supported requests:\n" +
"- enter a natural number to know its properties;\n" +
"- enter 0 to exit.\n" +
"\n" +
"Enter a request:");
int number = scanner.nextInt();
if (number == 0)// checks for the number to be zero or not.
{
break; // jump statement, breaks out of the loop.
}
if (number > 0) {// if entered number is greater than zero,
System.out.println("Properties of " + number);
System.out.println("\t even: " + (number % 2 == 0));
System.out.println("\t odd: " + (number % 2 != 0));
System.out.println("\t buzz: " + checkBuzzNumber(number));
System.out.println("\t duck: " + checkDuckNumber(number));
System.out.println("\t palindromic: " + checkPalindromicNumber(number));
System.out.println();// for a new line
}
else // if number is less than zero,
{
System.out.println("The first parameter should be a natural number or zero.\n");
}
}
scanner.close();//good practice to close the scanner.
//____________________________________________________________
// if (number >= 0) {
// System.out.println("Properties of " + number);
// System.out.println("\t even: " + (number % 2 == 0));
// System.out.println("\t odd: " + (number % 2 != 0));
// System.out.println("\t buzz: " + checkBuzzNumber(number));
// System.out.println("\t duck: " + checkDuckNumber(number));
// System.out.println("\t palindromic: " + checkPalindromicNumber(number));
// } else {
// System.out.println("The first parameter should be a natural number or zero.");
// }
}
public static boolean checkBuzzNumber(int number) {
return number % 7 == 0 || String.valueOf(number).endsWith("7");
}
public static boolean checkDuckNumber(int number) {
String num = String.valueOf(number);
boolean flag = false;
if (num.startsWith("0")) {
return false;
} else {
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) == '0') {
flag = true;
break;
}
}
return flag;
}
}
public static boolean checkPalindromicNumber(int number) {
int rem, rev = 0, temp;
temp = number;
while (number != 0) {
rem = number % 10;
rev = rev * 10 + rem;
number = number / 10;
}
if (temp == rev)
return true;
else
return false;
}
}

Unable to figure out why my output is incorrect for this program

I'm creating a program that turns a user inputted number into English (eg 56 = fifty six). However, my output is completely incorrect. I've tried playing around with it and I'm not sure exactly what's wrong. This is the code I'm using! The number 7 outputs "zero thousand zero", the number 86 outputs "zero thousand eight", and the number 7556 outputs an error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 53 out of bounds for length 8
at SayingNumbers.twoDigitToStr(SayingNumbers.java:51)
at SayingNumbers.threeDigitToStr(SayingNumbers.java:70)
at SayingNumbers.numToStr(SayingNumbers.java:120)
at SayingNumbers.main(SayingNumbers.java:135)
This is the code I've been using! Any help troubleshooting would be much appreciated!
//This program takes a user inputted number and writes out the corresponding words in English
import java.util.Scanner;
public class SayingNumbers {
//This returns the English word for numbers 0 - 9
public static String oneDigitToStr(int num) {
switch (num) {
case 0 : return "zero";
case 1 : return "one";
case 2 : return "two";
case 3 : return "three";
case 4 : return "four";
case 5 : return "five";
case 6 : return "six";
case 7 : return "seven";
case 8 : return "eight";
case 9 : return "nine";
}
return"";
}
//This returns the English words for numbers 10 - 99
public static String twoDigitToStr(int num) {
//This returns the English word for numbers 10 - 19
switch(num){
case 10 : return "ten";
case 11 : return "eleven";
case 12 : return "tweleve";
case 13 : return "thirteen";
case 14 : return "fourteen";
case 15 : return "fifteen";
case 16 : return "sixteen";
case 17 : return "seventeen";
case 18 : return "eighteen";
case 19 : return "nineteen";
}
//This returns the English word for multiples of 10 up until 90.
String tens[] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
int onesPlace;
int tensPlace;
int i;
i = num;
onesPlace = i%10; //Finds ones place
i /= 10;
tensPlace = i; //Finds tens place
if(tensPlace == 0) {
return oneDigitToStr(onesPlace); //Calls oneDigitToStr for single digit numbers
}
if(onesPlace == 0) {
return tens[tensPlace - 2]; //Multiples of 10
}
//Returns all other two digit numbers > 20
return tens[tensPlace - 2] + " " + oneDigitToStr(onesPlace);
}
//Returns the English words for numbers 100-999
public static String threeDigitToStr (int num) {
String hundreds = "hundred";
int hundredsPlace;
int tensPlace;
int onesPlace;
int i;
i = num;
onesPlace = i % 100;
hundredsPlace = i / 100;
i = num;
i = i - hundredsPlace;
tensPlace = i / 10;
if (hundredsPlace == 0) {
return twoDigitToStr(tensPlace);
}
i = num - hundredsPlace;
return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(i);
}
//Returns the English words for numbers 1000+ (within int parameters)
public static String numToStr (int num) {
String userNum = Integer.toString(num);
int billions;
int millions;
int thousands;
int hundredsPlace;
int tensPlace;
int onesPlace;
int i = num;
int n = userNum.length();
if (n > 9) {
if (n < 12) {
n = 12 - n;
while (n > 0) {
userNum = "0" + userNum;
n--;
}
}
billions = Integer.parseInt(userNum.substring(0,3));
millions = Integer.parseInt(userNum.substring(3,6));
thousands = Integer.parseInt(userNum.substring(6,9));
hundredsPlace = Integer.parseInt(userNum.substring(9,12));
return threeDigitToStr(billions) + " billion " + threeDigitToStr(millions) + " million " + threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace);
}
else if (n > 6 && n <= 9) {
if (n < 9) {
n = 9 - n;
while (n > 0) {
userNum = "0" + userNum;
n--;
}
}
millions = Integer.parseInt(userNum.substring(0,3));
thousands = Integer.parseInt(userNum.substring(3,6));
hundredsPlace = Integer.parseInt(userNum.substring(6,9));
return threeDigitToStr(millions) + " million " + threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace);
}
else if (n > 3) {
if (n < 6) {
n = 6 - n;
while (n > 0) {
userNum = "0" + userNum;
n--;
}
}
thousands = Integer.parseInt(userNum.substring(0,3));
hundredsPlace = Integer.parseInt(userNum.substring(3,6));
return threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace);
}
else {
return threeDigitToStr(Integer.parseInt(userNum));
}
return "";
}
//This gets user input
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numEntered;
while(true) {
System.out.print("Enter an integer to pronounce (any negative value to exit): ");
numEntered = scnr.nextInt();
if (numEntered < 0) {
break;
}
System.out.println(numEntered);
String numToString = numToStr(numEntered);
System.out.println(numToString);
}
System.out.println("kthxbye!");
}
}
In your code, there are multiple problems but at one line your logic fails and that line is in method threeDigitToStr(the last line i.e. return statement has i in place of onesPlace. So, change below-suggested code:
instead of
return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(i);
modify to
return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(onesPlace);
Complete code can be viewed online.

Trying to correctly determine whether numbers are weird

Made a program that prints if a number is weird or not. If the number is odd, it's weird. If the number is even and inclusively between 2 and 5, it is not weird. If it's even and inclusively between 6 and 20, it's weird, and if it's even and greater than 20, it's not weird. The problem I'm having here is that instead of the output displaying "This number is weird/not weird", I get "Weird" or "Not Weird" on one line, followed by "This number is 0" if it's even, or "This number is 1" if it's odd.
public Weird(int num)
{
n = num;
}
public int EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && answer >= 2 && answer <= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && answer >= 6 && answer <= 20)
{
System.out.println("Weird");
}
else if (check == 0 && answer > 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
return check;
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You actually return int which is value of check field. This is either 1 or 0.
When you call this line-
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
It prints either This number is 0 or This number is 1.
You can get desired output by two ways-
Way 1-
Change return type of method to void EvenOrOdd() like-
public void EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n<= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && n>= 6 && n<= 20)
{
System.out.println("Weird");
}
else if (check == 0 && n> 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
}
and call method in main as-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
w.EvenOrOdd();
a.EvenOrOdd();
}
Way 2- Change return type of method to String as-
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n>= 2 && n<= 5)
{
return "Not Weird";
}
else if (check == 0 && n>= 6 && n<= 20)
{
return "Weird";
}
else if (check == 0 && n> 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
And main method remains same-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You should return that string rather than printing it. In your function, you are returning an int but rather you should write a String. Besides that everything looks good but you can decrease the number of check like below:
public Weird(int num)
{
n = num;
}
public String EvenOrOdd()
{
int check = n % 2;
if (check == 1 || (check == 0 && n >= 6 && n <= 20)) {
return "Weird";
}else{
return "Not Weird";
}
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
The value you return from a method will kind of "replace" the method call. Because you returned check:
return check;
The calls:
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
are basically:
System.out.println("This number is " + 0);
System.out.println("This number is " + 1);
You seem to be confused about returning and printing. Your method should look like this:
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n <= 5)
{
return "Not Weird";
}
else if (check == 0 && n >= 6 && n <= 20)
{
return "Weird";
}
else if (check == 0 && n > 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
Now the two calls is basically:
System.out.println("This number is " + "Weird");
System.out.println("This number is " + "Not Weird");

Hailstone Sequence, recursive, missing the 1 case

I have the following hailstone sequence code, which works for all numbers, beside the sequence of 1:
public class Recursion {
public static void main(String[] args) {
hailstone(16); // prints 16 8 4 2 1
hailstone(1); //prints just 1 instead of 1 4 2 1
}
public static void hailstone(int seed) {
String str = "" + seed;
if (seed == 1) {
System.out.print(str);
} else {
if (seed % 2 == 0) {
System.out.print(str + " ");
hailstone(seed / 2);
} else {
System.out.print(str + " ");
hailstone((3 * seed) + 1);
}
}
}
}
How can I bypass this special case while staying in recursive method and in void?
I'm not allowed using any kind of loops.
1 is the exit point of your recursion, that's why you can't make it also behave like an entry point.
What if you change the exit point? Make 2 the pre-exit point:
public static void hailstone(int seed) {
String str = "" + seed;
if (seed == 2) {
System.out.print(str + " 1");
} else {
if (seed % 2 == 0) {
System.out.print(str + " ");
hailstone(seed / 2);
} else {
System.out.print(str + " ");
hailstone((3 * seed) + 1);
}
}
}
public static void main(String[] args) {
hailstone(16);
System.out.println();
hailstone(15);
System.out.println();
hailstone(1);
System.out.println();
}
will print:
16 8 4 2 1
15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
1 4 2 1
At the end a small note for your information (I am surprised to see all static in the code).
To the point. You say that:
you cannot change the signature
you must use recursion (no loops allowed)
Define a static boolean and add a condition for the case you reach the number 1.
The last sequence in the hailstone sequence is an infinte pattern. The special case is because you need the program to stop at some point. Here I simply use a boolean to print the pattern once after the number 1 has been reached for the first time. I hope the code is self explaining.
public class Recursion {
private static boolean reached = false;
public static void main(String[] args) {
//hailstone(16); // prints 16 8 4 2 1
hailstone(1); //prints just 1 instead of 1 4 2 1
}
public static void hailstone(int seed) {
String str = "" + seed;
if (seed == 1 && reached) {
System.out.print(str);
} else if (seed == 1 && !reached) {
System.out.print(str + " ");
reached = true;
hailstone((3 * seed) + 1);
} else {
if (seed % 2 == 0) {
System.out.print(str + " ");
hailstone(seed / 2);
} else {
System.out.print(str + " ");
hailstone((3 * seed) + 1);
}
}
}
}
Note: In Java usually it is not a good practice to code a lot of static members/methods. It could be designed better I believe. I did not want to go into this because I do not want to confuse and I would like to focus on the question.
There is a downside to code it the way I did for example. Simply try to call hailstone(16) and hailstone(1) subsequently and you will see what I mean; this is because the boolean had already been set from the first sequence calculation. You would need to reset it to false again. There are better ways to design this...

Using recursion, in java, to have a variety of outputs from a single int parameter

If anyone is familiar with PracticeIt, it's what I'm doing and I'm on recursion problem sets. I'm having trouble doing them. Here's one problem:
Write a method writeSquares that accepts an integer parameter n and prints the first n squares separated by commas, with the odd squares in descending order followed by the even squares in ascending order. The following table shows several calls to the method and their expected output:
writeSquares(5); ----> Output: 25, 9, 1, 4, 16
writeSquares(1); ----> Output: 1
I've spent a few hours each day for the past 3 days figuring out recursions but I just can't figure it out.
Can anyone point me in the right direction?
My code looks like:
public static void writeSquares(int n)
{
if(n<1)
throw new IllegalArgumentException();
else{
if(n%2==0){
System.out.print((n-1)*(n-1));
writeSquares2(n-1, n-1, "down");
}
else{
System.out.print(n*n);
writeSquares2(n-1, n-1, "down");
}
}
}
public static void writeSquares2(int n, int m, String s)
{
if(m==0){
return;
}
String ss = s;
if(n<=1){
ss = "up";}
if(n%2==1&&s=="down"){
System.out.print(", " + n*n);
writeSquares2(n-2,m-1,ss);
}
if(n%2==0&&s=="down"){
writeSquares2(n-1,m-1,ss);
System.out.print(", " + n*n);
}
if(n%2==1&&s=="up"){
System.out.print(", " + n*n);
writeSquares2(n+2,m-1,ss);
}
if(n%2==0&&s=="up"){
writeSquares2(n+1,m-1,ss);
System.out.print(", " + n*n);
}
EDIT: Woops I fixed the code below
And another question from another problem set 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:
writeSequence(9); -----> 5 4 3 2 1 2 3 4 5
writeSequence(10); -----> 5 4 3 2 1 1 2 3 4 5
My code:
public void writeSequence(int n)
{
if(n<1)
throw new IllegalArgumentException();
else
writeSequence2(n, n, "down"); //I actually dont need the second parameter
}
public void writeSequence2(int n, int m, String s)
{
String ss = s;
if(n/2-1==1)
ss = "up";
if(n==1)
System.out.print(n);
else if(ss.equals("down")){
if(n%2==0){
System.out.print(n/2+" ");
writeSequence2(n-1, m-1, ss);
}
else if(n%2==1){
writeSequence2(n-1, m-1, ss);
System.out.print(" "+ (n/2+1));
}
}
else if(ss.equals("up")){
if(n%2==0){
System.out.print(n/2+" ");
writeSequence2(n-1, m-1, ss);
}
else if(n%2==1){
writeSequence2(n-1, m-1, ss);
System.out.print(" " + (n/2+1));
}
}
}
For the second one, my code is somewhat correct. Except when n is odd.
Also another question - is it possible to do these with just a single method?
Thanks for your time. The tutors in my school aren't very helpful and neither are my classmates.
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(n/2 +" " + n/2);
}
else if(n%2 ==0){
System.out.print(n/2 +" ");
writeSequence(n-2);
System.out.print(" " +n/2);
}
else if(n%2 ==1){
System.out.print( (n/2+1) +" ");
writeSequence(n-2);
System.out.print( " "+(n/2 +1));
}
}
I realize this is an old thread but in case anyone still gets directed to this page, I just had this question as well. this is how I answered it without a helper method. by the way its really close to Eran's 1st answer except I took my writeSequence out of the if statement. this worked.
public void writeSquares(int n) {
//for exception
if (n < 1) {
throw new IllegalArgumentException();
//for base
} else if (n == 1) {
System.out.print("1");
return;
}
//printing evens before base
// commas trail number now
if ((n % 2) != 0) {
System.out.print((n * n) + ", ");
}
//does this until base
writeSquares(n - 1);
//then as we start coming back out of the method calls print evens
// commas before lead numbers now
if ((n % 2) == 0) {
System.out.print(", " + (n * n));
}
}
Create two arraylists that EvenList and oddList
if squared value matches even condition put it in evenList, else in oddList.
First print oddList in reverse order and print evenList as it is from index 0.
The idea is that if n is odd, you want to print n*n immediately (which would print the odd squares in descending order), and then make a recursive call with n-1, while if n is even, you first make the recursive call with n-1 and then print n*n (which would print the even squares in ascending order after all the odd squares are printed).
public static void writeSquares(int n){
if(n<1)
throw new IllegalArgumentException();
if (n==1)
System.out.print(1 + ",");
else if (n % 2 == 1) {
System.out.print(n*n + ",");
writeSquares (n - 1);
} else {
writeSquares (n - 1);
System.out.print(n*n + ",");
}
}
EDIT : this code would produce an extra , at the end.
25,9,1,4,16,
To get rid of that, you might have to add a boolean parameter to the method, which indicates whether it's the first call to the method or not.
For writeSequence, the idea is to solve the problem for n assuming you already have the solution for n - 1. If you have a method the writes the sequence for n - 1, in order to expand it to n, you have to print n, print the sequence for n - 1, and print n again. In addition, you need a stopping condition, which is n==1, in which case you just print 1.
public static void writeSequence(int n)
{
if(n<1)
throw new IllegalArgumentException();
if (n==1)
System.out.print(1 + " ");
else {
System.out.print(n + " ");
writeSequence (n-1);
System.out.print(n + " ");
}
}
EDIT:
I missed some details in the question about the second recursion. Here's the updated method. I'm not sure if it's possible to have all the logic in a single method. I had to split it to two recursive methods, based on whether n is odd or even.
public static void writeSequence(int n)
{
if (n%2 == 0)
writeSequenceEven (n);
else
writeSequenceOdd (n);
}
public static void writeSequenceOdd(int n)
{
if (n == 1) {
System.out.print (1 + " ");
} else if (n>1) {
System.out.print((1+n/2) + " ");
writeSequenceOdd (n-2);
System.out.print((1+n/2) + " ");
}
}
public static void writeSequenceEven(int n)
{
if (n>1) {
System.out.print(n/2 + " ");
writeSequenceEven (n-2);
System.out.print(n/2 + " ");
}
}
Here is my solution, it's pretty compact and should work.
public static void writeSequence(int n) {
if (n <= 1){
System.out.print(1);
} else if (n % 2 != 0){
System.out.print(n*n + ", ");
writeSequence(n-1);
} else{
writeSequence(n-1);
System.out.print(", " + n*n );
}
}

Categories