I want create a power pyramid of “*” with Java. - java

Input: base=2, row = 3
Output:
**
****
********
Input: base=3, row = 3
Output:
***
*********
***************************
I have tried this way, but I spaces aren't printing properly.
import java.util.Scanner;
public class loops {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();
System.out.println("enter height:");
int h = s.nextInt();
for (int i = 1; i <= h; i++) {
int num = (int)Math.pow(base, i);
for(int n=h-1; n>i-1; n--) {
System.out.print(" ");
}
for (int j = 0; j < num; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}

import java.util.Scanner;
public class loops {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();
System.out.println("enter height:");
int h = s.nextInt();
int spacesNum;
int asterisksNum;
for (int i = 1; i <= h; i++) {
spacesNum = (int) ((Math.pow(base, h) - Math.pow(base, i)) / 2);
asterisksNum = (int) (Math.pow(base, i));
for (int j = 0; j < spacesNum; j++) {
System.out.print(" ");
}
for (int j = 0; j < asterisksNum; j++) {
System.out.print("*");
}
System.out.println();
}
s.close();
}
}

The width of space grows geometrically, just like the width of the rings, but in the opposite direction -- it's decaying. Probably the easiest way to code it is to think about the total width, and what you're taking away from it with each ring.
Your code with that taken into account:
public class loops {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();
System.out.println("enter height:");
int h = s.nextInt();
int width = (int) Math.pow(base, h); // Note the total width.
for (int i = 1; i <= h; i++) {
int num = (int) Math.pow(base, i);
// The space is half of what's left after removing the ring.
for(int j = 0; j < (width - num)/2; j++) {
System.out.print(" ");
}
for (int j = 0; j < num; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}

Your code calls System.out.print method exponential times, one call per character.
Also, System.out.println is invoked in every iteration which causes the underlying stream to flush. (refer links from michaelt in the comments).
This SO answer is a good reference.
This is NOT good approach because:
h number of I/O operations are performed, which is expensive.
So many method invocations of print and println reduces the readability of the code.
Compose the strings in a separate method and use System.out.print only for printing.
Please refer the code below:
public static void main(String[] args) {
//your code here
int totalWidth = (int) Math.pow(base, h);
String output = "";
for (int i = 1; i <= h; i++) {
int numOfStars = (int) Math.pow(base, i);
int numOfSpace = (int) ((totalWidth - numOfStars) / 2);
output += composeString(' ', numOfSpace).concat(composeString('*', numOfStars ).concat("\n"));
}
System.out.println(output);
}
//Method to create String with same character repeated X number of times
public static String composeString(char character, int x) {
StringBuilder buf = new StringBuilder(x);
while (buf.length() < x) {
buf.append(character);
}
return buf.toString();
}

Related

Take in a positive integer n Create n triangles in stars with their bases below of size n each

Help with this question:
Take a positive integer n and form n triangles from stars with their base down of size n each.
For example, for input 3, the following output will be obtained:
* * *
** ** **
*** *** ***
Here's what I've tried.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
for (int c = 1; c <= r; c++)
System.out.print("*");
System.out.println();
}
}
}
Here's my solution, with explanations in comments
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)) {
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) { // <-- we will have to print n rows
printLine(n, r);
}
}
}
static void printLine(int n, int lineNumber) {
StringBuffer line = new StringBuffer();
for(int i = 0; i < n; i ++) { // <-- each line will have '*'s for n triangles
for(int j = lineNumber; j > 0; j--) { // <-- each line has as many '*'s as its line number, so print those first
line.append("*");
}
for(int j = 0; j < n - lineNumber + 1; j ++) { // <-- we then have to add enough spaces to leave room for the next triangle's '*'s
line.append(" ");
}
}
System.out.println(line.toString()); // <-- print the line we've built so far
}
}
EDIT:
Here's a replit that avoids one of the loops by using a modulo to print an entire line at once, and also uses recursion, for no real reason, in place of the outer-most loop: https://replit.com/#anqit/MicroExtrovertedTrace#Main.java
First, the blanks follow the stars, then, you have to repeat n times the two loops:
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++)
System.out.print("*");
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
}
System.out.println();
}
You have one for loop that prints out a single triangle of stars using nested for loops. The outer loop is responsible for the number of rows and the inner loops are responsible for printing the spaces and stars.
In my updated code, I added an outer loop that runs n times, and each time it runs, it prints out a triangle of stars. The inner loops are responsible for printing the stars of the triangle and spaces between the triangles.
The main difference is that in your first code, only one triangle is printed, while in my updated code, n triangles are printed. In addition, the indentation of the inner loops has been adjusted to align the triangles correctly on the same line.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n:");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error: please enter a positive number:");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++) {
System.out.print("*");
}
for (int i = 0; i < n - r + 1; i++) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Here is a 3 forloop variant
int n = 4;
for (int i = 1; i <= n; i++) {
StringBuilder b = new StringBuilder("");
for (int s = 0; s < n; s++) {
b.append(s < i ? "*" : " ");
}
String line = b.append(" ").toString();//space between
for (int j = 1; j < n; j++) {
System.out.print(line);
}
System.out.println();
}
produces
> * * *
> ** ** **
> *** *** ***
> **** **** ****

