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...
Related
I tried to check other questions close to this one, but couldn't figure out one answer for mine, that's why sending it as a new post. Hope this won't cause any problem.
I am trying to write a simple JAVA code for number conversion- from decimal to octal or hex. With octal everything is fine, but with hex, the output is in wrong order. like if the answer is 613 - program gives out 316.
Here is my full code:
import java.util.Scanner;
public class Cem {
public static void octalconverter(int a) {
if (a == 0) { //our base
System.out.println(); //I first put here return a, but then it was adding zeros to the end
} else {
System.out.print(a % 8);// first remainder = last digit, and so on
octalconverter(a / 8); //recursively going till it is base
}
}
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}
public static String hexchart(int a) {
String result = "";
if (a <= 9) {
result = a + result;
} else {
if (a == 10)
result = result + "A";
// System.out.print("A");
if (a == 11)
result = result + "B";
// System.out.print("B");
if (a == 12)
result = result + "C";
// System.out.print("C");
if (a == 13)
result = result + "D";
//System.out.print("D");
if (a == 14)
result = result + "E";
//System.out.print("E");
if (a == 15)
result = result + "F";
// System.out.print("F");
}
return result;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner oScan = new Scanner(System.in);
System.out.println("Please enter your decimal number : "); //getting input
int num = oScan.nextInt(); //assigning
System.out.println("Enter 1 for Octal Base Conversion #### Enter 2 for Hex Conversion");
int num2 = oScan.nextInt();
if (num2 == 1) {
System.out.print(num + " in Octal(base8) system is : ");
octalconverter(num); //conversion
} else if (num2 == 2) {
System.out.print(num + " in Hexadecimal(base16) system is : ");
hexconverter(num);
} else {
System.out.println("You entered a wrong choice for conversion type, please restart the program");
}
}
}
Can you please tell me where I messed up. I also must say I am looking for the mistake I did here, not another way of how to write this code. Thank you those who are willing to share another way of it, but again I need to learn my mistake here.
Thank you for your help
Change
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}
To
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
hexconverter(a / 16);
System.out.print(hexchart(a % 16));
}
}
Your octal conversion is also not working properly. It prints in reverse order. So just swapped those instructions also.
Bill Gates once said that he would always "hire a lazy person to do a difficult job" at Microsoft. ... "Because a lazy person will find an easy way to do it."
I know you said you aren't looking for another way of how to write this code but this is much easier way to get the job done.
public static String octalNumber = "";
public static void octalconverter(int a){
while(a!=0){
octalNumber = octalNumber + String.valueOf(a%8);
a = a/8;
}
System.out.println(new StringBuilder(octalNumber).reverse().toString());
}
Final number has to be reversed.That was a mistake.
I'm trying to build the following string using recursion in Java. The expected output is:
4! = 4!
= 4 * 3!
= 4 * 3 * 2!
= 4 * 3 * 2 * 1!
= 4 * 3 * 2 * 1 * 0!
This is my factorial method:
public static String factorial(int n, int count, String equation)
{
if (n == 0) {
return equation += (n + "!");
} else {
equation += (n - count);
return factorial(n - 1, count, equation);
}
}
I'm entering the following input in my main method:
System.out.print(factorial(4, 0, ""));
It currently prints out the String "43210!" I haven't worked with recursion much. What am I doing wrong?
I changed some your code,then code can achieve one's goals.here is the code.I hope this can help you.
public class Snippet {
public static String factorial(int n, String equation)
{
if (n == 0) {
return equation += (n + "!");
} else {
equation += (n + "*");
return factorial(n - 1, equation);
}
}
public static void factorial1(int n, String equation)
{
if(n < 0)
{
return;
}
System.out.println(equation + n + "!");
factorial1(n - 1, equation + n + "*");
}
public static void main(String [] arg)
{
System.out.println("4! ");
System.out.println(factorial(4, "="));
System.out.println();
factorial1(4, "=");
}
}
If you want to achieve your goal using only one recursion function, it will require nested recursion. You might want to try something like following:
public class Factorial {
public static void main(String[] args) {
System.out.println(factorial(4));
}
private static String factorial(int origNum, int lineNum, int innerLoopNum, String equation) {
if(innerLoopNum == origNum - lineNum) {
equation = equation + innerLoopNum + "!" + "\n";
}
else if(lineNum > origNum)
return equation;
else {
equation = equation + innerLoopNum + "*";
equation = factorial(origNum, lineNum, --innerLoopNum, equation);
return equation;
}
++lineNum;
if(lineNum > origNum)
return equation;
return factorial(origNum, lineNum, origNum, equation);
}
public static String factorial(int n) {
return factorial(n, 0, n, "");
}
}
Assuming that n will never be negative, this should suffice...
public String factorialString(int n) {
if (n == 0) return "0!";
return n + " * " + factorialString(n - 1);
}
Just for fun, you can also write it as:
public String factorialString(int n) {
return (n == 0)
? "0!"
: n + " * " + factorialString(n - 1);
}
For people concerned, I know I am doing a string concatenation and I should use a StringBuilder instead. The task is to demonstrate recursion here.
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
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 );
}
}
We have as an exercise the task of finding errors in the following loop. The task of the loop is to output the number of digits of a number before the ".", i.e. "32782.12" would be equal to 5. Now so far, I really do not see any error. The only thing that is the case is that an input = 0 would not lead to a correct answer - do you have me any hint?
public class countingDigits {
public static void main(String[] args) {
double number = 88888888.99;
for(int digits=0; digits<6; ++digits) {
if (number*number < 1) {
System.out.println("The number has " + digits + " digits");
break;
}
number /= 10;
}
}
}
Is is not unusual to handle the special cases separately:
0
-0 (where applicable...)
maximum value of datatype (Double.MAX_VALUE)
minimum value of datatype (Double.MIN_VALUE)
etc.
So I'd handle 0 this way:
if(number==0.0 ) {
return 1;
}
public void countingDigits {
public static void main(String[] args){
double number = 88888888.99;
if (number == 0){
System.out.println("The number has 1 digits");
}else {
for(int digits=0; digits<20; ++digits) {
if (number < 1) {
System.out.println("The number has " + digits + " digits");
break;
}
number /= 10;
}
}
}