This is an assignment for school. I am having trouble understanding how I can print the following recursively:
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 4.
This ALSO written by call number 3.
This ALSO written by call number 2.
This ALSO written by call number 1.
I'm not sure if I am supposed to be illustrating a loop vs. recursion or if there is a way to print all of this recursively. Additionally, how would I go about reversing the recursion call so it starts from 4 as per the example output?
This is my current output.
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 1.
This ALSO written by call number 2.
This ALSO written by call number 3.
This ALSO written by call number 4.
There is no spacing implemented in the for loop yet b/c I'm not sure if that part is also supposed to be recursive.
My code:
public class Recursion {
public static void main(String[] args) {
for (int i = 2; i < 5; i++) {
System.out.println("This was written by call number " + i + ".");
}
recurse(4);
}
public static void recurse(int n) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n < 2) {
System.out.println("This ALSO written by call number " + n + ".");
}
else {
recurse(n - 1);
System.out.println(temp + "This ALSO written by call number " + n + ".");
}
}
A simpler solution.
public static void main(String[] args) {
recurse(1);
}
public static void recurse (int n) {
if (n==5) return;
String temp="";
for (int i=0;i<n;i++) temp += " ";
if (n!=1) {
System.out.println(temp + "This was written by call number " + n + ".");
}
recurse(n+1);
temp=" ";
for (int i=0;i<n;i++) temp += " ";
System.out.println(temp + "This ALSO was written by call number " + n + ".");
}
The key to writing most recursive programs (especially the ones you're given as assignments) is to look for a larger problem that contains a similar but smaller occurrence of the same problem.
In your case, the "larger problem" would be to print the 6 lines that start and end with "call number 2". That is, print lines for call numbers 2 through 4. The way to do this is: print the first line that says "call number 2", solve the problem to print the 4 lines for call numbers 3 through 4, and print the last line that says "call number 2". The part in the middle is the smaller occurrence of the same problem. That's going to be the recursive call.
Since your larger problem is going to start with "call number 2", and your smaller problem is going to start with the call number that's one higher, I'd recommend arranging things so that you call recurse(n+1) instead of recurse(n-1). If you do that, you'll need a second parameter so that you know when to stop recursing--something like recurse(n+1, last).
Hopefully this will be enough to get you thinking on the right track.
Try this:
public static void main(String[] args) {
recurse(1, true, 1);
}
public static void recurse(int n, boolean loop, int add) {
String temp = "";
String out = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (add > 0) {
out = temp + "This was written by call number ";
} else {
out = temp + "This ALSO written by call number ";
}
if (n == 1 && !loop) {
System.out.println(out + n + ".");
return;
} else if (n == 1) {
recurse(n+add, false, add);
} else if (n == 5) {
add = add - 2 * add;
recurse(n+add, false, add);
} else {
System.out.println(out + n + ".");
recurse(n+add, false, add);
}
}
Here is quite a straightforward solution. Also pay attention how you can easily get the indent string (via substring). The recursion is as simple as it gets: print the number, enter the function with a larger number if below the max, then follow back.
class R{
static final String spaces=" ";
public static void main(String[] args) {
rec3(1,4);
}
private static void rec3(int i, int max) {
if (i>1) System.out.printf("%sThis was written by call number: %d%n", spaces.substring(0, i-1), i);
if (i<max) rec3(i+1, max);
System.out.printf("%sThis was ALSO written by call number: %d%n", spaces.substring(0, i-1), i);
}
}
Thanks to everyone for the help. I ended up modifying the solution from #JoseLuis a little bit.
public class Recursion {
public static void main(String[] args) {
recurse(1, 5);
}
public static void recurse(int n, int max) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n == max) {
return;
}
if (n != 1) {
System.out.println(temp + "This was written by call number " + n + ".");
}
recurse(n + 1, max);
System.out.println(temp + "This ALSO was written by call number " + n + ".");
}
}
Related
I need to create a program that reads in a random word using a prompt.
The program needs to produce an output that is the average letter in the string.
If the average of the letters was 97.2 display a small a, but if the average of the letters was 97.5, display a small b.
I need to use type-casting and the charAt method that is part of the string class
This is all the information that I was given on what I have to do, and I am very confused. I don't have any code, because I don't even know where to start on this question. All help would be greatly appreciated.
Thank you! I really appreciate the feedback!
Here is my code post feedback:
public class Average_Of_String {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word;
System.out.println("say something");
word = scan.nextLine();
float sum = 0;
for(int i = 0; i < word.length(); i += 1) {
sum += word.charAt(i);
}
System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
int average = (int) (sum/word.length());
System.out.println((char) average);
}
}
Try this, code is simple and self-explanatory:
class Average {
public static void main(String[] args) {
String word = args[0]; // let us suppose you get the word this way
float sum = 0;
for(int i = 0; i < word.length(); i += 1) {
sum += word.charAt(i);
}
System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
}
}
The charAt function returns a character. Ascii Table states:
an ASCII code is the numerical representation of a character such as
'a' or '#' or an action of some sort
On that site you can see that a equals decimal 97 etc.
This question already has an answer here:
Odds and Evens Applications
(1 answer)
Closed 8 years ago.
How can I display all the evens on one line and all the odds on the next line? need to display 25 integers.
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
System.out.print ("EVENS & ODDS");
for(int i=0; i < 25; i++)
{
numbers [i] = (int) (Math.random()*99) + 1;
if(numbers[i]%2 == 0)
System.out.println(numbers[i] +" " );
else
System.out.println(numbers[i] +" " );
}
}
}
Instead of printing each number immediately, consider building up two strings (the first made up of the evens, and the second the odds). Then print the result strings when you're done. This should require just one loop.
In your providing code you print every number at time when it processed.if you want to print in one line so one possible solution is that you have store numbers in some array, or a string instead of display the number.
So in your code this line must change
System.out.println(numbers[i] +" ");
like this (if you want to store them in string variable)
even += numbers[i] +" ";
and later when loops end you can print out both line one by one.
Hope this will help you
//Snippet
if(numbers[i]%2 == 0)
even += numbers[i] +" ";
else
odd += numbers[i] +" ";
//after loops ends
System.out.println(even);
System.out.println(odd);
Just save all the evens in one array and all the odds in another and then print them seperately.
Well right now you are printing them all individually. what you could do is before the for loop declare a String for the odds and a String for the evens. and initialize them to "". then in the for loop instead of printing, just add the numbers[i] to the string and print them outside of the for loop
Alternatively ...
Read the javadoc for PrintStream, 'cos System.out is a PrintStream. Look at the different print methods available.
Create a string to hold them and just display them at once at the end:
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
String evens = "";
String odds = "";
System.out.print ("EVENS & ODDS");
for(int i = 0; i < 25; i++)
{
numbers [i] = (int) (Math.random() * 99) + 1;
if(numbers[i] % 2 == 0)
evens += numbers[i] + " "; // save it to evens string
else
odds += numbers[i] + " "; // save it to odds string
}
// now print them
System.out.println("Evens: " + evens);
System.out.println("Odds: " + odds);
}
}
I have a homework assignment that requires me to write a program that counts the dots in an input line. So far this is what I have came up with it works (sort of)except that it is counting everything instead of only the dots. I am stuck with how to make the program to only count the dots.
import javax.swing.*;
import java.lang.Character;
public class Assign5_Polk {
public static void main(String[] args) {
String string = JOptionPane.showInputDialog("Give me dots and i will count them : ");
int count = 0;
for (int i = 0; i< string.length(); i++) {
char c = string.charAt(i);
if (string.contains(".")) {
count++;
}
}
System.out.println("There are" + " "+ count + " " + "dots" +" " + "in this string. " + string);
}
}
if (string.contains("."))
This line is checking the whole string and returning true if there is a . anywhere in it.
Instead, you want to test if c is a .
Change the if condition as below :
if (string.contains(".")) { // Check whole String contain dot
count++;
}
to
if (c == '.') { //Check single char of String contain dot
count++;
}
In your for loop, you repeatedly test if the entire string has dots, and increment the counter each time. You need something like if (c == '.') instead, to determine if the character you are looking at is a dot.
Solution without loop ;-)
count = string.replaceAll("[^.]","").length();
This makes your program pretty short:
public static void main(String[] args) {
String string = JOptionPane.showInputDialog("Give me dots and i will count them : ");
int count = string.replaceAll("[^.]","").length();
System.out.println("There are "+ count + " dots in this string: " + string);
}
Please explain how this converts decimal to binary:
import java.util.*;
public class decimalToBinaryTest {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
number = in.nextInt();
if (number < 0) {
System.out.println("Not a positive interger");
}
else {
System.out.print("Convert to binary is: ");
System.out.print(binaryform(number) + ".");
}
}
private static Object binaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return null;
}
remainder = number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
I mainly don't get the bit in private static object. Or the return " ". I really don't see how it does but it works. If you enter 10 it displays: Convert to binary is: 1010.
Do I need the >> 1 or can it be *0.5
There are two important moments in this code:
binaryform(number >> 1);
first: recursion. Call function from this function (foo() {foo();}
second: bitwise. >>1 - shift number for 1 bit, it's the same to devide by 2.
every recursion iteration, code devide number by 2 and print reminder AFTER recursion function works (from last to first). It's like:
{
{
{
{
print inner (fourth iteration
}
print before inner (third iteration)
}
print before before inner (second iteration)
}
print outer (first iteration)
}
I got the code from this question, I ran it in Eclipse and the code was fine, but I confused myself in how the recursion order goes internally.
public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(
System.in));
String text = bufReader.readLine();
shuffle("", text);
}
public static void shuffle(String dummy, String input) {
if (input.length() <= 1)
System.out.println(dummy + input);
else {
for (int i = 0; i < input.length(); i++) {
input = input.substring(i, i + 1) + input.substring(0, i)
+ input.substring(i + 1);
shuffle(dummy + input.substring(0, 1), input.substring(1));
}
}
}
}
I found difficulty in understanding recursion in the for loop of Shuffle. Any pointers in decoding the recursion steps?
EDIT : Okay this is my understanding, say suppose my input is ABC and when i run in the first loop , i get dummy = A and input = BC, so the immediate step would be to go down the recursion for input = BC and dummy = A and then come back to iterate i for the initial input ?
Add a global counter:
static int depth = 0; /* calling depth of the recursive method */
Add as the first line of shuffle:
System.out.printf("%" + depth++ + "s call dummy='%s' input='%s'\n", "", dummy, input);
Add as the last line of shuffle:
System.out.printf("%" + --depth + "s return\n", "");
Run the program. Now you can see what happens.
Think of it as dividing the job in steps. Your shuffle function takes two arguments, dummy for the part of the string that is already shuffled, and input for the part of the string that still has to be shuffled.
At every step, you shuffle the first character of input:
for (int i = 0; i < input.length(); i++) {
input = input.substring(i, i + 1) + input.substring(0, i)
+ input.substring(i + 1);
and then, recursively apply the algorhythm, with the part already shuffled being a character longer:
shuffle(dummy + input.substring(0, 1), input.substring(1));
Until there is nothing more to shuffle:
if (input.length() <= 1)
System.out.println(dummy + input);
It exhaustively shuffles the input by the inputs length, recursively. So once each recursion has shuffled the string by the i'th term, it returns.
This would be an n-squared complexity algorithm in big-O notation.
The shuffling is tricky to work out without a debugger ;)