Rhombus with letters - Java

I am new to programming and started with learning c# and now java. I came across a task creating a rhombus where the user inputs the height (odd numbers only) and the char for the rhombus.
I created a for loop for the height and another loop for the characters. Here is my output:
h: 7
c: k
k
jkj
ijkji
hijkjih
ghijkjihg
But I want the output to be:
h: 7
c: k
k
jkj
ijkji
hijkjih
ijkji
jkj
k
How can I develop my logic to apply it to my code.
Here is my code:
Scanner in = new Scanner(System.in);
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
if(h%2==0){
System.out.println("Invalid number!");
return;
}
int count = 1;
int space = 1;
for (int i = 2; i < h; i++)
{
for (int spc = h - space; spc > 0; spc--)
{
System.out.print(" ");
}
if (i < h)
{
space++;
}
else {
space--;
}
for (int j = 0; j < count; j++)
{
System.out.print(c);
if (j < count/2)
{
c++;
}
else {
c--;
}
}
if (i < h)
{
count = count + 2;
}
else {
count = count - 2;
}
System.out.println();
}
Any help is highly appreciated.
Your code contains the following flaws:
count and space variables depend on the values of i and h, which makes it very hard to keep track of and understand. You should avoid hidden dependencies in your code in general
you change the value of c all the time. It makes it very hard to keep track of. You should never change its value
your function is too big
strange values like i = 2, count/2, incrementing by 2
incorrect conditions
You have one loop which increments i. What you need is a second loop which decrements the value of i. And you should also use the same approach for printing of the characters (2 loops for both sides). Let me show you:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// load parameters
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
// validate parameters
if (h % 2 == 0) {
System.out.println("Invalid number!");
return;
}
for(int i = 0; i <= h/2; i++) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
for(int i = h/2-1; i >= 0; i--) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
}
private static void printLine(char character, int sideWidth) {
for (int j = sideWidth; j >= 0; j--)
System.out.print((char) (character - j));
for (int j = 1; j <= sideWidth; j++)
System.out.print((char) (character - j));
}
private static void printSpaces(int numberOfSpaces) {
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
}
which gives you the desired output.
public class Rhombusstar
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter N : ");
int n=sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(int j=1;j<=n;j++)
{
System.out.print(c);
}
System.out.println();
}
}
}

Given number n, find the factorial of that number

Output is wrong it just multiplying second number with itself.
import java.util.Scanner;
public class trybew {
void factorial(int n) {
long fact = 1;
for(int i=1; i<=n; i++) {
fact *= n;
System.out.println(" "+fact);
}
}
public static void main(String[] args) {
int cnt;
trybew f1= new trybew();
Scanner s= new Scanner(System.in);
System.out.println("Enter Test case ");
cnt=s.nextInt();
int n[]= new int[cnt];
for(int i=0; i<cnt; i++) {
System.out.println("ENter NO:: ");
n[i]=s.nextInt();
}
for(int i=0; i<cnt; i++)
f1.factorial(n[i]);
}
}
void factorial(int n) {
long fact = 1;
for(int i=n; i>=1; i--)
fact *= i;
System.out.println(" "+fact);
}
Your mistake is with your code fact *= n; . You are supposed to use i here.
Change
fact *= n;
To
fact *= i;
Modified code :-
import java.util.Scanner;
public class trybew {
void factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i; // not *=n
System.out.println(" " + fact);
}
}
public static void trybew(String[] args) {
int cnt;
trybew f1 = new trybew();
Scanner s = new Scanner(System.in);
System.out.println("Enter Test case ");
cnt = s.nextInt();
int n[] = new int[cnt];
for (int i = 0; i < cnt; i++) {
System.out.println("ENter NO:: ");
n[i] = s.nextInt();
}
for (int i = 0; i < cnt; i++)
f1.factorial(n[i]);
}
}
Output :-
Enter Test case
2
ENter NO::
4
ENter NO::
5
1
2
6
24
1
2
6
24
120
It is better to use System.out.println(" " + fact); outside the for-loop in function void factorial(int n) .

