I'm trying to solve this problem but in stuck in converting my while loop into recursion
Ive managed to implement the printMany function as follows
public static void printMany(int count, String s){
if(count >= 1) {
System.out.print(s);
printMany(count-1, s);
}
}
But the current implementation of the hourglass method still uses loops though it displays the correct output.
public static void hourglass(int numberOfStars, int numberOfSpaces){
while(numberOfStars>0){
printMany(numberOfSpaces++, " ");
printMany(numberOfStars--, "X ");
System.out.println();
}
numberOfSpaces -=2;;
numberOfStars += 2;
while(numberOfSpaces>=0){
printMany(numberOfSpaces--, " ");
printMany(numberOfStars++, "X ");
System.out.println();
}
}
I want to ask, how can I convert this while loop into a recursive call?
I'm not just going to give you the answer, but I'll try to help you along. If you want to break this down using recursion and without loops, the key really is to figure out what the parameters of your recursive helper function must be. It seems like you will always need to remember the original user input (to know how many spaces to print out and to know when to stop the recursion), the current number of stars you're on, and whether you're on the top half of the pyramid or the bottom half. Given all of that information, you should be able to do two things. First, you should be able to correctly print out a line. Second, you should be able to determine what the next line should be. Given this, you can print and recurse, stopping once your base case is reached.
This is one possible solution:
public static void printMany(int count, String s) {
if (count == 0)
return;
System.out.print(s);
printMany(count - 1, s);
}
public static void upperhalf(int count, int max) {
if (count == 0)
return;
printMany(max - count, " ");
printMany(count, "* ");
System.out.println();
upperhalf(count - 1, max);
}
public static void lowerhalf(int count, int max) {
if (count == max)
return;
printMany(max - count - 1, " ");
printMany(count + 1, "* ");
System.out.println();
lowerhalf(count + 1, max);
}
public static void hourglass(int n) {
upperhalf(n, n);
lowerhalf(0, n);
}
Calling hourglass(1); within e.g. main results to:
*
*
So hourglass(2); prints:
* *
*
*
* *
And so on...
Instead of a while looping your program you call the same function.
public static void hourglass(int numberOfStars, int numberOfSpaces){
hourglass(numberOfStars, numberOfSpaces, false);
}
private static void hourglass(int numberOfStars, int numberOfSpaces, boolean dir){
if(dir==false && numberOfStars > 0){
printMany(numberOfSpaces, " ");
printMany(numberOfStars, "X ");
System.out.println();
hourglass(--numberOfStars, ++numberOfSpaces, false);
return;
}
if(numberOfStars==0){
numberOfSpaces -=2;
numberOfStars += 2;
}
if(numberOfSpaces>0){
printMany(numberOfSpaces, " ");
printMany(numberOfStars, "X ");
System.out.println();
hourglass(++numberOfStars, --numberOfSpaces, true);
}
}
Here's a piece of code for you. Used symmetrical padding.
public class Hourglass {
public static void printRow(int nStars, int padding) {
if (nStars == 0)
return;
if (padding > 0) {
System.out.print(" ");
printRow(nStars, padding - 1);
System.out.print(" ");
return;
}
if (nStars <= 0)
return;
System.out.print("*");
if (nStars > 1) {
System.out.print(" ");
printRow(nStars - 1, padding);
}
}
public static void printTop (int height, int padding) {
if (height == 0)
return;
printRow(height,padding);
System.out.print("\n");
printTop(height - 1, padding + 1);
}
public static void printBottom(int currentHeight, int height, int padding) {
printRow(currentHeight, padding);
System.out.print("\n");
if (currentHeight < height)
printBottom(currentHeight + 1, height, padding - 1);
}
public static void printHourglass(int height) {
if (height <= 0)
throw new IllegalArgumentException();
printTop(height, 0);
printBottom(1, height, height - 1);
}
public static void main(String[] args) {
printHourglass(5);
}
}
Just split that method into two, here's another recursion solution for your question:
public static void hourglass(int numberOfStars, int numberOfSpaces) {
if(numberOfStars== 0) return;
printMany(numberOfSpaces++, " ");
printMany(numberOfStars--, "X ");
System.out.println();
hourglass(numberOfStars,numberOfSpaces);
numberOfSpaces -=2;
numberOfStars += 2;
if(numberOfStars==2)
hourglassBottom(numberOfStars,numberOfSpaces);
}
public static void hourglassBottom(int numberOfStars, int numberOfSpaces){
if(numberOfSpaces==0 )return;
printMany(numberOfSpaces--, " ");
printMany(numberOfStars++, "X ");
System.out.println();
hourglassBottom(numberOfStars,numberOfSpaces);
}
For example, running hourglass(3,1); would give you following:
X X X
X X
X
X X
X X X
Related
I'm learning about recursive and Greedy algorithms, this code separate the change needed for a original amount. I tried using a recursive algorithm but the code wasn't working properly until I added the break to avoid further iterations. Is this correct?
public class Main {
public static void main(String[] args) {
// write your code here
int[] coinSet = {20,10,5,1};
int N = 214;
GreedyChange greedyChange = new GreedyChange();
greedyChange.greedyChange(coinSet,N);
greedyChange.printChange();
}
}
public class GreedyChange {
private final List<Integer> coins = new ArrayList<>();
public void greedyChange(int[] coinSet, int change) {
if(change<=0){
return;
}
for (int j : coinSet) {
if (change - j >= 0) {
coins.add(j);
change -= j;
greedyChange(coinSet, change);
break;
}
}
}
public void printChange() {
System.out.println("The change is being distributed in " + coins.size() + " coins in the following" +
" way: ");
int sum = 0;
for (int i = 0; i < coins.size(); i++) {
if (i == coins.size() - 1) {
System.out.print( "$" +coins.get(i));
} else {
System.out.print("$" + coins.get(i) + " + ");
}
sum += coins.get(i);
}
System.out.print(" = $" + sum);
}
}
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 writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}
I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.