I want to print a pyramid of pins using recursion(no Loops). I got the code almost done, but my pyramid is upside down, and it is not formatted. How can I fix it.
Below is my source code:
public void pinPattern(int count) {
if(count == 1)
System.out.println("*");
else {
System.out.print("*");
pinPattern(count - 1);
}
}
public int numberOfPins(int n) {
if(n == 0)
return 0;
else {
pinPattern(n);
return n + numberOfPins(n - 1);
}
}
public static void main(String[] args) {
Recursion x = new Recursion();
System.out.println("The number of pin: " + x.numberOfPins(5));
}
Thanks in advance.
So there are two considerations here. First, the need to have the pyramid go the other direction. If it is printing upside-down, then instead of counting down (which goes from max to min), invert the approach. Something like:
public static int pinPatternUp(int numPins, int maxPins)
{
if (numPins <= maxPins) {
// this will add spaces
spaces(maxPins - numPins);
pins(numPins);
return numPins + (pinPattern(numPins + 1, maxPins));
}
return 0;
}
The logic for the pins method (which in the OP's code was 'pinPattern) in the OP's approach is essentially fine for either direction. However, making this change (so that there is a space after each*`) will allow for a bit better formatting.
System.out.print("* ");
The second question is one of formatting. In this case, we can look at the pyramid as requiring N spaces before the first output. And with a bit of investigation, it appears that a given line will have the total number of rows - the current row in terms of spaces. Using recursion, it is possible to do something like:
public static void spaces(int num)
{
if (num == 0) {
return;
}
System.out.print(" ");
spaces(num - 1);
}
Note that one can now have an "up" or "down" facing pyramid depending upon whether the pinPattern is increasing or decreasing.
Note: due to some editing, the method names do not exactly align with the OP's.
public static void main(String[] args)
{
pinPatternUp(1, 5);
pinPatternDown(5, 5);
}
Output if run up and then down:
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
Related
This code prints all prime numbers between start and end, based on the user's input.
What is its complexity? Is it O(end * sqrt(n))?
/**
* Print prime numbers between start and end inputs
* Time-Complexity: O(end * sqrt(n))
* Space-Complexity: O(1) only one value as input
* #param start, end
* #return
*/
public void printPrimeSeries(int start, int end) {
for (int i = start; i < end; i++) {
if (findPrimeOrNot(i)) {
System.out.println("The value " + i + " is a prime number");
}
}
}
public boolean findPrimeOrNot(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter start number for prime:");
int startInput = scanner.nextInt();
System.out.println("Enter end number for prime:");
int endInput = scanner.nextInt();
PrimeNoSeries primeNoSeries = new PrimeNoSeries();
primeNoSeries.printPrimeSeries(startInput, endInput);
}
Going step by step, to be concise, let's call your start value m, and end as n:
printPrimeSeries method is linearly corelated to n - m
For each element within the range above, the complexity of inner loop is sqrt(n) - 2. Neglecting the constant it is sqrt(n)
So, the complexity appears to be O((n - m) * sqrt(n)).
The overall complexity is O(end - start) * sqrt(end)). FYI: I show you an alternative estimation, which is not as tight:
In O-notation you are interested in the worst case, therefore we can assume that start is always 0. Now we only need end for the analysis.
The method printPrimeSeries is just O(end), from 0 to end. The method uses findPrimeOrNot that iterates from 2 to Math.sqrt(n), which is O(sqrt(n)). The maximum value for n is the value of end, so we can call the complexity O(sqrt(end)) for our purposes. Combining both is O(end) * O(sqrt(end)), which is just O(end sqrt(end)).
There are interesting details to the question, which have to do with the distribution of prime numbers. You can read about it here.
I tried to find any sequence or formula for below star pattern but i did not found, so simply tried below
public class MyClass {
public static void main(String args[]) {
System.out.println("....*....");
System.out.println("...***...");
System.out.println("*********");
System.out.println(".*******.");
System.out.println("*********");
System.out.println("...***...");
System.out.println("....*....");
}
}
Here "." means " " space character.
Can we print this star using loop ?
Not sure what you mean, but if you really want a loop, here is a solution!
public class Star {
public static void main(String[] args) {
int[] dots = new int[] {4, 3, 0, 1, 0, 3, 4};
int width= 9;
for (int i = 0; i < dots.length; i++) {
for (int j = 0; j < width; j++) {
if (j < dots[i] || j > width - dots[i] - 1) {
System.out.print(".");
} else {
System.out.print("*");
}
}
System.out.println();
}
}
}
Hope It Helps! This is Easy to understand for Low Class Students Rather than Creating Arrays
class starPattern {
public static void main(String []args) {
for(int i=1;i<=7;i++) {
for(int j=1;j<=9;j++) {
if(i==3 || i==5 || j==5 || (i==4 && j>1 && j<9) || ((i==2 || i==6) && (j>3 && j<7))) {
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
My Computer Teacher Check it and it was Correct Method!
A Brief Description About this Pattern
1↓ 1→ 2 3 4 5 6 7 8 9
2 *
3 * * *
4 * * * * * * * * *
5 * * * * * * *
6 * * * * * * * * *
7 * * *
8 *
I'm using Java 11. You should be able to draw any enantiomorphic pattern of asterisks. Read the comments for detailed explanation.
import java.util.Arrays;
class Star {
public static void main(String[] args) {
int[] stars = new int[] { 1, 3, 9, 7, 9, 3, 1 }; // asterisks per line
int max = Arrays.stream(stars).max().getAsInt(); // max asterisks in any line
for (int i = 0; i < stars.length; i++) { // prints the asterisks for a given row, and pads it left and right with spaces
System.out.print(" ".repeat((max - stars[i]) / 2) + "*".repeat(stars[i]) + " ".repeat((max - stars[i] + 1) / 2));
}
}
Yes, it can be done using loops and should not be done via sout statements.
Also seems like you are a beginner in programming, so I will suggest you to try out logic for these kind of questions yourself. It will help in your growth.
Just try out line by line.
These questions generally need 2 loops, one to move in vertical direction and other to move in horizontal direction.
You can think it of as a i*j matrix( eg 3X3, 4X4).
So try it out yourself start with some basic one's.
If you still need solution just ping me but please try it on your own first.
so I'm not really sure what to do what I've already done
/*
* a collection of methods to be completed
* complete each TODO body-code for the given methods
* use recursion for the first method and last method
*/
public class Methods
/*
* method to compute value of f(n) where:
* f(1) = 1
* f(n) = n + f(n-1) for n>1, n is even
* f(n) = n * f(n-1) for n>1, n is odd
*/
public static int f(int n) {
//TODO
return 0; //dummy line, replace this
}
/*
* method to compute the sum of the proper divisors of a given positive integer, n
* e.g., if n is 12, the sum of the proper divisors is:
* 1 + 2 + 3 + 4 + 6 = 16
* note: proper divisors are all divisors of an integer other than itself
*/
public static int sumOfDivisors(int n) {
//TODO
return 0; //dummy line, replace this
}
/*
* method that returns a String indicating whether a given positive integer, n, is:
* "abundant" - sum of proper divisors is greater than n
* "deficient" - sum of proper divisors is less than n
* "perfect" - sum of proper divisors is equal to n
*/
public static String numberType(int n) {
//TODO
return "foo"; //dummy line, replace this
}
/*
* method that returns the sum of the digits of the positive integer, n
* e.g., if n = 5403, the method will return:
* 5+4+0+3 = 12
* note: the right-most (1's) digit can be found using n%10
* the remaining digits (all but the 1's digit) can be found using n/10
*/
public static int sumOfDigits(int n) {
//TODO
return 0; //dummy line, replace this
}
//a dummy main method, not used
public static void main(String[] args) {
System.out.println("This program is not meant to be run on its own.");
System.out.println("This is just a dummy main method.");
}
} //end Methods
so yea any help would be great.
so I'm not really sure what to do what I've already done
You actually wrote only method declarations.
Your task is really well documented, you may try out to implement the utilities(like a public int[] divisors(int n) and so on) and eventually come back here and ask help about your concerns, posting either code or errors.
PS:This seems an academic assignment , have you checked some books, or notes?
I'm trying to make a square root calculator with my own function which is sqrt and borrowing a already made one to test accuracy. The issue is every time I output my guess to the screen after putting it into the function the numbers just return as the same number inputted but it has a .0 on it. An example is, when I put in the number 2 I get back 2.0 which is wrong. Please help :)
import java.io.IOException;
import java.util.Scanner;
public class test {
/**
* Main method.
*
* #param args
* the command line arguments
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Scanner data = new Scanner(System.in);
double root;
/*
* Put your main program code here; it may call myMethod as shown
*/
System.out.println("Please enter a root to be calculated:");
root = data.nextDouble();
double actual = root;
sqrt(root);
sqrt_(actual);
System.out.println(root);
System.out.println(actual);
/*
* Close input and output streams
*/
}
/**
* Computes estimate of square root of x to within relative error 0.01%.
*
* #param x
* positive number to compute square root of
* #return estimate of square root
*/
private static double sqrt(double x) {
double epilson = 0.0001;
double approx = 1;
int count = 0;
while ((Math.abs(approx - (x / approx)) > (0.0001 * approx))
&& (count < 100)) {
approx = 0.5 * (approx + (x / approx));
count++;
}
return approx;
}
public static double sqrt_(double c) {
if (c < 0) {
return Double.NaN;
}
double EPS = 1E-15;
double t = c;
while (Math.abs(t - c / t) > EPS * t) {
t = (c / t + t) / 2.0;
}
return t;
}
}
You are simply forgetting to assign your return values.
root = sqrt(root);
actual = sqrt_(actual);
This question already has answers here:
How to add a new method called numberOfDigits() in java?
(4 answers)
Closed 9 years ago.
i posted a question similar to this one but I still can't figure how to code this little part. Can someone please tell me how I can add a new method named "numberOfDigits"and a line to test it in the main() method . Below is the code I came up for numberOfZeros. To be more specific, all I want to know is how I can add numberOfDigits to this.
import java.util.*;
public class ZeroCounter {
public static void main(String[] args)
{
System.out.println("Enter a nonnegative number:");
Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt( ) ;
System.out.println(number + " contains " + numberOfZeros(number) + " zeros.");
} // End of main
// * * * * Recursive Method * * * *
public static int numberOfZeros(int n) {
n = Math.abs(n); // Make sure the number is not negative.
// 1. STOPPING CONDITION: Number has only only digit.
if ( n < 10 ) {
// if( n == 0 ) return 1; else return 0;
return n==0 ? 1: 0 ; // Conditional operator.
} // end of the outer if block handling the stopping condition.
// 2. Else handle the case of two or more digits using recursion.
else {
return n%10 == 0 ? 1 + numberOfZeros(n/10): numberOfZeros(n/10) ; // Conditional operator.
// if (n%10 == 0) return 1 + numberOfZeros(n/10);
// else return numberOfZeros(n/10);
} // end of outer else block
} // end of recursive method method numberOfZeros. * * * * * * * *
// * * * * Non-recursive method using a while loop. * * * *
public static int numberOfZeros(int n)
{
if (n<0) n = -n;
if (n == 0) return 1; // Handle the special case of n = 0.
int zeros = 0; // The variable "zeros" will keep track of the number of zeros.
while (n > 0) { if(n%10==0) zeros++; n = n/10; }
return zeros;
} // End of NON_RECURSIVE method numberOfZeros.
// End of multiline comment below.
*/
} // end of class
int noOfDigits = (int) Math.log10(n) + 1;