Improve performance of reversing array

I am trying to solve question at Reverse Game
When I submit my code, in some of the testcases it is getting timeout.
I think problem may be in reverseSubArray() method but I am not sure how to improve performance here.
Following is my code:
public class ReverseGame
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
int[] numberOFBalls = new int[testCases];
int[] ballNumberArray = new int[testCases];
for (int i = 0; i < testCases; i++)
{
numberOFBalls[i] = scanner.nextInt();
ballNumberArray[i] = scanner.nextInt();
}
for (int i = 0; i < testCases; i++)
{
process(numberOFBalls[i], ballNumberArray[i]);
}
scanner.close();
}
private static void process(int totalNumberOFBalls, int ballNumber)
{
int[] ballsArray = new int[totalNumberOFBalls];
int maximumNumberOnBall = totalNumberOFBalls - 1; // This is because
// balls are numbered
// from 0.
// As the first step is to reverse the Balls arrangement, So insert into
// ballsArray in descending order of index.
for (int i = 0; i < totalNumberOFBalls; i++)
ballsArray[i] = maximumNumberOnBall--;
for (int i = 1; i < totalNumberOFBalls; i++)
{
ballsArray = reverseSubArray(ballsArray, i);
}
int position = findPosition(ballsArray, ballNumber);
System.out.println(position);
}
private static int[] reverseSubArray(int[] a, int fromIndex)
{
int temp = 0, counter = 1;
int midIndex = (a.length - fromIndex) / 2;
for (int i = fromIndex; i < fromIndex + midIndex; i++)
{
temp = a[a.length - (counter)];
a[a.length - (counter)] = a[i];
a[i] = temp;
counter++;
}
/*
* System.out.println(); for (int i = 0; i < a.length; i++)
* System.out.print(a[i] + " ");
*/
return a;
}
private static int findPosition(int[] ballsArray, int ballNumber)
{
for (int i = 0; i < ballsArray.length; i++)
{
if (ballsArray[i] == ballNumber)
return i;
}
return 0;
}
}
The time complexity of your solution is O(n ^ 2). It is too slow for n = 10 ^ 5. So you need to use a better algorithm. Here is simple linear solution which uses the fact that we do not need to know the positions of all balls(we need only the k-th):
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int testsCount = in.nextInt();
for (int t = 0; t < testsCount; t++) {
int n = in.nextInt();
int k = in.nextInt();
// Simulates all rotations,
// but keeps track only of the k-th ball.
// It does not matter what happens to the others.
for (int i = 0; i < n; i++)
if (k >= i)
k = i + n - 1 - k;
out.println(k);
}
out.flush();
}
}
This solution has an O(n) time complexity and easily passes all test cases.
It is actually possible to find the positions of all balls in linear time, but it is not required here.

Make smaller christmas tree

So I'm beginning in the world of java programming language and I'm trying to print a christmas tree of X height. So far its working, but if for example the user input 4, it will print 4 rows + the christmas tree stump, wich mean 5. However, I would like it to be 4 INCLUDING the stump.So far I have this:
public class xmas {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
I don't know how to do that. Thanks!
Try using temp-- just after the input, like that:
int temp = scan.nextInt();
temp--;
Or decreasing your loop condition:
for(int i=0; i<temp-1; i++)
Output in both cases:
*
***
*****
*
If you just subtract one from the input, your christmas tree should be the right size. Here's what it would look like (using the Java style conventions):
public class ChristmasTree {
public static void main(String[] args) {
Scanner scanner = new Scanner(in);
out.print("Please enter a number: ");
int temp = scanner.nextInt() - 1; // note the `- 1`
int x = (temp - 1) * 2 + 1;
int y = x / 2;
int z = 1;
for(int i = 0; i < temp; i++) {
for(int j = 0; j <= y; j++) {
out.print(" ");
}
for(int j = 0; j < z; k++) {
out.print("*");
}
out.println();
y--;
z += 2;
}
for(int i =0; i<=x/2; i++) {
out.print(" ");
}
out.println("*");
}
}

Categories