Printing pattern a pattern in java [duplicate] - java

This question already has answers here:
Java algorithm to make a straight pyramid [closed]
(4 answers)
How to print this pyramid pattern?
(5 answers)
Logic behind printing pyramid shape using nested for loops in Java
(1 answer)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I tried to print the below pattern in java
***1***
**2*2**
*3*3*3*
4*4*4*4
like this way
public class Sample {
public static void main(String[] args) {
int m, n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of rows");
m = s.nextInt();
System.out.println("Enter the no of columns");
n = s.nextInt();
s.close();
//Printing the number of rows
for (int i = 1; i <= m; i++) {
//printing number of columns
for (int j = n; j > 0; j--) {
//Printing values in the pattern
for (int k = 0; k < j; k++) {
if (k == j / 2)
System.out.print(i);
}
System.out.print("*");
}
System.out.print("\n");
}
}
}
I am facing problem at the logic of finding the positions to print the values in each row. Its asked at my previous interview.

Try to figure out a formula when the asterisk(*) is replaced with number.
Hint1: the formula depends on the distance of the given symbol from the middle of the row
Hint2: the formula depends on the remainder modulo 2 of the position in the current row(and the number of the row too)
The formula is simple enough if you note the two dependencies I mention above.

we can write logic based on the output. Right now you are passing the value row = 4 and column =7. For that you have provided output. Based on that I have written this program, which output matching with that, we can modify/tune this program also:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
int m, n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of rows");
m = s.nextInt();
System.out.println("Enter the no of columns");
n = s.nextInt();
s.close();
String[][] str = new String[m][n];
int frontPos = 0;
int backPos = n-1;
for (int i=0; i<m; i++){
int l = Math.round((n)/(i+2));
if(i==(m-1)){
frontPos = 0;
backPos = n-1;
} else {
frontPos = l;
backPos = n-1-l;
}
//System.out.println("Difference =="+frontPos);
boolean contFlag = false;
do{
//System.out.println("frontPos=="+frontPos+"|backPos=="+backPos);
if(frontPos == backPos){
str[i][frontPos] = new Integer(i+1).toString();
} else if(frontPos < backPos){
str[i][frontPos] = new Integer(i+1).toString();
str[i][backPos] = new Integer(i+1).toString();
}
if((backPos-frontPos) > l){
contFlag = true;
frontPos = frontPos + (l+1);
backPos = backPos -(l+1);
} else {
contFlag = false;
}
} while(contFlag);
//System.out.print("\n");
}
for(int a=0; a<m; a++){
for(int b=0; b<n; b++){
if(str[a][b]==null){
System.out.print("*");
} else {
System.out.print(str[a][b]);
}
}
System.out.print("\n");
}
}
}

Related

Compilation Error at Enhanced For-Loop. i is already defined in main method but I need integer i for the for loop [duplicate]

This question already has answers here:
Java: Variable is already defined in method
(4 answers)
Closed 12 months ago.
Hello StackOverflow Community.
I was working on a Java program using Arrays and 12 integer inputs to then find evens, odds, and negatives and separate them into 3 different arrays.
The program looks as though it should compile and run as intended but it gives me an error at the enhanced for loop saying that variable i is already defined in method main(java.lang.String[])
I already looked at this post and it did not help me with my for-loop issue.
Java: Variable is already defined in method
Here is the program:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
int i = 0;
for (i = 0; i < twelveInt.length; i++) {
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt [i] = in.nextInt();
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
Any help with this strange bug is greatly appreciated.
int i = 0;
for (i = 0; i < twelveInt.length; i++) {
Change it to this:
for (int i = 0; i < twelveInt.length; i++) {

Storing output of a nested loop as new array - Java

I need to find the largest prime number of a given array when adding two numbers in an array,so I decided to add all possible sums first and displayed it. Now I want to take those output elements to a new array.Please help me solve this problem.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int noOfElem = scanner.nextInt();
int[] array = new int[noOfElem];
int[][] newArray = new int[5][4];
int i=0;
while(scanner.hasNextInt()){
array[i] = scanner.nextInt();
i++;
if(i == noOfElem){
break;
}
}
for (int a = 0; a < array.length; a++)
{
for (int b = a+1; b < array.length; b++) {
int m = array[a] + array[b];
newArray[a][b] =
}
}
}
}
Not quite sure what the problem is here, just do
newArray[a][b] = m;
This stores all sums of all 'a's and 'b's such that newArray[a][b] is the sum of array[a] + array[b]

Loop inside Loop in Java (simple)

I am doing an exercise where I have to print 'x' (is an input) rows of numbers incrementing from 0 to 10.
If I input 3, the output should look like this
012
345
678
012
345
678
012
345
678
but instead, I get 3 rows of a 0 to 10 count.
I know it might be easy to code, but I am stuck in that!
I think I am not undestanding well the nested loops :(
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
}
}
}
You don't need two loops for this. All you need is to print a newline after every 3rd letter and an extra newline after every 3rd line. Your code can be like:
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
int lines = 0;
int letters = 0;
while (lines < q) {
System.out.print(i);
if (letters && letters % q == 0) {
System.out.println();
lines++;
}
if (lines && lines % q == 0) {
System.out.println();
letters = 0;
continue;
}
letters++;
}
}
PS: I haven't tried this code myself. But concept would be the same.
The answer above should solve your problem so I will try to explain what your code does.
Let's start with code inside first for loop:
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
First we have a loop iterating through numbers from 0 to 10 and the output is:
012345678910
and a new line after that.
That means that output of your program will print above mentioned output q times.
012345678910
012345678910
012345678910
You can try with below code
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i < 9; i++) {
if(i%3 == 0)
System.out.println();
System.out.print(i);
}
System.out.println();
}
}
}
Print X quandrants of X rows and X columns each
Scanner in = new Scanner(System.in);
int q = in.nextInt();
// q quadrants
for (int iQuadrat = 0; iQuadrat < q; iQuadrat++) {
// count will keep track of the last number you print
int count = 0;
// q rows
for (int iRow = 0; iRow < q; iRow++) {
// q cols
for (int iCol = 0; iCol < q; iCol++) {
System.out.print(count);
// increment the count and take its modulo 10 so it stays between 0 and 9
count = (count+1)%10;
}
// line return at the end of the row
System.out.println();
}
// line return between quadrants
System.out.println();
}
For an input of 12, it will print 12 times this quadrant
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123

2D array and method calling

So, I'm creating this minesweeper game and I am confused with 2 of my methods which one, will initialize the array with a certain character and one method will actually print the game. Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = 0;
int b = 0;
System.out.println("Welcome to Mine Sweeper!");
a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);
eraseMap(new char[b][a]);
simplePrintMap(new char[b][a]);
}
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userInput;
System.out.println(prompt);
userInput = in.nextInt();
while (userInput < min || userInput > max) {
System.out.println("Expected a number from 3 to 20.");
userInput = in.nextInt();
}
return userInput;
}
public static void eraseMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
map[i][j] = (Config.UNSWEPT);
}
}
return;
}
public static void simplePrintMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
System.out.print(map[b][a] + " ");
}
System.out.println();
}
return;
}
The methods that are in question is eraseMap and simplePrintMap. eraseMap is supposed to initialize the array with "." and simplePrintMap is supposed to actually print the array. So if i input 3 and 4, it will print periods will a width of 3 and height of 4.
(each period separated by space).
A) You create 2 seperate maps. You perform the erase on the first, then throw it all away, create a new map and print that. Which, of course, is empty.
Try creating one map and work on it:
char[][] map = new char[b][a]
eraseMap(map);
simplePrintMap(map);
B) in the print method, you use the wrong indices:
System.out.print(map[b][a] + " ");
change these to
System.out.print(map[i][j] + " ");
C) not an error, just a hint: you don't need return; at the end of void methods.

Java Shortest Path general solution

The 'p' is the number of nodes. So now in my solution the user has to type in all the matrix elements, in case of 7 nodes, 49 numbers. I don't want it this way. I would like to ask the user the distances from one point to the other. Sorry for the weird names in my program, they're in my language. latogatott = visited, tav=distance
package legrovidebb_ut;
import java.util.Scanner;
public class Legrovidebb_ut {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Adja meg a pontok szamat: ");
int p;
p = scan.nextInt( );
int[][] matrix = new int [p][p];
int[] tav = new int[p];
int[] latogatott = new int[p];
int[] pre = new int[p];
int min;
int nextNode = 0;
System.out.println("Enter the matrix!");
for (int i=0; i<p; i++){
latogatott[i]=0;
pre[i]=0;
for (int j=0;j<p;j++){
matrix[i][j] = scan.nextInt();
if(matrix[i][j]== 0)
matrix[i][j]=999;
}
}
tav = matrix[0];
tav[0]=0;
latogatott[0]=1;
for (int i=0;i<p;i++){
min=999;
for(int j=0;j<p;j++){
if(min>tav[j] && latogatott[j]!=1){
min=tav[j];
nextNode=j;
}
}
latogatott[nextNode]=1;
for(int c=0;c<p;c++){
if(latogatott[c]!=1){
if(min+matrix[nextNode][c]<tav[c]){
tav[c]=min+matrix[nextNode][c];
pre[c]=nextNode;
}
}
}
}
for (int i=0;i<p;i++){
System.out.print("|" + tav[i]);
}
System.out.println("|");
for(int i=0;i<p;i++){
int j;
System.out.print("Ut: " + (i+1));
j=i;
do{
j=pre[j];
System.out.println(" <- " + (j+1));
}while(j!=0);
System.out.println();
}
}
}
If your graph is undirected and you want the user to input the distances between each two nodes (as stated in your comment), you will need a loop through all your nodes and another loop through all the other nodes, as a distance for 2-1 is not needed if you have a distance for 1-2:
for(int i = 0; i < p; i++) {
for(int k = i+1; k < p; k++) {
// ask user for distance between i and k
}
}

Categories

Resources